<?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 ConsumableConsumptionAPIController extends AppBaseController
{
    public function createConsumption(Request $request){
         
        $input = $request->all();
        //dd($input);

        $request->validate(\App\Models\ConsumableConsumpation::$rules);

        $array = json_decode($input['data'], true);
         $this->validateParam($array); 
        
    
         $consumption = \App\Models\ConsumableConsumpation::create([
             'name' => $input['name'],
             'change_date' => $input['change_date'],
             'narration' => $input['narration'],
             'change_reason' => $input['change_reason'],
             'created_at' => \Carbon\Carbon::now(),
         ]);   

        
        $this->saveConsumptionDetail($array, $consumption->id);    
        
        \App\Http\Resources\Consumable\ConsumableConsumpationResource::withoutWrapping();
        $packing = \App\Models\ConsumableConsumpation::find($consumption->id);
        //dd($packing);
        return $this->sendResponse(new \App\Http\Resources\Consumable\ConsumableConsumpationResource($packing), "Consumption Created Successfully");

    }

    public function listConsumption(Request $request){
        $query = $request->get('query');
        $consumptions=null;
        $user = Auth::user();

        if ($user->hasPermission('limitlist.consumableconsumpation')) { // you can pass an id or slug
            $consumptions = \App\Models\ConsumableConsumpation::orderBy('created_at','DESC')->take(config('app_data.limit_list_count'))->get();
            return  new \App\Http\Resources\LimitlistPaginationResourceCollection($consumptions, \App\Http\Resources\Consumable\ConsumableConsumpationResource::class);      
        }else{
            if(!empty($query)){
                $consumptions = \App\Models\ConsumableConsumpation::where('name','like','%'.$query.'%')->orderBy('created_at', 'DESC')->paginate(config('app_data.per_page_data'));
            }else{
                $consumptions = \App\Models\ConsumableConsumpation::orderBy('created_at', 'DESC')->paginate(config('app_data.per_page_data'));
            }
        }

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

    public function updateConsumption($id, Request $request){

        $request->validate(\App\Models\ConsumableConsumpation::$rules);

        $input = $request->all();
        $array = json_decode($input['data'], true);
        $this->validateParam($array); 
       // dd($input)
        
        $consumption = \App\Models\ConsumableConsumpation::find($id);    
        
        $consumption->update([
            'name' => $input['name'],
            'change_date' => $input['change_date'],
            'narration' => $input['narration'],
            'change_reason' => $input['change_reason']
        ]);
        
        $this->saveConsumptionDetail($array, $consumption->id);    
       
        \App\Http\Resources\Consumable\ConsumableConsumpationResource::withoutWrapping();
        $packing = \App\Models\ConsumableConsumpation::find($consumption->id);
       //dd($packing);
       return $this->sendResponse(new \App\Http\Resources\Consumable\ConsumableConsumpationResource($packing), "Consumption Updated Successfully");

   }


   public function deleteConsumption($id){
    $packing = \App\Models\ConsumableConsumpation::find($id);    
    if(!$packing){
        return $this->sendValidationError("Consumption entry not found.");
    }
    $packing->delete();
   return $this->sendResponseMessage("Consumption Deleted Successfully");
}

    private function validateParam($array){
        $rules = [
            '*.consumable_id' => 'required|integer|exists:consumable_items,id',
            '*.qty' => 'required|numeric|min:0',
            '*.consumed_percentage' => 'numeric|min:0|max:100'
        ];   
        
        $validator = Validator::make($array, $rules);
        //dd($input['data']);

       // $request->validate($rules);
        if ($validator->fails()) 
         { 
            //dd($validator->errors());
           $error = \Illuminate\Validation\ValidationException::withMessages($validator->errors()->getMessages());
           throw $error;
         }
    }

    private function saveConsumptionDetail($array, $consumptionId){
        \App\Models\ConsumableConsumpationDetail::where('consumpation_id','=', $consumptionId)->delete();
        foreach( $array as $item){
            $obj= \App\Models\ConsumableConsumpationDetail::create([
                'created_by' => \Auth::user()->id,
                'consumpation_id' => $consumptionId, 
                'consumable_id' => $item['consumable_id'],
                'consumed_percentage' => $item['consumed_percentage'],
                'qty' => $item['qty'],
                'created_at' => \Carbon\Carbon::now(),
            ]);
        }
    }

}

