<?php


namespace App\Http\Controllers\Administrator;


use App\Model\AccountReceivableModel;

use App\Model\DeliveryOrderDetailModel;

use App\Model\PaymentDetailModel;

use App\Model\PaymentModel;

use App\Model\PaymentTypeModel;

use App\User;

use App\Model\WalletModel;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\Model\CustomerModel;

use App\Model\ProductModel;

use App\Model\StockModel;

use App\Model\SaleDetailsModel;

use App\Model\OrderModel;

use App\Model\OrderDetailsModel;

use App\Model\SaleModel;

use Session;

use DB;

use Auth;

use DataTables;

use App\Fun\Fun;

use App\Model\JournalModel;

use App\Model\NextPaymentModel;

use App\Model\WarehouseModel;

use Carbon\Carbon;

use App\Model\ProductUnitModel;

use App\Model\DriverOwnStock;

class SellerRequestController extends Controller

{


    public function index()

    {

        $customers = CustomerModel::get();

        return view('seller.customers.customer-list', compact('customers'));

    }


    public function create()

    {

        return view('seller.customers.create');

    }

    public function store(Request $request)

    {
        $this->validate($request, [

            'customer_name' => 'required|max:255',

            'customer_phone' => 'required|max:15',

            'sex' => 'required',

        ]);

        $customer = new CustomerModel;

        $customer->agent_id = Auth::user()->id;

        $customer->customer_name = $request->customer_name;

        $customer->customer_phone = $request->customer_phone;

        $customer->customer_email = $request->customer_email;

        $customer->customer_address = $request->customer_address;

        $customer->sex = $request->sex;

        $customer->note = $request->note;

        $customer->save();

        return redirect()->route('customers.index')
            ->with('success', 'Customer created successfully');

    }

    public function show(Request $request, $id)

    {

        $customers = CustomerModel::where('id', $id)
            ->first();

        $search = $request->input('search.value');

        $count_total = OrderModel::where(['nso007_orders.status' => 1])
            ->where(['nso007_orders.user_id' => Auth::user()->id])
            ->count();

        $count_filter = OrderModel::select('nso007_orders.user_id')
            ->join('nso007_order_details', 'nso007_order_details.order_id', '=', 'nso007_orders.id')
            ->join('nso007_customers', 'nso007_customers.id', '=', 'nso007_orders.customer_id')
            ->where(['nso007_orders.status' => 1])
            ->where(['nso007_orders.customer_id' => $id])
            ->where(function ($query) use ($search) {

                $query->orWhere('nso007_orders.invoice_number', 'LIKE', '%' . $search . '%');

                $query->orWhere('nso007_orders.transaction_code', 'LIKE', '%' . $search . '%');

            })
            ->groupby('nso007_order_details.order_id')
            ->get()->count();


        $data = OrderModel::select('nso007_orders.*',

            DB::raw('SUM(nso007_order_details.qty*nso007_order_details.cost - nso007_order_details.qty*nso007_order_details.cost*nso007_order_details.dis/100) as amount'),

            'nso007_customers.customer_name', 'nso007_customers.customer_phone')
            ->join('nso007_order_details', 'nso007_order_details.order_id', '=', 'nso007_orders.id')
            ->join('nso007_customers', 'nso007_customers.id', '=', 'nso007_orders.customer_id')
            ->where(['nso007_orders.status' => 1])
            ->where(['nso007_orders.customer_id' => $id])
            ->groupby('nso007_order_details.order_id')
            ->take(10);

        if ($request->ajax()) {

            return DataTables::of($data)
                ->with([

                    "recordsTotal" => $count_total,

                    "recordsFiltered" => $count_filter,

                ])
                ->addColumn('created_at', function ($purchase) {

                    return date('d-m-Y', strtotime($purchase->created_at));

                })
                ->addColumn('total', function ($purchase) {

                    return '$' . number_format($purchase->amount, 2);

                })->addColumn('delivery_fee', function ($purchase) {

                    return '$' . number_format($purchase->delivery_fee, 2);

                })
                ->addColumn('purchase_date', function ($purchase) {

                    return date('d-m-Y', strtotime($purchase->purchase_date));

                })
                ->editColumn('delivery_service', function ($purchase) {

                    $check_language = Fun::lang();

                    $delivery_detail = DeliveryOrderDetailModel::where('export_id', $purchase->id)->first();


                    if ($check_language == 'km') {

                        $yes = 'បង់ប្រាក់';

                        $no = 'មិនគិតថ្លៃ';

                        $processing = 'ដំណើរការ';

                        $pending = 'រង់ចាំ';

                        $done = 'រួចរាល់';

                        $cancel = 'បោះបង់';

                    } else {

                        $yes = 'Paid';

                        $no = 'Free';

                        $processing = 'Processing';

                        $pending = 'Pending';

                        $done = 'Done';

                        $cancel = 'Cancel';

                    }

                    $status = '';


                    if ($delivery_detail != null) {

                        if ($delivery_detail->status == 1) {

                            $status = '<label class="label label-info">' . $processing . '</label>';

                        }

                        if ($delivery_detail->status == 2) {

                            $status = '<label class="label label-warning">' . $pending . '</label>';

                        }

                        if ($delivery_detail->status == 3) {

                            $status = '<label class="label label-success">' . $done . '</label>';

                        }

                        if ($delivery_detail->status == 4) {

                            $status = '<label class="label label-danger">' . $cancel . '</label>';

                        }

                    } else {

                        $status = '<label class="label label-warning">' . $pending . '</label>';

                    }


                    if ($purchase->delivery_service == 1) {

                        $delivery = $yes;

                    } else {

                        $delivery = $no;

                    }

                    return $delivery . ' ' . $status;

                })
                ->editColumn('payment_type', function ($purchase) {

                    $type = '';

                    if ($purchase->payment_type) {

                        if ($purchase->payment_type == 'cash') {

                            $type = 'Cash';

                        } else if ($purchase->payment_type == 'wallet') {

                            $type = 'Wallet';

                        } else {

                            $payment_type = PaymentTypeModel::find($purchase->payment_type);

                            if ($payment_type) {

                                $type = $payment_type->name;

                            }

                        }


                    }

                    return $type;

                })
                ->editColumn('paid_amount_kh', function ($purchase) {

                    $paid = ($purchase->paid_amount_km > 0 ? ($purchase->paid_amount_km / $purchase->rate) : 0) + $purchase->paid_amount_us;

                    return '$' . number_format($paid, 2);

                })
                ->editColumn('remain', function ($purchase) {

                    $paid = ($purchase->paid_amount_km > 0 ? ($purchase->paid_amount_km / $purchase->rate) : 0) + $purchase->paid_amount_us;

                    return '$' . number_format(($purchase->amount - $paid) > 0 ? ($purchase->amount - $paid) : 0, 2);

                })
                ->editColumn('order_status', function ($purchase) {

                    $check_language = Fun::lang();

                    if ($check_language == 'km') {

                        $pending = 'រង់ចាំ';

                        $accept = 'បានទទួលយក';

                        $reject = 'បានបដិសេធ';

                    } else {

                        $pending = 'Pending';

                        $accept = 'Accepted';

                        $reject = 'Rejected';

                    }

                    if ($purchase->order_status == 0) {

                        $status = '<span class="label label-warning">' . $pending . '</span>';

                    } else if ($purchase->order_status == 1) {

                        $status = '<span class="label label-success">' . $accept . '</span>';

                    } else {

                        $status = '<span class="label label-danger">' . $reject . '</span>';

                    }

                    return $status;

                })
                ->editColumn('payment_status', function ($sales) {

                    $status = '';

                    if ($sales->payment_status == 'Due') {

                        $status = '<span class="label label-danger">Due</span>';

                    }

                    if ($sales->payment_status == 'Paid') {

                        $status = '<span class="label label-success">Paid</span>';

                    }

                    if ($sales->payment_status == 'Partial') {

                        $status = '<span class="label label-info">Partial</span>';

                    }

                    return $status;

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

                    $show = '';

                    $delete = '';

                    $check_language = Fun::lang();

                    if ($check_language == 'km') {

                        $show = 'មើល';

                        $delete = 'លុប';

                        $print = 'ព្រីន';

                    } else {

                        $show = 'Show';


                        $delete = 'Delete';

                        $print = 'Print';

                    }

                    $bill = 'Bill';

                    $invoice = 'Invoice';

                    return '<a href="' . route("request_order_show", $purchase->id) . '?type=1" title="Bill" class="button_primary">' . $bill . '</a>

                            <a href="' . route("request_order_show", $purchase->id) . '?type=2" title="Invoice" class="button_success">' . $invoice . '</a> 

                            <a href="' . route("request_order_show_print", $purchase->id) . '" title="Print" class="button_info" style="display:none">' . $print . '</a> ';

                })
                ->addIndexColumn()
                ->rawColumns(['invoice_number' => 'invoice_number', 'action' => 'action', 'payment_status' => 'payment_status', 'order_status' => 'order_status', 'remain' => 'remain', 'delivery_service' => 'delivery_service'])
                ->make(true);

        }

        return view('seller.customers.customer-list-show', compact('customers'));

    }

    public function edit($id)

    {
        $customer = CustomerModel::find($id);
        return view('seller.customers.edit', compact('customer'));
    }

    public function update(Request $request, $id)

    {
        $this->validate($request, [

            'customer_name' => 'required|max:255',

            'customer_phone' => 'required|max:15',

            'sex' => 'required',

        ]);

        $customer = CustomerModel::find($id);

        $customer->customer_name = $request->customer_name;

        $customer->customer_phone = $request->customer_phone;

        $customer->customer_email = $request->customer_email;

        $customer->customer_address = $request->customer_address;

        $customer->sex = $request->sex;

        $customer->note = $request->note;

        $customer->update();

        return redirect()->route('customers.index')
            ->with('success', 'Customer updated successfully');

    }

}

