<?php

namespace App\Http\Controllers\Administrator\stock_adjustment;

use App\Model\AdjustmentDetailModel;
use App\Model\AdjustmentModel;
use App\Model\product\ColorModel;
use App\Model\product\SizeModel;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use Yajra\DataTables\DataTables;
use DB;
use App\Model\stock_inventory\StockModel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use App\Model\product\ProductUnitModel;

class StockAdjustmentController extends Controller

{

     function __construct()
     {
         $this->middleware('permission:Adjustment List', ['only' => ['index']]);
         $this->middleware('permission:Adjustment Show', ['only' => ['show']]);
         $this->middleware('permission:Adjustment Create', ['only' => ['create','store']]);
     }
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = AdjustmentModel::where('type', 'item')->latest();
                return DataTables::of($data)

                    ->editColumn('warehouse_id', function ($item) {
                        return findWarehouse($item->warehouse_id)->warehouse_name ?? '';
                    })
                    ->editColumn('date', function ($item) {
                        return date('d-m-Y', strtotime($item->date));
                    })
                    ->editColumn('user_id', function ($item) {
                        return findUser($item->user_id)->name ?? '';
                    })
                    ->addColumn('action', function ($item) {
                        if (Gate::check('Adjustment Show'))
                            return '<a data-href="' . route("stock-adjustment.show", $item->id) . '" data-width="700px" title="' . __('administrator.show') . '" class="button_info getHtmlFormShow">' . __('administrator.show') . '</a>';
                    })
                    ->addIndexColumn()
                    ->rawColumns(['action','confirm_status'])
                    ->make(true);
        }

        return view('administrator.adjustment.index');
    }

    public function create(Request $request)
    {
        if ($request['product_id']) {
            $this->validate($request, [
                'warehouse_id' => 'required'
            ]);
            if ($request->getType==='getSize') {
                $size = ProductUnitModel::where('product_id',$request['product_id'])->pluck('size_code');
                $size = SizeModel::whereIn('code', $size)->pluck('size', 'code');
                return response()->json(['size' => $size]);
            }
            if ($request->getType === 'getColor') {
                $color = ProductUnitModel::where(['product_id'=>$request['product_id'],'size_code'=>$request->size_code])
                    ->pluck('color_code');
                $color = ColorModel::whereIn('code', $color)->pluck('name', 'code');
                return response()->json(['color'=>$color]);
            }
            if($request->getType === 'getStock'){
                $wh = $request->all();
                unset($wh['getType']);
                $stock = StockModel::where($wh)->first();
                return response()->json(['qty' => $stock->stock_qty ?? 0]);
            }
            return response()->json(['status' => 'hello error']);
        }
        return view('administrator.adjustment.create');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'warehouse_id' => 'required',
            'date' => 'required',
            'product_id' => 'required',
            'product_id.*' => 'required',
            'size_code.*' => 'required',
            'color_code.*' => 'required',
            'qty.*' => 'required',
        ]);
        $data = [];
        $data['invoice_number'] = generate_inv('nso007_adjustment', 'ADJ');
        $data['type'] = 'item';
        $data['date'] = date('Y-m-d', strtotime($request['date']));
        $data['user_id'] = Auth::user()->id;
        $data['branch_id'] = Auth::user()->branch_id;
        $data['year'] = date('Y');
        $data['warehouse_id'] = $request['warehouse_id'];
        $data['note'] = $request['note'];
        $data['updated_at'] = date('Y-m-d H:i:s');
        $data['created_at'] = date('Y-m-d H:i:s');
        $id = AdjustmentModel::insertGetId($data);
        foreach ($request['product_id'] as $key => $value) {
            $product_unit = ProductUnitModel::where(['product_id' => $value, 'size_code' => $request['size_code'][$key], 'color_code' => $request['color_code'][$key]])->first();

            $add_tran = new AdjustmentDetailModel();
            $add_tran->adjustment_id = $id;
            $add_tran->barcode = $product_unit->barcode;
            $add_tran->size_code = $request['size_code'][$key];
            $add_tran->color_code = $request['color_code'][$key];
            $add_tran->product_id = $value;
            $add_tran->qty = $request['qty'][$key];
            $add_tran->operator = $request['operator'][$key];
            $add_tran->old_stock = $request['stock'][$key];
            $add_tran->balance_stock = $request['balance'][$key];
            $old_stock = StockModel::where([
                    'barcode' => $product_unit->barcode,
                    'warehouse_id' => $request['warehouse_id']
                ])->first()->stock_qty??0;
            $qty = eval("return $old_stock$add_tran->operator$add_tran->qty;");
            $aa = StockModel::updateOrCreate(
                [
                    'barcode' => $product_unit->barcode,
                    'warehouse_id' => $request['warehouse_id']
                ], [
                'type'=>'product',
                'size_code'=>$add_tran->size_code,
                'color_code'=>$add_tran->color_code,
                'product_id'=>$add_tran->product_id,
                'warehouse_id'=>$request['warehouse_id'],
                'barcode'=>$product_unit->barcode,
                'stock_qty' => $qty,
            ]);
            if($aa){
                $add_tran->note = "Added ".$product_unit->barcode.' '.$request['operator'][$key] . $request['qty'][$key];
                $add_tran->save();
            }
        }
        return response()->json(['status' => 'success','route'=>route('stock-adjustment.index')]);
    }

    public function show($id)
    {
        $master = AdjustmentModel::find($id);
        return view('administrator.adjustment.show', compact('master'));
    }


}

