<?php

namespace App\Http\Controllers\Administrator\production;

use App\Fun\Fun;
use App\Model\product\ProductUnitModel;
use App\Model\production\ProductionTemplateModel;
use App\Model\production\TailorStockPaymentModel;
use App\Model\production\packing\ProductionPackingDetailModel;
use App\Model\production\packing\ProductionPackingDoneDetailModel;
use App\Model\production\packing\ProductionPackingDoneModel;
use App\Model\production\packing\ProductionPackingModel;
use App\Model\production\ProductionRequestDetailModel;
use App\Model\production\ProductionRequestModel;
use App\Model\setup\PackerModel;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\ValidationException;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Gate;

class PackingController extends Controller
{

    public function __construct()
    {

//        $this->middleware('permission:Item Template List', ['only' => ['index']]);
//        $this->middleware('permission:Item Template Create', ['only' => ['create', 'store']]);
//        $this->middleware('permission:Item Template Edit', ['only' => ['update', 'edit']]);
        Fun::lang();
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {
            Fun::lang();
            if ($request->getPacking) {
                $master = ProductionPackingModel::where(['production_id' => $request->production_id])->get();
                return view('administrator.production-packing.packing-detail', compact('master'));
            }
            $production = ProductionRequestModel::where(['packing' => 1, 'reference_id' => Null])
                ->select('*')
                ->latest();
            return DataTables::of($production)
                ->addIndexColumn()
                ->editColumn('user_id', function ($data) {
                    return findUser($data->user_id)->name ?? '';
                })
                ->editColumn('date', function ($data) {
                    return date('d-m-Y', strtotime($data->date));
                })
                ->addColumn('total_item', function ($data) {
                    return $data->total_item = ProductionPackingModel::where('production_id', $data->id)->sum('total_qty');
                })
                ->addColumn('return_qty', function ($data) {
                    return $data->return_qty = ProductionPackingModel::where('production_id', $data->id)->sum('return_qty');
                })
                ->addColumn('import_qty', function ($data) {
                    return $data->import_qty = ProductionPackingModel::where('production_id', $data->id)->sum('import_qty');
                })
                ->addColumn('remain_qty', function ($data) {
                    return $data->total_item - $data->return_qty - $data->import_qty;
                })
                ->addColumn('action', function ($data) {
                    return '<a data-width="900px" data-href="' . route("production-request.show", $data->id) . '?htmlonly=1" title="' . __('administrator.show') . '" class="button_info getHtmlFormShow">' . __('administrator.show') . '</a>';
                })
                ->rawColumns(['action', 'total_item', 'done', 'return_qty', 'import_qty', 'remain_qty', 'total_item'])
                ->make(true);
        }
        return view('administrator.production-packing.index');
    }


    public function create(Request $request)
    {
        $id = $request['prdid'];
        $production = ProductionRequestModel::find($id);
        $detail = ProductionRequestDetailModel::where('production_id', $production->id)->where('return_qty', '>', 0)->get();
        return view('administrator.production-packing.create', compact('production', 'detail'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'production_id' => 'required',
            'packer_id' => 'required|exists:nso007_packer,id',
            'detail_id.*' => 'required',
            'qty.*' => 'required',
        ]);
        if (!array_sum($request->qty)) {
            throw ValidationException::withMessages(['qty' => 'មិនមានចំនួនវេចខ្ចប់']);
        }
        $production = ProductionRequestModel::find($request['production_id']);
        $production->packing = 1;
        $production->packing_qty += array_sum($request['qty']);
        $production->update();
        $id = ProductionPackingModel::create([
            'production_id' => $production->reference_id ?? $production->id,
            'production_invoice' => $production->reference_invoice ?? $production->invoice_number,
            'date' => date('Y-m-d h:i:s'),
            'year' => date('Y'),
            'user_id' => Auth::user()->id,
            'packer_id' => $request->packer_id,
            'total_qty' => array_sum($request['qty']),
            'invoice_number' => generate_inv('nso007_production_packing', 'PK'),
        ]);
        $packer = PackerModel::find($request->packer_id);
        foreach ($request['detail_id'] as $key => $detail_id) {
            $production_detail = ProductionRequestDetailModel::find($detail_id);
            $tp = ProductionTemplateModel::find($production_detail->template_id);
            $cost = $tp?($tp->total_cost- $tp->cutting_price - $tp->sewing_price):0;
            $production_detail->packing_qty += $request['qty'][$key];
            $production_detail->update();

            if ($packer->currency_id != $production_detail->currency_id) {
                if ($production_detail->currency_id == 1) {
                    $fee = $packer->fee * getRate();
                } else {
                    $fee = $packer->fee / getRate();
                }
            } else {
                $fee = $packer->fee;
            }

            ProductionPackingDetailModel::create([
                'packing_id' => $id->id,
                'product_id' => $production_detail->product_id,
                'barcode' => $production_detail->barcode,
                'qty' => $request['qty'][$key],
                'packing_price' => $fee,
                'cutting_price' => $production_detail->cutting_price,
                'sewing_price' => $production_detail->sewing_price,
                'cost' => $cost,
                'total_cost' => ($cost + $production_detail->sewing_price + $production_detail->cutting_price + $fee),
                'currency_id' => 1,
            ]);
        }
        return response()->json(['status' => 'success', 'route' => route('production-packing.index')]);
    }

    public function show($id)
    {
        $master = ProductionPackingModel::find($id);
        return view('administrator.production-packing.show', compact('master'));
    }

    public function import_stock($id, Request $request)
    {
        $master = ProductionPackingModel::find($id);
        if ($request->method() === 'POST') {
            $this->validate($request, [
                'warehouse_id' => 'required',
                'packing_detail_id' => 'required',
                'packing_detail_id.*' => 'required',
                'qty.*' => 'required',
            ]);
            $packing_done = ProductionPackingDoneModel::create([
                'packing_id' => $id,
                'packer_id' => $master->packer_id,
                'warehouse_id' => $request['warehouse_id'],
                'date' => date('Y-m-d h:i:s'),
                'year' => date('Y'),
                'user_id' => Auth::user()->id,
                'invoice_number' => generate_inv('nso007_production_packing_done', 'PKD'),

            ]);
            $packer = PackerModel::find($master->packer_id);
            foreach ($request['packing_detail_id'] as $key => $value) {
                $detail = ProductionPackingDetailModel::find($value);
                $pkd_detail = ProductionPackingDoneDetailModel::create([
                    'packing_done_id' => $packing_done->id,
                    'barcode' => $detail->barcode,
                    'fee' => $packer->fee ?? 0,
                    'qty' => $request['qty'][$key],
                ]);
                add_stock_item($request['warehouse_id'], $detail->barcode, $request['qty'][$key]);

                $con_tsp = [
                    'model'=>get_class($master),
                    'model_id'=>$master->id,
                    'packer_id' => $master->packer_id,
                    'type' => 'packing',
                    'product_id' => $detail->product_id,
                    'barcode' => $detail->barcode,
                    'price' => $packer->fee ?? 0,
                    'currency_id' => 1,
                ];


                $product = ProductUnitModel::where([
                    'product_id' => $detail->product_id,
                    'barcode' => $detail->barcode,
                ])->first();
                $detail->currency_id = 1;
                if ($product) {
                    if ($detail->currency_id == 1) {
                        $product->cost_riel = $detail->total_cost;
                        $product->cost_usd = $detail->total_cost / getRate();
                    }
                    if ($detail->currency_id == 2) {
                        $product->cost_riel = getRate() * $detail->total_cost;
                        $product->cost_usd = $detail->total_cost;
                    }
                    $product->update();
                }

                $old_tsp = TailorStockPaymentModel::where($con_tsp)->first()->stock_qty ?? 0;
                TailorStockPaymentModel::updateOrCreate($con_tsp, array_merge($con_tsp, ['stock_qty' => ($old_tsp + $pkd_detail->qty)]));
            }
            $master->import_qty += array_sum($request['qty']);
            $master->update();
            return response()->json(['status' => 'success']);
        }
        $master->route = route('production-packing-import-stock', $master->id);
        return view('administrator.production-packing.import-return-form', compact('master'));
    }

    public function return_production($id, Request $request)
    {
        if ($request->method() === 'POST') {
            $this->validate($request, [
                'packing_detail_id.*' => 'required',
                'barcode' => 'required',
                'qty' => 'required',
            ]);
            $packing = ProductionPackingModel::find($id);
            $ref_production = ProductionRequestModel::find($packing->production_id);

            $production = new ProductionRequestModel();
            $production->invoice_number = generate_inv('nso007_production_request', 'FPK');
            $production->packing_id = $id;
            $production->reference_id = $packing->production_id;
            $production->reference_invoice = $ref_production->invoice_number;
            $production->user_id = Auth::user()->id;
            $production->year = date('Y');
            $production->tailor_id = $ref_production->tailor_id;
            $production->type = 'packing';
            $production->year = date('Y');
            $production->status = 0;
            $production->note = $request['note'];
            $production->total_item = array_sum($request->qty);
            $production->date = date('Y-m-d');
            $production->save();
            $packing->return_qty += array_sum($request['qty']);
            $packing->update();
            foreach ($request->packing_detail_id as $key => $value) {
                $detail = ProductionPackingDetailModel::find($value);

                $add_item = new ProductionRequestDetailModel();
                $pro_unit = findProductUnitByCode($detail->barcode);
                $add_item->production_id = $production->id;
                $add_item->type = 'item';
                $add_item->product_id = $detail->product_id;
                $add_item->barcode = $detail->barcode;
                $add_item->size_code = $pro_unit->size_code ?? 0;
                $add_item->color_code = $pro_unit->color_code ?? 0;
                $add_item->qty = $request->qty[$key];
                $add_item->template_qty = 1;
                $add_item->save();
            }
            return response()->json(['status' => 'success']);
        }
        $master = ProductionPackingModel::find($id);
        $master->route = route('production-packing-return-to-production', $master->id);
        $master->return = 1;
        return view('administrator.production-packing.import-return-form', compact('master'));
    }

    public function import_list($id)
    {
        $packing = ProductionPackingModel::find($id);
        $packing_done = ProductionPackingDoneModel::where('packing_id', $id)->orderBy('id', 'DESC')->get();

        return view('administrator.production-packing.import-stock-list', compact('packing', 'packing_done'));
    }

    public function return_list($id)
    {
        $packing = ProductionPackingModel::find($id);
        $production = ProductionRequestModel::where('packing_id', $id)->orderBy('id', 'DESC')->get();

        return view('administrator.production-packing.return-list', compact('packing', 'production'));
    }

    public function show_import($id)
    {
        $master = ProductionPackingDoneModel::find($id);
        return view('administrator.production-packing.show-import', compact('master'));
    }

    public function done($id)
    {
        $master = ProductionPackingModel::find($id);
        $master->done = 1;
        $master->update();
        return response()->json(['status' => 'success']);

    }

}
