<?php


namespace App\Http\Controllers\report;

use App\Fun\Fun;
use App\Model\pos\SaleDetailsModel;
use App\Model\product\ProductUnitModel;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\pos\SaleModel;
use session;
use DB;
use Auth;
use DataTables;

class ReportSaleController extends Controller

{
    function __construct()
    {
        $this->middleware('permission:Report Sales List', ['only' => ['index']]);
    }

    public function index()
    {
        Fun::lang();
        $user = SaleModel::where('is_role', '!=', 'seller')->groupBy('user_id')->pluck('user_id');
        $user = User::whereIn('id', $user)->pluck('name', 'id');
        $type = SaleModel::pluck('sale_type', 'sale_type');
        $report_type = 'user';
        return view('report.sale-report.index', compact('type', 'user', 'report_type'));
    }

    public function sale_request()
    {
        Fun::lang();
        $user = SaleModel::where('is_role', 'seller')->groupBy('user_id')->pluck('user_id');
        $user = User::whereIn('id', $user)->pluck('name', 'id');
        $type = SaleModel::pluck('sale_type', 'sale_type');
        $report_type = 'seller';
        return view('report.sale-report.index', compact('type', 'user', 'report_type'));
    }

    public function get_sale(Request $request)
    {
        if ($request->ajax()) {
            $customer = $request->customer_id;
            $type = $request->type;
            $user_id = $request->user_id;
            $from_date = $request->start_date;
            $to_date = $request->end_date;
            $report_type = $request->report_type;
            $data = SaleModel::where('is_role', $report_type)
                ->where('nso007_sales.status', 1)
                ->where(function ($query) use ($from_date, $to_date) {
                    if($from_date&& $to_date){
                        $query->whereBetween('nso007_sales.sale_date', [sDate($from_date).' 00:00:00',sDate($to_date).' 23:59:59']);
                    }
                })
                ->where(function ($q) {
                    $mybr = myBranch();
                    if (!auth()->user()->can('View Sale Request All Branch')) {
                        $q->where('nso007_sales.user_id', auth()->id());
                    }
                    if (!$mybr->main) {
                        $q->where('nso007_sales.branch_id', $mybr->id);
                    }
                })
                ->where(function ($query) use ($user_id) {
                    if ($user_id) {
                        $query->where('nso007_sales.user_id', $user_id);
                    }
                })
                ->where(function ($query) use ($customer) {
                    if ($customer) {
                        $query->where('nso007_sales.customer_id', $customer);
                    }
                })
                ->where(function ($query) use ($type) {
                    if ($type) {
                        $query->where('nso007_sales.sale_type', $type);
                    }
                })->orderBy('nso007_sales.id', 'DESC');
            return Datatables::of($data)
                ->addColumn('amount', function ($sales) {
                    $sales->symbol = findCurrency($sales->currency_id)->symbol ?? '';
                    $total = $sales->grand_total;
                    $input = '<span data-cur_id="' . ($sales->currency_id) . '" data-amount="' . $total . '" ></span>';
                    return $sales->symbol . number_format($total, 2) . $input;
                })
                ->addColumn('sale_type', function ($sales) {
                    Fun::lang();
                    return __('administrator.' . $sales->sale_type);
                })
                ->addColumn('sale_date', function ($sales) {
                    return date('d-m-Y', strtotime($sales->sale_date));
                })
                ->editColumn('customer_id', function ($sales) {
                    return $sales->customer->name ?? '';
                })
                ->addColumn('customer_phone', function ($sales) {
                    return $sales->customer->phone ?? '';
                })
                ->editColumn('user_id', function ($sales) {
                    return findUser($sales->user_id)->name;
                })
                ->editColumn('payment_status', function ($sales) {
                    return checkPaymentStatus($sales->payment_status);
                })
                ->addColumn('invoice_number', function ($sales) {
                    return '<a data-href="' . route("get-wholesale-invoice", $sales->id) . '" title="Show" class="show_invoice text-primary cursor-pointer ">' . $sales->invoice_number . '</a>';
                })
                ->addColumn('delivery_fee', function ($data) {
                    if ($data->delivery_fee)
                        return $data->symbol . number_format($data->delivery_fee, 2) . ($data->delivery_fee_by ? (' - ' . getFeeBy($data->delivery_fee_by)) : '');
                })
                ->addColumn('more_fee', function ($data) {
                    if ($data->more_fee)
                        return $data->symbol . number_format($data->more_fee, 2) . ($data->reason_fee ? " ( $data->reason_fee )" : '');
                })
                ->addIndexColumn()
                ->rawColumns(['invoice_number', 'payment_status', 'amount', 'customer_phone'])
                ->make(true);
        }
    }

    public function sale_detail(Request $request)
    {
        $type = SaleModel::pluck('sale_type', 'sale_type');
        $seller = SaleModel::where('status', '1')->pluck('user_id');
        $seller = User::whereIn('id', $seller)->pluck('name', 'id');
        if ($request->ajax()) {
            $type = $request->type;
            $customer = $request->customer_id;
            $product = $request->product_id;
            $seller = $request->user_id;
            $from_date = $request->start_date;
            $to_date = $request->end_date;
            $branch_id = $request->branch_id;
            $data = SaleDetailsModel::select('nso007_sales.invoice_number', 'nso007_sales.currency_id',
                'nso007_sales.customer_id', 'nso007_sales.sale_date', 'nso007_sales.discount', 'nso007_sales.sale_type', 'nso007_sales.rate',
                'nso007_sales.user_id', 'nso007_sale_details.*', 'nso007_sales.branch_id', 'nso007_products.product_name')
                ->join('nso007_sales', 'nso007_sales.id', 'nso007_sale_details.sale_id')
                ->join('nso007_products', 'nso007_products.id', 'nso007_sale_details.product_id')
                ->where(['nso007_sales.status' => 1, 'nso007_sale_details.status' => 1])
                ->where(function ($query) use ($customer) {
                    if ($customer) {
                        $query->where('nso007_sales.customer_id', $customer);
                    }
                })
                ->where(function ($query) use ($from_date, $to_date) {
                    if ($from_date) {
                        $query->whereDate('nso007_sales.sale_date', '>=', date('Y-m-d', strtotime($from_date)));
                    }
                    if ($to_date) {
                        $query->whereDate('nso007_sales.sale_date', '<=', date('Y-m-d', strtotime($to_date)));
                    }
                })
                ->where(function ($query) use ($product) {
                    if ($product) {
                        $query->where('nso007_sale_details.product_id', $product);
                    }
                })

                ->where(function ($query) use ($branch_id) {
                    if ($branch_id) {
                        $query->where('nso007_sales.branch_id', $branch_id);
                    }
                })
                ->where(function ($query) use ($seller) {
                    if ($seller) {
                        $query->where('nso007_sales.user_id', $seller);
                    }
                })
                ->where(function ($query) use ($type) {
                    if ($type) {
                        $query->where('nso007_sales.sale_type', $type);
                    }
                })
                ->where(function ($q) {
                    $mybr = myBranch();
                    if (!auth()->user()->can('View Sale Request All Branch')) {
                        $q->where('nso007_sales.user_id', auth()->id());
                    }
                    if (!$mybr->main) {
                        $q->where('nso007_sales.branch_id', $mybr->id);
                    }
                })
                ->orderBy('nso007_sales.sale_date', 'DESC');
            return Datatables::of($data)
                ->addColumn('amount', function ($sales) {
                    $currency = findCurrency($sales->currency_id);
                    $sales->currency = $currency->symbol??'';
                    return ($sales->currency) . number_format($sales->item_grand_total, 2) .
                        '<span data-cur_id="' . ($currency ? $currency->id : '') . '" data-amount="' . $sales->item_grand_total . '" data-rate="' . $sales->rate . '"></span>';
                })
                ->addColumn('sale_type', function ($sales) {
                    return __('administrator.' . $sales->sale_type);

                })
                ->addColumn('sale_date', function ($sales) {

                    return date('d-m-Y', strtotime($sales->sale_date));

                })
                ->editColumn('user_id', function ($sales) {
                    return findUser($sales->user_id)->name;

                })
                ->editColumn('product_name', function ($sales) {
                    $size = findSize($sales->size_code)->size ?? '';
                    $color = findColor($sales->color_code)->name ?? '';
                    return $sales->product_name . ' ( ' . ($size . ',' . $color) . ' )';
                })
                ->editColumn('customer_id', function ($sales) {

                    $customer = findCustomer($sales->customer_id);
                    return $customer ? $customer->name : '';
                })
                ->addColumn('branch_id', function ($sales) {
                    $br = findBranch($sales->branch_id);
                    return $br ? $br->name : '';
                })
                ->addColumn('qty', function ($sales) {
                    return $sales->qty . ' ' . findUnit($sales->unit_id)->unit_name_en;
                })
                ->addColumn('dis', function ($sales) {
                    return $sales->dis ? ("$sales->dis $sales->currency") : 0;
                })
                ->addColumn('total_discount', function ($sales) {
                    return $sales->total_discount_in_cash ? ("$sales->total_discount_in_cash $sales->currency") : 0;
                })
                ->addColumn('sale_price', function ($sales) {
                    $id = findSale($sales->sale_id)->currency_id;
                    return findCurrency($id)->symbol . $sales->sale_price;
                })
                ->addIndexColumn()
                ->rawColumns(['action' ,'total_discount', 'customer_phone' => 'customer_phone', 'amount' => 'amount'])
                ->make(true);

        }

        return view('report.sale-report.sale-detail', compact('type', 'seller'));

    }

    public function sale_by_seller(Request $request)
    {
        $type = SaleModel::pluck('sale_type', 'sale_type');
        $seller = SaleModel::where('status', '1')->pluck('user_id');
        $seller = User::whereIn('id', $seller)->pluck('name', 'id');
        if ($request->ajax()) {
            $customer = $request->customer_id;
            $product = $request->product_id;
            $seller = $request->user_id;
            $branch_id = $request->branch_id;
            $start = Carbon::now()->startOfMonth()->toDateString();
            $end = Carbon::now()->endOfMonth()->toDateString();
            $from_date = $request->start_date ? $request->start_date : $start;
            $to_date = $request->end_date ? $request->end_date : $end;
            $data = SaleDetailsModel::selectRaw('
            nso007_sales.invoice_number,
            nso007_sales.branch_id,
            nso007_sales.currency_id,
            nso007_sales.customer_id,
            nso007_sales.sale_date,
            nso007_sales.sale_type,
            nso007_sales.rate,
            nso007_sales.user_id,
            nso007_sale_details.*,
            SUM(nso007_sale_details.qty) as sale_qty ,
            SUM(nso007_sale_details.item_grand_total) as total_amount_gen')
                ->join('nso007_sales', 'nso007_sales.id', 'nso007_sale_details.sale_id', 'nso007_sales.currency_id')
                ->where(['nso007_sales.status' => 1, 'nso007_sale_details.status' => 1])
                ->where(function ($query) use ($customer) {
                    if ($customer) {
                        $query->where('nso007_sales.customer_id', $customer);
                    }
                })
                ->where(function ($query) use ($from_date, $to_date) {
                    if($from_date&& $to_date){
                        $query->whereBetween('nso007_sales.sale_date', [sDate($from_date).' 00:00:00',sDate($to_date).' 23:59:59']);
                    }
                })
                ->where(function ($query) use ($product) {
                    if ($product) {
                        $query->where('nso007_sale_details.product_id', $product);
                    }
                })
                ->where(function ($query) use ($seller) {
                    if ($seller) {
                        $query->where('nso007_sales.user_id', $seller);
                    }
                })
                ->where(function ($query) use ($branch_id) {
                    if ($branch_id) {
                        $query->where('nso007_sales.branch_id', $branch_id);
                    }
                })
                ->groupBy('nso007_sale_details.product_id')
                ->groupBy('nso007_sales.user_id')
                ->groupBy('nso007_sales.currency_id')
                ->orderBy('nso007_sale_details.barcode', 'DESC');

            return Datatables::of($data)
                ->addColumn('total_amount', function ($sales) {
                    $currency = findCurrency($sales->currency_id);
                    $sales->total_amount = $sales->total_amount_gen??$sales->total_amount;
                    return ($currency ? $currency->symbol : '') . number_format($sales->total_amount, 2) .
                        '<span data-cur_id="' . ($currency ? $currency->id : '') . '" data-amount="' . $sales->total_amount . '" data-rate="' . $sales->rate . '"></span>';
                })
                ->addColumn('sale_date', function ($sales) use ($from_date, $to_date) {
                    return myDate($from_date) . ' -> ' . myDate($to_date);
                })
                ->editColumn('user_id', function ($sales) {
                    Fun::lang();
                    $is_role = strtolower(findUser($sales->user_id)->is_role);
                    if ($is_role) {
                        if ($is_role === 'administrator') {
                            $is_role = 'user';
                        }
                    } else {
                        $is_role = 'user';
                    }
                    return findUser($sales->user_id)->name . ' (' . __('administrator.' . $is_role) . ')';
                })
                ->editColumn('product_id', function ($sales) {
                    return getProductById($sales->product_id)->product_name ?? '';
                })
                ->addColumn('sale_qty', function ($sales) {
                    return $sales->sale_qty . ' ' . findUnit($sales->unit_id)->unit;
                })
                ->addColumn('branch_id', function ($sales) {
                    return findBranch($sales->branch_id)->name ?? '';
                })
                ->addIndexColumn()
                ->rawColumns(['invoice_number', 'customer_phone', 'total_amount'])
                ->make(true);
        }

        return view('report.sale-report.sold-product-by-seller', compact('type', 'seller'));

    }

    public function report_income(Request $request)
    {
        if ($request->ajax()) {
            $from_date = $request->from_date;
            $to_date = $request->to_date;
            $branch_id = $request->branch_id;
            $user_id = $request->user_id;
            $data = SaleModel::selectRaw('
            nso007_sales.id,
            nso007_sales.currency_id,
            nso007_sales.sale_date,
            nso007_sales.rate,
            nso007_sales.invoice_number,
            nso007_sales.branch_id,
            nso007_sales.user_id,
            nso007_sales.delivery_fee,
            nso007_sales.delivery_fee_by,
            nso007_sales.grand_total
            ')
                ->where(['nso007_sales.status' => 1])

                ->where(function ($query) use ($from_date, $to_date) {
                    if ($from_date) {
                        $query->whereDate('nso007_sales.sale_date', '>=', sDate($from_date));
                    }
                    if ($to_date) {
                        $query->whereDate('nso007_sales.sale_date', '<=', sDate($to_date));
                    }
                })
                ->where(function ($query) use ($user_id) {
                    if ($user_id) {
                        $query->where('nso007_sales.user_id', $user_id);
                    }
                })
                ->where(function ($query) use ($branch_id) {
                    $main = myBranch();
                    if ($main->main) {
                        if ($branch_id) {
                            $query->where('nso007_sales.branch_id', $branch_id);
                        }
                    } else {
                        $query->where('nso007_sales.branch_id', $main->id);
                    }
                })->orderBy('nso007_sales.id', 'DESC');
            return Datatables::of($data)
                ->addColumn('sale_date', function ($sales) {
                    return myDate($sales->sale_date);
                })
                ->addColumn('branch_id', function ($sales) {
                    $br = findBranch($sales->branch_id);
                    return $br ? $br->name : '';
                })
                ->addColumn('total_cost', function ($sales) {
                    $sales->symbol = findCurrency($sales->currency_id)->symbol??'';
                    $sales->total_cost =  SaleDetailsModel::where('sale_id',$sales->id)->sum(DB::raw('product_cost*qty'));
                    return "$sales->symbol". (number_format($sales->total_cost, 2));

                })
                ->editColumn('user_id', function ($sales) {
                    return findUser($sales->user_id)->name??'';
                })
                ->editColumn('invoice_number', function ($sales) {
                    return '<a  class="getHtmlFormShow text-primary cursor"  data-width="900px" data-href="' . route("get-wholesale-invoice", $sales->id) . '">' . $sales->invoice_number . '</a>';
                })
                ->addColumn('grand_total', function ($sales) {
                    return $sales->symbol . (number_format($sales->grand_total, 2));
                })
                ->editColumn('delivery_fee', function ($sales) {
                    if ($sales->delivery_fee)
                        return $sales->symbol . number_format($sales->delivery_fee, 2) . ($sales->delivery_fee_by ? (' - ' . getFeeBy($sales->delivery_fee_by)) : '');
                })
                ->addColumn('profit', function ($sales) {
                    $delivery_fee = ($sales->delivery_fee_by==1?$sales->delivery_fee:0);
                    $total_profit = $sales->grand_total-$sales->total_cost-$delivery_fee;
                    return $sales->symbol . number_format($total_profit, 2)."<i class='row_data'
                    data-grand_total='$sales->grand_total'
                    data-total_cost='$sales->total_cost'
                    data-delivery_fee='$delivery_fee'
                    data-total_profit='$total_profit'
                    data-currency_id='$sales->currency_id'
                    ></i>";
                })
                ->addIndexColumn()
                ->rawColumns(['invoice_number', 'action','total_cost','profit'])
                ->make(true);

        }
        $seller = SaleModel::where('status', '1')->pluck('user_id');
        $seller = User::whereIn('id', $seller)->pluck('name', 'id');
        return view('report.sale-report.report-income',compact('seller'));
    }
}

