<?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\BondMaterialRecipeRepository;
use App\Models\BondMaterialRecipe;
/**
 * Class DemoController
 * @package App\Http\Controllers\API
 */

class MaterialAPIController extends AppBaseController
{
    private $bondMaterialRecipeRepository;

    public function __construct(BondMaterialRecipeRepository $bondMaterialRecipeRepo)
    {
        $this->bondMaterialRecipeRepository = $bondMaterialRecipeRepo;
    }

    // public function updateStatus(Request $request){
    //     $status = $request->get('status');
    //     $materialId = $request->get('material_id');
    //     $material = \App\Models\BondRecipeProductionStatus::where('material_id')->first();
    //     if($material->status->tag == 'COMPLETED'){
    //         return $this->sendValidationError('Material production is completed, Please contact to admin to update status.');
    //     }else{
    //         \App\Models\BondRecipeProductionStatus::updateProductionStatus($materialId, $status);
    //         return $this->sendResponseMessage( 'Bond production status updated successfully.');
    //     }
    // }

    public function listMaterial(Request $request){
        $query = $request->get('query');
        $status = $request->get('status');
        $bondMaterialRecipe=null;
        if(!empty($status)){
            return $this->getListOfMaterialWithStatus($status);
        }
        if(!empty($query)){
            $bondMaterialRecipe = BondMaterialRecipe::where('material_id','like','%'.$query.'%')->orderBy('created_at','DESC')->paginate(config('app_data.per_page_data'));
        }else{
            $bondMaterialRecipe = BondMaterialRecipe::orderBy('created_at','DESC')->paginate(config('app_data.per_page_data'));
        }
        

        return  new \App\Http\Resources\BasePaginationResourceCollection($bondMaterialRecipe, collect($bondMaterialRecipe->items()), \App\Http\Resources\Production\BondMaterialResource::class);
    }

    public function getBondProducts(){
        $bondProcess = \App\Models\BondProduct::orderBy('created_at', 'DESC')->get();
        \App\Http\Resources\Mini\MiniBondProductResource::withoutWrapping();
        return \App\Http\Resources\Mini\MiniBondProductResource::collection($bondProcess);
    }

    public function getMaterialFullDetail($materialId){
        $object = (object) ['materialId' => $materialId];
        //$object->materialId= $materialId;
        return new \App\Http\Resources\Production\BondMaterialFullResource($object);
    }

    public function getListOfReadyforProductionMaterial(){

        $status= 'READY_FOR_PRODUCTION';
        $orders = \App\Models\BondMaterialRecipe::leftJoin('bond_recipe_production_status', 'bond_material_recipes.material_id', '=', 'bond_recipe_production_status.material_id')
        ->rightJoin('production_status', function ($join) use ($status) {
         $join->on(
             'bond_recipe_production_status.status_id',
             '=',
             DB::raw("(SELECT id FROM production_status WHERE tag = '".$status."'  ORDER BY created_at DESC LIMIT 1)")
         );
    })
    ->select('bond_material_recipes.*', 'production_status.tag')
    ->groupBy('bond_material_recipes.material_id')
    ->orderBy('created_at','DESC')
    ->paginate(config('app_data.per_page_data'));
    
    if (!count($orders)) { 
       return $this->sendEmptyDataResponse();
    }
        //$bondRecipeProducton= \App\Models\BondRecipeProduction::select('*')->where('status', '!=', 'COMPLETED')->orderBy('created_at','desc')->orderByRaw(\DB::raw("FIELD(priority, URGENT,HIGH,MEDIUM,LOW )"))->get();
        return new \App\Http\Resources\BasePaginationResourceCollection($orders, collect($orders->items()), \App\Http\Resources\Production\BondMaterialResource::class);
     }


     public function getListOfMaterialWithStatus($status){
        
        $stat = \App\Models\ProductionStatus::where('tag', '=', $status)->first();
        if(!$stat){
            return $this->sendEmptyDataResponse();     
        }
        $status = $stat->id;

        $orders = \App\Models\BondMaterialRecipe::leftJoin('bond_recipe_production_status', 'bond_material_recipes.material_id', '=', 'bond_recipe_production_status.material_id')
        ->join('production_status', function ($join) use ($status) {
         $join->on(
             'bond_recipe_production_status.status_id',
             '=',
             DB::raw("(SELECT id FROM production_status WHERE id = ".$status."  ORDER BY created_at DESC LIMIT 1)")
         );
    })
    ->select('bond_material_recipes.*', 'production_status.tag')
    ->groupBy('bond_material_recipes.material_id')
    ->orderBy('created_at','DESC')
    ->paginate(config('app_data.per_page_data'));

    //dd($orders);
    
    if (!count($orders)) { 
       return $this->sendEmptyDataResponse();
    }
        //$bondRecipeProducton= \App\Models\BondRecipeProduction::select('*')->where('status', '!=', 'COMPLETED')->orderBy('created_at','desc')->orderByRaw(\DB::raw("FIELD(priority, URGENT,HIGH,MEDIUM,LOW )"))->get();
        return new \App\Http\Resources\BasePaginationResourceCollection($orders, collect($orders->items()), \App\Http\Resources\Production\BondMaterialResource::class);
     }

     public function updateStatus(Request $request){
        $input = $request->all();
        $validator = Validator::make($input, [
            "material_id" => "required|exists:bond_material_recipes"
        ]);
          if ($validator->fails()) 
           { 
             throw new \Illuminate\Validation\ValidationException($validator);
             //throw $error;
           }

         $materialId = $request->get('material_id');
         $pstatus = $request->get('status');
         $status = \App\Models\BondRecipeProductionStatus::where('material_id','=', $materialId)->orderBy('created_at','DESC')->first();
        if($status->status->tag == 'COMPLETED'){
            
            return $this->sendValidationError('You cant change production status, if status is completed');
        }
        $totalQCFreshQty = \App\Models\QualityCheck::getTotalProductionFreshQty($materialId);
        $totalQCQty = \App\Models\QualityCheck::getTotalProduction($materialId);
        $packedQty = \App\Models\ProductionPackaging::getTotalPackedQty($materialId);
        $producedPcs = BondMaterialRecipe:: getTotalProductionPcs($materialId);
        if($pstatus=='COMPLETED'){
            if($totalQCQty< $producedPcs){
                return $this->sendValidationError('You cant change production status to completed,'
                 .'<br>it has qty '.($producedPcs-$totalQCQty).' pcs which are not quality checked <br> here is full production detail of material <br>'.
                 'Total Produced Pcs: '.$producedPcs.' pcs <br>'.
                'Total QC Pcs : '.$totalQCQty.' pcs <br>'.
                'Total Packed Qty : '.$packedQty.' pcs');
            }
            if($packedQty < $totalQCFreshQty){
                return $this->sendValidationError('You cant change production status to completed,'.
                '<br>it has qty '.($totalQCQty-$packedQty).' pcs which are not packed ,  please generate packing id for them. <br> here is full production detail of material <br>'.
                'Total Produced Pcs: '.$producedPcs.' pcs <br>'.
                'Total QC Pcs(without Rej) : '.$totalQCFreshQty.' pcs <br>'.
                'Total QC Pcs : '.$totalQCQty.' pcs <br>'.
                'Total Packed Qty : '.$packedQty.' pcs');
            }
        }
        

        \App\Models\BondRecipeProductionStatus::updateProductionStatus($materialId, $pstatus);  
        
        return $this->sendResponseMessage('Production status sucessfully updated');
     }
}

