<?php

namespace App\Http\Controllers\Api\Manufacturing;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Models\QualityCheck;
use App\Models\QualityCheckItem;
use App\Service\QualityCheckService;
use App\Service\SequenceService;

class QualityCheckController extends Controller
{

    //  create QualityCheck record
    public function qualityCheck_create(Request $request)
    {
        $validator=validator($request->all(),[
            'qc_id'=>'required',
            'date'=>'required',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try {

                $obj['qc_id'] = $request['qc_id'];
                $obj['date'] = $request['date'];
                $obj['item_check_id'] = $request['item_check_id']?? 0;
                $obj['production_id'] = $request['production_id'] ?? 0;
                $obj['batch_id'] = $request['batch_id'] ?? 0;
                $obj['remarks'] = $request['remarks'];
                $obj['attachments'] = $request['attachments'];
                $obj['status'] = $request['status'];

                // Update QualityCheck with QualityCheck id
                if ($request['id'] > 0) {
                    $qualityCheck = QualityCheck::where('id', $request['id'])->first();
                    $qualityCheck->update($obj);

                    QualityCheckItem::where('qc_id',$request['id'])->delete();

                    $qualityCheckItem=new QualityCheckService;
                    $qualityCheckItem->qualityCheckItem($request,$qualityCheck);

                    return response()->json(['success' => true, 'message' => 'QualityCheck updated successfully', 'quality_check' => $qualityCheck], 200);

                } else {
                    // Creating new QualityCheck
                    $qualityCheck = QualityCheck::create($obj);
                    
                    $qualityCheckItem=new QualityCheckService;
                    $qualityCheckItem->qualityCheckItem($request,$qualityCheck);

                    $module='quality_check';

                    // Update Sequence
                    $sequence=new SequenceService;
                    $sequence->updateSequence($module);

                    return response()->json(['success' => true, 'message' => 'QualityCheck  created successfully', 'quality_check' => $qualityCheck], 200);
                }
            } catch (\Exception $e) {
                
                return response()->json(['success' => false, 'message' => 'Failed to create QualityCheck ', 'error' => $e->getMessage()], 500);
            }
        }
    }
    
    public function qualityCheck_details(Request $request){

        $validator=validator($request->all(),[
            'qc_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try{

                $qualityCheck=QualityCheck::where('id',$request['qc_id'])
                    ->with('batch','production','quality_items')->first();

            }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return [
                    'success' => false,
                    'message' => 'QualityCheck not found'
                ];
            }
            
            $response=[
                'success'=>true,
                'qualityCheck'=>$qualityCheck,
                'message'=>'QualityCheck Details Fetch Successfully'
            ];

            return response()->json($response, 200);
        }
    }

    public function qualityCheck_list(Request $request){
        try{

            $qualityCheck=QualityCheck::with('entry_by','production')->where('rolledback',0);

            if($request['search']!=null && $request['search']!=''){

                $qualityCheck = $qualityCheck->where('qc_id', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('status', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('item_check_id', 'LIKE', '%' . $request['search'] . '%');
            }

            // get custom_date 
            if ($request['custom_date']!='' && isset($request['custom_date'])) {
                $customDate = $request->custom_date;
                $qualityCheck = $qualityCheck->whereDate('date', $customDate);
            }

            if ($request['from_date']!='' && isset($request['to_date'])) {

                $fromDate = $request->from_date;
    
                $toDate = $request->to_date;
    
                // 'fromDate' and 'toDate'
                $qualityCheck = $qualityCheck->whereBetween('date', [$fromDate, $toDate]);
    
            }

            if ($request['status']!='' && isset($request['status'])) {
                $status = $request->status;
                $qualityCheck = $qualityCheck->where('status', $status);
            }

            // Count all the items
            $qualityCheck_count=$qualityCheck->count();

            if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
                $sort_order=$request['sort_order']==1?'asc':'desc';
    
                $qualityCheck = $qualityCheck->orderby($request['sort_by'],$sort_order);
    
            }else{
                $qualityCheck = $qualityCheck->orderby('id','desc');
            }

            // Pagination
            $qualityCheck=$qualityCheck->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                // ->orderBy('id','desc')
                ->get();

        }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return [
                'success' => false,
                'message' => 'QualityCheck  Raw not found'
            ];
        }
        
        $response=[
            'success'=>true,
            'count'=>$qualityCheck_count,
            'qualityCheck'=>$qualityCheck,
            'message'=>'QualityCheck List Fetch Successfully'
        ];

        return response()->json($response, 200);
        
    }

    
    public function qualityCheck_delete(Request $request){

        $user=Auth::user();
        // Validate Item
        $validator=validator($request->all(),[
           'qc_id'=>'required|integer'
       ]);

       if ($validator->fails()) { 
           return [
               'success' => false, 
               'message' => $validator->errors()->first(),
           ];

       } else {

           try{
               $qualityCheck = QualityCheck::findOrFail($request['qc_id'])->first();

               $qualityCheck['rolledback']=1;
               $qualityCheck->update();

               $response=[
                   'success'=>true,
                   'message'=>'QualityCheck Deleted successfully.'
               ];
           } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
               // Return error message in JSON if ID not found
               return response()->json(['success'=>false,'message' => 'Invalid Id found'], 404);
           }

           return response()->json($response);

       }
    }

    public function status(Request $request){
        $validator=validator($request->all(),[
            'id'=>'required',
            'status'=>'required'
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try {

                $qualityCheck = QualityCheck::findOrFail($request['id']);
                $qualityCheck['status']=$request['status'];
                $qualityCheck->update();

                $response=[
                    'success'=>true,
                    'message'=>'QualityCheck Status Updated successfully.'
                ];

            }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['success'=>false,'message' => 'Invalid Id found'], 404);
            }

            return response()->json($response);
        }
    }
}
