<?php

namespace App\Repositories\InventorySetup;

use App\Helpers\Helper;
use Illuminate\Support\Facades\Auth;
use App\Models\Brand;
use App\Models\Stock;
use App\Models\StockSummary;
use App\Models\Grn;
use App\Models\Grn_detail;
use App\Models\Order;
use App\Models\Purchases;
use App\Models\PurchasesDetails;
use App\Models\QC;
use App\Models\QcDetails;
use Illuminate\Support\Facades\DB;

class QcRepositories
{
    /**
     * @var user_id
     */
    private $user_id;
    /**
     * @var Brand
     */
    private $qc;
    /**
     * CourseRepository constructor.
     * @param brand $purchase
     */
    public function __construct(QC $qc)
    {
        $this->qc = $qc;
        //$this->middleware(function ($request, $next) {
        $this->user_id = 1; //auth()->user()->id;
        //  return $next($request);
        //});
    }

    /**
     * @param $request
     * @return mixed
     */
    public function getAllList()
    {
        $result = $this->qc::latest()->get();
        return $result;
    }

    /**
     * @param $request
     * @return mixed
     */
    public function getList($request)
    {
        $columns = array(
            0 => 'id',
            1 => 'invoice_no',
        );

        $edit = Helper::roleAccess('delivery.qc.edit') ? 0 : 0;
        $delete = Helper::roleAccess('delivery.qc.destroy') ? 1 : 0;
        $view = Helper::roleAccess('delivery.qc.invoice') ? 1 : 0;
        $ced = $edit + $delete + $view;

        $totalData = $this->qc::count();

        $limit = $request->input('length');
        $start = $request->input('start');
        $order = $columns[$request->input('order.0.column')];
        $dir = $request->input('order.0.dir');
        $auth = Auth::user();
        if (empty($request->input('search.value'))) {
            $qc = $this->qc::offset($start);
            // if ($auth->branch_id !== null) {
            //     $qc = $qc->where('branch_id', $auth->branch_id);
            // }
            $qc = $qc->limit($limit)
                ->orderBy($order, $dir)
                //->orderBy('status', 'desc')
                ->get();
            $totalFiltered = $this->qc::count();
        } else {
            $search = $request->input('search.value');
            $qc = $this->qc::where('invoice_no', 'like', "%{$search}%");
            if ($auth->branch_id !== null) {
                $qc = $qc->where('branch_id', $auth->branch_id);
            }
            $qc = $qc->where('purchase_type', 'Direct')
                ->offset($start)
                ->limit($limit)
                ->orderBy($order, $dir)
                // ->orderBy('status', 'desc')
                ->get();
            $totalFiltered = $this->qc::where('invoice_no', 'like', "%{$search}%")->count();
        }



        $data = array();
        if ($qc) {
            foreach ($qc as $key => $grn) {
                // dd($grn);
                $nestedData['id'] = $key + 1;
                $nestedData['date'] = $grn->date;
                $nestedData['invoice_no'] = $grn->invoice_no;
                $nestedData['total_qty'] = $grn->total_qty;
                $nestedData['approve_qty'] = $grn->approve_qty;
                $nestedData['remarks_qty'] = $grn->remarks_qty ;
                $nestedData['payment'] = $grn->payment;
                $nestedData['due'] = $grn->due;

                if ($ced != 0) :
                    if ($edit != 0)
                        $edit_data = '<a href="' . route('delivery.qc.edit', $grn->id) . '" class="btn btn-xs btn-default"><i class="fa fa-edit" aria-hidden="true"></i></a>';
                    else
                        $edit_data = '';
                    if ($view = !0)
                        $view_data = '<a href="' . route('delivery.qc.invoice', $grn->id) . '" class="btn btn-xs btn-default"><i class="fa fa-eye" aria-hidden="true"></i></a>';
                    else
                        $view_data = '';
                    if ($delete != 0)
                        $delete_data = '<a delete_route="' . route('delivery.qc.destroy', $grn->id) . '" delete_id="' . $grn->id . '" title="Delete" class="btn btn-xs btn-default delete_row uniqueid' . $grn->id . '"><i class="fa fa-times"></i></a>';
                    else
                        $delete_data = '';
                    $nestedData['action'] = $edit_data . ' ' . $view_data . ' ' . $delete_data;
                else :
                    $nestedData['action'] = '';
                endif;
                $data[] = $nestedData;
            }
        }
        $json_data = array(
            "draw" => intval($request->input('draw')),
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );

        return $json_data;
    }


    /**
     * @param $request
     * @return mixed
     */
    public function details($id)
    {
        $result = $this->qc::find($id);
        return $result;
    }

    public function store($request)
    {
        DB::beginTransaction();
        try {
            $remainingtt = $request->remaining;
            $approve_qtyt = $request->approve_qty;
            $statuscheck = array_sum($remainingtt) + array_sum($approve_qtyt);
            $qc = new QC();
            $qc->date = $request->date;
            $qc->invoice_no = "Qc" . rand(111111,99999);
            $qc->order_voucher_id = $request->order_voucher;
            $qc->total_qty = array_sum($request->qty);
            $qc->approve_qty = array_sum($request->approve_qty)  + array_sum($request->remaining);
            $qc->remarks_qty = array_sum($request->qty) - (array_sum($request->approve_qty)  + array_sum($request->remaining));
            $qc->note = $request->note;
            $qc->create_by = Auth::user()->id;
            $qc->save();
            $grnId = $qc->id;

            $purchase = Order::findOrFail($request->order_voucher);


            if (array_sum($request->qty) <= abs($statuscheck)) {
                $purchase->status =  'Confirmed';
            }
            $purchase->save();


            $product = $request->product_id;
            $qty = $request->qty;
            $approve_qty = $request->approve_qty;
            $remainingqty = $request->remaining;

            for ($i = 0; $i < count($product); $i++) {
                $qcdetails = new QcDetails();
                $qcdetails->qc_id = $grnId;
                $qcdetails->product_id = $product[$i];
                $qcdetails->qty = $qty[$i];
                $qcdetails->order_voucher = $request->order_voucher;
                $qcdetails->approve_qty = $approve_qty[$i] + $remainingqty[$i];
                $qcdetails->save();
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            dd($e->getMessage(), $e->getLine());
            redirect('delivery.qc.index')->with('error', 'Something Wrong Please try again');
        }
        return;
    }


    public function update($request, $id)
    {
        DB::beginTransaction();
        try {

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            redirect('inventory-purchase-create')->with('error', 'Something Wrong Please try again');
        }
        return;
    }

    public function statusUpdate($id, $status)
    {
        $purchase = $this->qc::find($id);
        $purchase->status = $status;
        $purchase->save();
        return $purchase;
    }

    public function destroy($id)
    {
        // $grn = $this->qc::find($id);
        // $grn->delete();
        // Grn_detail::where('good_rcv_note_id',$id)->delete();
        // Stock::where('good_rcv_note_id',$id)->delete();
        return true;
    }
}
