<?php

namespace App\Repositories\InventorySetup;

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

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

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

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

        $edit = Helper::roleAccess('finished.goods.edit') ? 0 : 0;
        $delete = Helper::roleAccess('finished.goods.destroy') ? 1 : 0;
        $view = Helper::roleAccess('finished.goods.show') ? 1 : 0;
        $ced = $edit + $delete + $view;

        $totalData = $this->fg::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'))) {
            $fg = $this->fg::offset($start);
            // if ($auth->branch_id !== null) {
            //     $fg = $fg->where('branch_id', $auth->branch_id);
            // }
            $fg = $fg->limit($limit)
                ->orderBy('id', "desc")
                //->orderBy('status', 'desc')
                ->get();
            $totalFiltered = $this->fg::count();
        } else {
            $search = $request->input('search.value');
            $fg = $this->fg::where('invoice_no', 'like', "%{$search}%");
            if ($auth->branch_id !== null) {
                $fg = $fg->where('branch_id', $auth->branch_id);
            }
            $fg = $fg->where('purchase_type', 'Direct')
                ->offset($start)
                ->limit($limit)
                ->orderBy($order, $dir)
                // ->orderBy('status', 'desc')
                ->get();
            $totalFiltered = $this->fg::where('invoice_no', 'like', "%{$search}%")->count();
        }



        $data = array();
        if ($fg) {
            foreach ($fg as $key => $grn) {
                // dd($grn);
                $nestedData['id'] = $key + 1;
                $nestedData['date'] = $grn->date;
                $nestedData['order_voucher_id'] = $grn->order->order_code ?? "";
                $nestedData['invoice_no'] = $grn->invoice_no;
                $nestedData['total_qty'] = $grn->total_qty;
                $nestedData['status'] = $grn->status;
                $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('finished.goods.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('finished.goods.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('finished.goods.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->fg::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);
            $fg = new FinishedGood();
            $fg->date = $request->date;
            $fg->invoice_no = "FG" . rand(111111,99999);
            $fg->order_voucher_id = $request->order_voucher;
            $fg->total_qty = array_sum($request->qty);
            $fg->approve_qty = array_sum($request->approve_qty) + array_sum($request->remaining);
            $fg->remarks_qty = array_sum($request->qty) - (array_sum($request->approve_qty)  + array_sum($request->remaining));
            $fg->note = $request->note;
            $fg->shiping_details = json_encode($request->only('payment_type','company','phone','address','biller_name'));
            $fg->create_by = Auth::user()->id;
            $fg->save();
            $grnId = $fg->id;

            $orderstatus = new OrderStatus();
            $orderstatus->fg_id = $grnId;
            $orderstatus->name = "Pending";
            $orderstatus->save();

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

            for ($i = 0; $i < count($product); $i++) {
                $fgdetails = new FgDetails();
                $fgdetails->fg_id = $grnId;
                $fgdetails->product_id = $product[$i];
                $fgdetails->qty = $qty[$i];
                $fgdetails->order_voucher = $request->order_voucher;
                $fgdetails->approve_qty = $approve_qty[$i] + $remainingqty[$i];
                $fgdetails->remaining = $remainingqty[$i];
                $fgdetails->save();
            }
            
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            dd($e->getMessage(), $e->getLine() ,$e->getFile());
            redirect('finished.goods.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->fg::find($id);
        $purchase->status = $status;
        $purchase->save();
        return $purchase;
    }

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