<?php

namespace App\Http\Controllers\Branch;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Fun\Fun;
use App\Model\CustomerDiscountModel;
use App\Model\CustomerModel;
use App\Model\DiscountModel;
use App\Model\PaymentDetailModel;
use App\Model\PaymentModel;
use App\Model\SaleDetailsModel;
use App\Model\SaleModel;
use App\Model\ProductModel;
use App\Model\ProductUnitModel;
use App\Model\StockModel;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\DataTables;

class SallerRequestController extends Controller
{
    public function index(Request $request)
    {
        Fun::lang();
        if ($request->ajax()) {
            $search = $request->input('search.value');
            $date = $request->date;
            $customer = $request->customer;
            $sale_type = $request->sale_type;
            $status = $request->status;
            $count_total = SaleModel::
            where('is_role', 'out_shop')
                ->where(function ($q) {
                    if (Auth::user()->user_type != 1 && Auth::user()->is_role == 'out_shop') {
                        $q->where('user_id', Auth::user()->id);
                    }
                })
                ->count();
            $count_filter = SaleModel::
            where('is_role', 'out_shop')
                ->where(function ($q) use ($date) {
                    if ($date) {
                        $q->where('sale_date', date('Y-m-d', strtotime($date)));
                    }
                })
                ->where(function ($q) use ($customer) {
                    if ($customer) {
                        $q->where('customer_id', $customer);
                    }
                })
                ->where(function ($q) use ($sale_type) {
                    if ($sale_type) {
                        $q->where('sale_type', $sale_type);
                    }
                })
                ->where(function ($q) use ($status) {
                    if ($status != '') {
                        $q->where('status', $status);
                    }
                })
                ->where(function ($q) {
                    if (Auth::user()->user_type != 1 && Auth::user()->is_role == 'out_shop') {
                        $q->where('user_id', Auth::user()->id);
                    }
                })
                ->count();
            $data = SaleModel::
            where('is_role', 'out_shop')
                ->where(function ($q) use ($date) {
                    if ($date) {
                        $q->where('sale_date', date('Y-m-d', strtotime($date)));
                    }
                })
                ->where(function ($q) use ($customer) {
                    if ($customer) {
                        $q->where('customer_id', $customer);
                    }
                })
                ->where(function ($q) {
                    if (Auth::user()->user_type != 1 && Auth::user()->is_role == 'out_shop') {
                        $q->where('user_id', Auth::user()->id);
                    }
                })
                ->where(function ($q) use ($sale_type) {
                    if ($sale_type) {
                        $q->where('sale_type', $sale_type);
                    }
                })
                ->where(function ($q) use ($status) {
                    if ($status != '') {
                        $q->where('status', $status);
                    }
                })
                ->orderBy('created_at', 'DESC')
                ->take(20);

            return DataTables::of($data)
                ->with([
                    "recordsTotal" => $count_total,
                    "recordsFiltered" => $count_filter,
                ])
                ->editColumn('customer_phone', function ($data) {
                    $customer = findCustomer($data->customer_id);
                    return $customer != null ? $customer->customer_phone : '';
                })
                ->editColumn('customer_id', function ($data) {
                    $customer = findCustomer($data->customer_id);
                    return $customer != null ? $customer->customer_name : '';
                })
                ->editColumn('paid_amount_kh', function ($data) {
                    $total = ($data->paid_amount_kh > 0 ? ($data->paid_amount_kh / $data->rate) : 0) + $data->paid_amount_usd;
                    return '$' . $total;
                })
                ->editColumn('total', function ($data) {
                    return '$' . number_format(generateSubTotal($data), 2);
                })
                ->editColumn('user_id', function ($data) {
                    return findUser($data->user_id)->name;
                })
                ->editColumn('payment_status', function ($data) {
                    return checkPaymentStatus($data->payment_status);
                })
                ->editColumn('delivery_status', function ($data) {
                    return checkRequestStatus($data->delivery_status);
                })
                ->editColumn('status', function ($data) {
                    return checkRequestStatus($data->status);
                })
                ->editColumn('sale_date', function ($data) {
                    return date('d-m-Y', strtotime($data->sale_date));
                })
                ->editColumn('discount', function ($data) {
                    return $data->discount . '%';
                })
                ->editColumn('delivery_fee', function ($data) {
                    if ($data->delivery_fee) {
                        return '$' . $data->delivery_fee;
                    }
                })
                ->addColumn('action', function ($data) {
                    $pending = '';

                    if (Auth::user()->user_type == 1) {
                        if ($data->status == 0) {
                            $pending = '<span class="fa fa-circle" style="color: orange;text-shadow: 0px 0px 2px black"></span>';
                        }
                    }
                    if ($data->seen_at == null) {
                        if (Auth::user()->is_role == 'out_shop') {
                            if ($data->status == 1) {
                                $pending = ' <span class="fa fa-circle" style="color: #00a65a;text-shadow: 0px 0px 2px black"></span>';
                            }

                            if ($data->status == 2) {
                                $pending = ' <span class="fa fa-circle" style="color: #ac2925;text-shadow: 0px 0px 2px black"></span>';
                            }
                        }
                    }
                    return '<a href="' . route("pos-retail.show", $data->id) . '" title="' . __('administrator.show') . '" class="button_info display-none">' . __('administrator.show') . '</a>' .
                        '<a  class="button_primary show_invoice" data-status="' . $data->status . '" data-id="' . $data->id . '" data-type="' . $data->sale_type . '">' . __('administrator.view') . '&nbsp;' . $pending . '</a>';
                })
                ->addIndexColumn()
                ->rawColumns(['action' => 'action', 'total' => 'total', 'status' => 'status', 'customer_id' => 'customer_id', 'payment_status' => 'payment_status', 'customer_phone' => 'customer_phone', 'delivery_status' => 'delivery_status',])
                ->make(true);
        }

        return view('branch.pos.sale-request.index');
    }

    public function update_status(Request $request, $status)
    {
        if ($status == 1) {
            $this->validate($request, [
                'delivery_fee' => 'required',
                'phone' => 'required',
            ]);
        }

        $sale = SaleModel::where('id', $request->id)->where('is_role', 'out_shop')->where('status', 0)->first();
        $saleDetail = getSaleDetail($request->id);
        $count_row = $saleDetail->count();
        $message = '<ul class="text-left">';
        $check_row = 0;
        $count_message = 0;
        $wh_id = getMainWarehouse('item')->id;

        if ($sale != null) {
            if ($status == 1) {
                foreach ($saleDetail as $key => $saleProduct) {
                    // check if all product has enough stock
                    $stock = StockModel::where(['warehouse_id' => $wh_id, 'product_id' => $saleProduct->product_id])->first();
                    $cut_qty = generateSaleCutQty($saleProduct);
                    if ($stock->stock_qty >= $cut_qty) {
                        $check_row++;
                    } else {
                        $count_message++;
                        $message .= '<li><span class="fa fa-circle text-danger"></span> ' . getProductById($saleProduct->product_id)->product_name . ' is not enough quantity.</li>';
                    }
                }

                if ($count_row == $check_row) {
                    foreach ($saleDetail as $key => $saleProduct) {
                        $stock = StockModel::where(['warehouse_id' => $wh_id, 'product_id' => $saleProduct->product_id])->first();
                        $child_unit = ProductUnitModel:: where(['product_id' => $saleProduct->product_id, 'type' => 'child'])->first();
                        $product_unit = ProductUnitModel:: where(['product_id' => $saleProduct->product_id, 'unit_id' => $saleProduct->unit_id])->first();
                        if ($product_unit->type == 'parent') {
                            // if buy unit is parent convert to child qty
                            $cut_qty = ($child_unit != null ? ($saleProduct->qty * $child_unit->qty_per_unit) : $saleProduct->qty);
                            $cut_qty = intval($cut_qty);
                        } else {
                            $cut_qty = $saleProduct->qty;
                        }
                        if ($stock->stock_qty >= $cut_qty) {
                            $stock->stock_qty -= $cut_qty;
                            $stock->save();
                        }
                    }

                    $rate = getRate();
                    $paid_amount = ($sale->paid_amount_kh > 0 ? $sale->paid_amount_kh / $rate : 0) + $sale->paid_amount_usd;
                    $total_amount = generateGrandTotal($sale);

                    if ($paid_amount > 0) {
                        if ($paid_amount >= $total_amount) {
                            $pstatus = 'paid';
                        } else {
                            $pstatus = 'partial';
                        }
                    } else {
                        $pstatus = 'due';
                    }

                    //insert to payment
                    $payment = new PaymentModel();
                    $payment->invoice_id = $sale->id;
                    $payment->customer_id = $sale->customer_id;
                    $payment->user_id = $sale->user_id;
                    $payment->payment_invoice = generate_inv('nso007_payment', 'PM');
                    $payment->payment_date = $sale->sale_date;
                    $payment->year = date('Y');
                    $payment->payment_amount = $total_amount;
                    $payment->paid_amount = $paid_amount;
                    $payment->payment_status = $pstatus;
                    $payment->status = 1;
                    $payment->type = 'sale-request';
                    $payment->save();

                    //insert to payment detail
                    if ($paid_amount > 0) {
                        $payment_detail = new PaymentDetailModel();
                        $payment_detail->payment_id = $payment->id;
                        $payment_detail->paid_amount = $paid_amount;
                        $payment_detail->payment_date = $sale->sale_date;
                        $payment_detail->status = 1;
                        $payment_detail->save();
                    }
                }
            }
        }

        $message .= '</ul>';
        if ($count_message > 0) {
            return redirect()->route('purchase-order.index')->with(['danger' => 'Something Wrong', 'count' => $count_message, 'message' => $message]);

        } else {
            $sale->status = $status;
            $sale->delivery_fee = $request->delivery_fee;
            $sale->delivery_phone = $request->phone;
            $sale->location = $request->location;
            $sale->delivery_status = $status;
            $sale->delivery_note = $request->note;
            $sale->warehouse_id = $wh_id;
            $sale->payment_status = $pstatus;
            $sale->update();
            return redirect()->route('purchase-order.index')->with('success', 'updated successful');
        }
    }

    public function update_seen()
    {
        SaleModel::where('seen_at', null)
            ->where('user_id', Auth::user()->id)
            ->where('status', '!=', 0)
            ->update(['seen_at' => date('Y-m-d H:i:s')]);
        return 'updated seen';
    }

    public function get_report_sale(Request $request)
    {
        $customer = SaleModel::where('branch_id', Auth::user()->branch_id)->where('is_role', '!=', 'out_shop')->where('status', 1)->pluck('customer_id');
        $customer = CustomerModel::whereIn('id', $customer)->pluck('customer_name', 'id');
        if ($request->ajax()) {
            $search = $request->input('search.value');
            $from_date = $request->start_date;
            $to_date = $request->end_date;
            $customer = $request->customer_id;
            $count_total = SaleModel::where(['status' => 1, 'user_id' => Auth::user()->id])
                ->count();
            $data = SaleModel::where(['status' => 1, 'user_id' => Auth::user()->id])
                ->where(function ($q) use ($search) {
                    if ($search) {
                        $q->where('nso007_sales.invoice_number', 'like', '%' . $search . '%');
                    }
                })
                ->where(function ($q) use ($from_date, $to_date) {
                    if ($from_date) {
                        $q->whereDate('nso007_sales.sale_date', '>=', date('Y-m-d', strtotime($from_date)));
                    }
                    if ($to_date) {
                        $q->whereDate('nso007_sales.sale_date', '<=', date('Y-m-d', strtotime($to_date)));
                    }
                })
                ->where(function ($q) use ($customer) {
                    if ($customer) {
                        $q->where('nso007_sales.customer_id', $customer);
                    }
                })
                ->orderBy('nso007_sales.id', 'DESC');
            $count_filter = $data->count();
            return Datatables::of($data->take(10))
                ->with([

                    "recordsTotal" => $count_total,

                    "recordsFiltered" => $count_filter,

                ])
                ->addColumn('amount', function ($sales) {
                    $price = generateGrandTotal($sales);
                    $user_currency = user_currency();
                    return $user_currency->symbol . number_format(convery_currency($sales->id, $price), 2);
                })
                ->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('customer_id', function ($sales) {

                    return findCustomer($sales->customer_id)->customer_name;

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

                    return findCustomer($sales->customer_id)->customer_phone;

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

                    return $sales->invoice_number;

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

                    return '<a href="' . route("reportsales_print", $sales->id) . '" title="Print" class="button_sm button_success">' . \Lang::get('administrator.print') . '</a>';

                })
                ->addIndexColumn()
                ->rawColumns(['invoice_number' => 'invoice_number', 'action' => 'action', 'customer_phone' => 'customer_phone'])
                ->make(true);

        }

        return view('branch.report.sale.index', compact('customer'));
    }

    public function get_report_sale_detail(Request $request)
    {

        $customer = SaleModel::where('branch_id', Auth::user()->branch_id)->where('is_role', '!=', 'out_shop')->where('status', 1)->pluck('customer_id');
        $customer = CustomerModel::whereIn('id', $customer)->pluck('customer_name', 'id');
        $product = SaleDetailsModel::join('nso007_sales', 'nso007_sales.id', 'nso007_sale_details.sale_id')
            ->where('branch_id', Auth::user()->branch_id)
            ->where('nso007_sales.status', 1)->pluck('product_id');
        $product = ProductModel::whereIn('id', $product)->pluck('product_name', 'id');
        if ($request->ajax()) {
            $search = $request->input('search.value');
            $customer = $request->customer_id;
            $product = $request->product_id . '';
            $from_date = $request->start_date;
            $to_date = $request->end_date;
            $count_total = SaleDetailsModel::select('nso007_sales.invoice_number')
                ->join('nso007_sales', 'nso007_sales.id', 'nso007_sale_details.sale_id')
                ->where(['nso007_sales.status' => 1, 'user_id' => Auth::user()->id])
                ->count();

            $data = SaleDetailsModel::select('nso007_sales.invoice_number', 'nso007_sales.customer_id', 'nso007_sales.sale_date', 'nso007_sales.sale_type', 'nso007_sales.user_id', 'nso007_sale_details.*')
                ->join('nso007_sales', 'nso007_sales.id', 'nso007_sale_details.sale_id')
                ->where(['nso007_sales.status' => 1, 'user_id' => Auth::user()->id])
                ->where(function ($q) use ($customer) {
                    if ($customer) {
                        $q->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 ($q) use ($product) {
                    if ($product) {
                        $q->where('nso007_sale_details.product_id', $product);
                    }
                })
                ->orderBy('nso007_sales.id', 'DESC');
            $count_filter = $data->count();
            return Datatables::of($data->take(20))
                ->with([
                    "recordsTotal" => $count_total,
                    "recordsFiltered" => $count_filter,
                ])
                ->addColumn('amount', function ($sales) {
                    $user_currency = findCurrency($sales->currency_id);
                    $total = generateTotal($sales);
                    return ($user_currency?$user_currency->symbol:'') . number_format($total, 2);
                })
                ->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) {
                    $is_role = strtolower(findUser($sales->user_id)->is_role);
                    if ($is_role == 'administrator') {
                        $is_role = 'user';
                    }
                    return findUser($sales->user_id)->name . ' (' . __('administrator.' . $is_role) . ')';
                })
                ->editColumn('product_id', function ($sales) {
                    return getProductById($sales->product_id)->product_name;
                })
                ->editColumn('customer_id', function ($sales) {
                    return findCustomer($sales->customer_id)->customer_name;
                })
                ->addColumn('invoice_number', function ($sales) {
                    return $sales->invoice_number;
                })
                ->addColumn('qty', function ($sales) {
                    return $sales->qty . ' ' . findUnit($sales->unit_id)->unit;
                })
                ->addColumn('dis', function ($sales) {
                    return $sales->dis . '%';
                })
                ->addColumn('sale_price', function ($sales) {
                    $user_currency = findCurrency($sales->currency_id);
                    return ($user_currency?$user_currency->symbol:'') . $sales->sale_price;

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

                })
                ->addIndexColumn()
                ->rawColumns(['invoice_number' => 'invoice_number', 'action' => 'action', 'customer_phone' => 'customer_phone'])
                ->make(true);

        }
        return view('branch.report.sale-detail.index', compact('customer', 'product'));
    }
}
