<?php
namespace App\Http\Controllers\API;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Response;
use App\Http\Resources\User\UserResource;
use Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Log;
use Carbon\Carbon;
use App\Repositories\BondRecipeProductionRepository;
/**
 * Class DemoController
 * @package App\Http\Controllers\API
 */

class PackagingAPIController extends AppBaseController
{
    public function createPackaging(Request $request){
         
        $input = $request->all();
        $this->validatePackingParam($input);
        $array = json_decode($input['data'], true);
         $this->validateParam($array); 
        // dd($input);
         foreach( $array as $item){
            $check = \App\Http\Controllers\ProductionPackagingController::validateQuantity($request, $item['material_id'], $item['qty'], null);
            if($check){
                return $this->sendValidationError($check);
             }
        }
         
         $packingId = \App\Models\SensitiveCRUDAwareModel::generateMaterialId(6);    
         $packing = \App\Models\ProductionPackaging::create([
             'packing_id' => $packingId,
             'qty' => 0,
             'weight' => (float)$input['weight']
         ]);   
        $this->savePackagingDetail($array, $packingId);    
        
        \App\Http\Resources\PackingDetailResource::withoutWrapping();
        $packing = \App\Models\ProductionPackaging::find($packingId);
        //dd($packing);
        return $this->sendResponse(new \App\Http\Resources\Packing\ProductionPackingResource($packing), "Packaging Created Successfully");

    }


    public function updatePackaging($id, Request $request){
        $input = $request->all();
        $this->validatePackingParam($input);
        $invoiceDetails = \App\Models\BondInvoiceDetail::where('packing_id','=', $id)->first();
        if(!empty($invoiceDetails)){
            return $this->sendValidationError("Packing ".$id." seems to be sold out, you cannot make any change to packing after selling it");
        }

        $array = json_decode($input['data'], true);
        $this->validateParam($array); 
        $packing = \App\Models\ProductionPackaging::find($id);   
       // dd($input);
        foreach( $array as $item){
           $check = \App\Http\Controllers\ProductionPackagingController::validateQuantity($request, $item['material_id'], $item['qty'], $packing);
           if($check){
               return $this->sendValidationError($check);
            }
       }
        
        $packing = \App\Models\ProductionPackaging::find($id);    
        $packing->update([
            "weight" => $input['weight']
        ]);    
        $this->savePackagingDetail($array, $packing->packing_id);    
       
       \App\Http\Resources\PackingDetailResource::withoutWrapping();
       $packing = \App\Models\ProductionPackaging::find($packing->packing_id);
       //dd($packing);
       return $this->sendResponse(new \App\Http\Resources\Packing\ProductionPackingResource($packing), "Packaging Updated Successfully");

   }


   public function deletePackaging($id){
    $invoiceDetails = \App\Models\BondInvoiceDetail::where('packing_id','=', $id)->first();
    if(!empty($invoiceDetails)){
        return $this->sendValidationError("Packing ".$id." seems to be sold out, you cannot delete packing after selling it");
    }

    $packing = \App\Models\ProductionPackaging::find($id);    
    if(!$packing){
        return $this->sendValidationError("Packing not found.");
    }
    $packing->delete();
   return $this->sendResponseMessage("Packaging Deleted Successfully");
}


public function viewPackaging($id){
    $packing = \App\Models\ProductionPackaging::find($id);    
    if(!$packing){
        return $this->sendValidationError("Packing not found.");
    }
    
   return new \App\Http\Resources\Packing\ProductionPackingResource($packing);
}

public function viewPackagingSold($id){
    $packing = \App\Models\ProductionPackaging::find($id);    
    if(!$packing){
        return $this->sendValidationError("Packing not found.");
    }

    $soldPacking = \App\Models\BondInvoiceDetail::where('packing_id','=', $id)->first();
    if(!empty($soldPacking)){
        return $this->sendValidationError("Packing already sold, please enter another packing");
    }
   return new \App\Http\Resources\Packing\ProductionPackingResource($packing);
}

    private function validateParam($array){
        $rules = [
            '*.material_id' => 'required|integer|exists:bond_material_recipes,material_id',
            '*.qty' => 'required|numeric'
        ];   
        
        $validator = Validator::make($array, $rules);
        //dd($input['data']);

       // $request->validate($rules);
        if ($validator->fails()) 
         { 
           throw new \Illuminate\Validation\ValidationException($validator);
           //throw $error;
         }
    }


    private function validatePackingParam($array){
        $rules = [
            'weight' => 'required|numeric'
        ];   
        
        $validator = Validator::make($array, $rules);
        //dd($input['data']);

       // $request->validate($rules);
        if ($validator->fails()) 
         { 
           throw new \Illuminate\Validation\ValidationException($validator);
           //throw $error;
         }
    }

    public function listPackaging(Request $request){
        $query = $request->get('query');
        $consumptions =null;

        $user = Auth::user();
        if ($user->hasPermission('limitlist.productionpackagings')) { // you can pass an id or slug
            $consumptions = \App\Models\ProductionPackaging::orderBy('created_at','DESC')->where('created_by',$user->id)->take(config('app_data.limit_list_count'))->get();
            return  new \App\Http\Resources\LimitlistPaginationResourceCollection($consumptions, \App\Http\Resources\Packing\ProductionPackingResource::class);      
        }else if($user->hasPermission('list.productionpackagings')){
            if(!empty($query)){
                $consumptions = \App\Models\ProductionPackaging::where('packing_id','like','%'.$query.'%')->orderBy('created_at', 'DESC')->paginate(config('app_data.per_page_data'));
            }else{
                $consumptions = \App\Models\ProductionPackaging::orderBy('created_at', 'DESC')->paginate(config('app_data.per_page_data'));    
            }
        }else{
            return $this->sendValidationError('Access denied, please contact to admin');
        }

        
        
        return new \App\Http\Resources\BasePaginationResourceCollection($consumptions, collect($consumptions->items()), \App\Http\Resources\Packing\ProductionPackingResource::class);
    }

    private function savePackagingDetail($array, $packingId){
        \App\Models\ProductionPackagingDetail::where('packing_id','=', $packingId)->delete();
        foreach( $array as $item){
            $obj= \App\Models\ProductionPackagingDetail::create([
                'packing_id' => $packingId, 
                'material_id' => $item['material_id'],
                'qty' => $item['qty'],
                'created_at' => \Carbon\Carbon::now(),
                'created_by' => \Auth::user()->id
            ]);
        }
        \App\Models\ProductionPackaging::updateQty($packingId);
    }

}

