<?php

namespace App\Http\Controllers;

use App\DataTables\ProductionPackagingDataTable;
use App\Http\Requests;
use App\Models\ProductionPackaging;
use App\Models\ProductionPackagingDetail;
use App\Http\Requests\CreateProductionPackagingRequest;
use App\Http\Requests\AttachProductionPackingRequest;
use App\Http\Requests\UpdateProductionPackagingRequest;
use App\Repositories\ProductionPackagingRepository;
use Flash;
use App\Http\Controllers\AppBaseController;
use Response;
use Illuminate\Http\Request;
use Log;

class ProductionPackagingController extends AppBaseController
{
    /** @var  ProductionPackagingRepository */
    private $productionPackagingRepository;

    public function __construct(ProductionPackagingRepository $productionPackagingRepo)
    {
        $this->productionPackagingRepository = $productionPackagingRepo;
    }

    /**
     * Display a listing of the ProductionPackaging.
     *
     * @param ProductionPackagingDataTable $productionPackagingDataTable
     * @return Response
     */
    public function index(ProductionPackagingDataTable $productionPackagingDataTable)
    {
        return $productionPackagingDataTable->render('production_packagings.index');
    }

    /**
     * Show the form for creating a new ProductionPackaging.
     *
     * @return Response
     */
    public function create()
    {
        return view('production_packagings.create');
    }

    /**
     * Store a newly created ProductionPackaging in storage.
     *
     * @param CreateProductionPackagingRequest $request
     *
     * @return Response
     */
    public function store(CreateProductionPackagingRequest $request)
    {
        $input = $request->all();
        $input['packing_id'] = \App\Models\SensitiveCRUDAwareModel::generateMaterialId(6);

        $productionPackaging = $this->productionPackagingRepository->create($input);

        if($request->expectsJson()){
            return  $this->sendResponseMessage('Production Packaging '.$productionPackaging->packing_id.' created successfully.');;
        }else{
            Flash::success('Production Packaging '.$productionPackaging->packing_id.' created successfully.');
            return redirect(route('productionPackagings.index'));
        }
        
    }


    public function attachPacking ($id)
    {
        //$data = \App\Models\ConsumableCategory::pluck('name')->toArray();
        $settings = \App\Models\ProductionPackaging::find($id);

        //dd($data);
        return view('production_packagings.attach')->with('settings', $settings);
    }

    public function deletePacking($id, Request $request)
    {
        $input = $request->all();
        $item = ProductionPackagingDetail::find((int)$input['id']);
        if(!empty($item)){
            $item->forceDelete();
        }
        $this->updateQty($id);
        
        return $this->getPacking($id);
    }

    public function savePacking($id, AttachProductionPackingRequest $request){
        $input = $request->all();
        //dd($input);
        //$item = ConsumableItem::where('name->en', '=', $input['item'])->first();
        $check = $this->validateQuantity($request, $input['material_id'], $input['qty'], null);
        if($check){
            return $this->sendErrorForTable($request, $check);
        }

        $obj= ProductionPackagingDetail::create([
            'packing_id' => $id, 
            'material_id' => $input['material_id'],
            'qty' => $input['qty'],
            'created_at' => \Carbon\Carbon::now(),
             'created_by' => \Auth::user()->id
        ]);
        $this->updateQty($id);

        \App\Http\Resources\PackingDetailResource::withoutWrapping();
        return new \App\Http\Resources\PackingDetailResource($obj);
    }

    public static function validateQuantity($request, $materialId, $qty, $packing){
        $totalQty = \App\Models\QualityCheck::getTotalProduction($materialId);
        $packedQty = \App\Models\ProductionPackaging::getTotalPackedQty($materialId);
        Log::info('totalQty '.$totalQty);
        Log::info('totalPackedQty '.$packedQty);
        $netQty = $totalQty - $packedQty;
        Log::info('remainingQty '.$netQty);
        if($packing){
            $netQty = $netQty + $packing->qty;
        }
        if($totalQty<=0){
            return "Material Id doesnot have production. Please double check material id";
        }else if($netQty<((float)$qty)){
            return "Material Id doesnot have sufficient production. It has currently ".$netQty.' qty';
        }
        return null;
    }
    private function sendErrorForTable(AttachProductionPackingRequest $request, $msg){
        if($request->expectsJson()){
            return  $this->sendValidationError($msg, $msg);
        }else{
            return  $this->sendValidationError($msg, $msg);
        }  
    }

    public function updatePacking($id, AttachProductionPackingRequest $request){
        $input = $request->all();
        //dd($input);
        $detail = ProductionPackagingDetail::find((int)$input['id']);

        $check = $this->validateQuantity($request, $input['material_id'], $input['qty'], $detail);
        if($check){
            return $this->sendErrorForTable($request, $check);
        }

            $detail->update([
                'packing_id' => $id, 
                'qty' => $input['qty'],
                'material_id' => $input['material_id'],
                'updated_at' => \Carbon\Carbon::now(),
                'updated_by' => \Auth::user()->id
            ]);
       $this->updateQty($id);
        \App\Http\Resources\PackingDetailResource::withoutWrapping();
        return new \App\Http\Resources\PackingDetailResource($detail);
        
    }

    private function updateQty($id){
        $productionPackaging= ProductionPackaging::find($id);   
        $productionPackaging->qty = ProductionPackagingDetail::where('packing_id','=', $id)->sum('qty');
        $productionPackaging->save();
    }



    public function getPacking($id){
        $settings = ProductionPackagingDetail::where('packing_id','=', $id)->get();
        //\App\Http\Resources\ConsumableSettingsDetailResource::withoutWrapping();
        return \App\Http\Resources\PackingDetailResource::collection($settings);
        
    }


    /**
     * Display the specified ProductionPackaging.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id, Request $request)
    {
        $productionPackaging = $this->productionPackagingRepository->find($id);

        if($this->checkEmpty($productionPackaging, $request)){
            return;
        }

        if($request->expectsJson()){
            return new \App\Http\Resources\Packing\ProductionPackingResource($productionPackaging);
        }else{
            return view('production_packagings.show')->with('productionPackaging', $productionPackaging);
        }
    }

    /**
     * Show the form for editing the specified ProductionPackaging.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $productionPackaging = $this->productionPackagingRepository->find($id);

        if (empty($productionPackaging)) {
            Flash::error('Production Packaging not found');

            return redirect(route('productionPackagings.index'));
        }

        return view('production_packagings.edit')->with('productionPackaging', $productionPackaging);
    }

    /**
     * Update the specified ProductionPackaging in storage.
     *
     * @param  int              $id
     * @param UpdateProductionPackagingRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateProductionPackagingRequest $request)
    {
        $productionPackaging = $this->productionPackagingRepository->find($id);

        if($this->checkEmpty($bondMaterialRecipe, $request)){
            return;
        }

        $productionPackaging = $this->productionPackagingRepository->update($request->all(), $id);

        if($request->expectsJson()){
            return  $this->sendResponseMessage('Production Packaging updated successfully.');;
        }else{
            Flash::success('Production Packaging updated successfully.');
            return redirect(route('productionPackagings.index'));
        }    
    }

    /**
     * Remove the specified ProductionPackaging from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id, Request $request)
    {
        $productionPackaging = $this->productionPackagingRepository->find($id);

        if($this->checkEmpty($productionPackaging, $request)){
            return;
        }

        $this->productionPackagingRepository->delete($id);

        if($request->expectsJson()){
            return  $this->sendResponseMessage('Production Packaging deleted successfully.');;
        }else{
            Flash::success('Production Packaging deleted successfully.');
            return redirect(route('productionPackagings.index'));
        }  

       
    }

    private function  checkEmpty($bondMaterialRecipe , $request){
        if (empty($bondMaterialRecipe)){
            if($request->expectsJson()){
                return $this->sendValidationError('Production Packaging not found');
            }else{
                Flash::error('Production Packaging not found');
                return redirect(route('productionPackagings.index'));
            }
        }
        return null;
    }
}
