<?php

namespace App\Http\Controllers\Api\Workshop;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Workshop\JobCard;
use App\Service\SequenceService;
use App\Service\ActivityService;

class JobCardController extends Controller
{
    // Job Card Create Update
    public function jobCardCreateUpdate(Request $request){

         $validator=validator($request->all(),[
            'check_in_type'=>'required',
            'vehicle_id'=>'required', 
            'vehicle_no'=>'required' 
        ]);

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

        } else {

            $obj['check_in_type']=$request['check_in_type'];   //1. New Customer 2. Existing Customer 3. Owned Vehicle
            $obj['customer_id']=$request['customer_id']??0;
            $obj['customer_name']=$request['customer_name'];
            $obj['customer_mobile']=$request['customer_mobile'];
            $obj['customer_email']=$request['customer_email'];

            $obj['driver_id']=$request['driver_id']??0;
            $obj['driver_name']=$request['driver_name'];
            $obj['driver_mobile']=$request['driver_mobile'];
            $obj['driver_license_no']=$request['driver_license_no'];

            $obj['vehicle_id']=$request['vehicle_id']??0;
            $obj['vehicle_no']=$request['vehicle_no'];
            $obj['vehicle_make']=$request['vehicle_make'];
            $obj['registration_no']=$request['registration_no'];
            $obj['year_of_manufacture']=$request['year_of_manufacture'];

            $obj['signature']=$request['signature'];
            $obj['arrival_date']=$request['arrival_date'];
            $obj['arrival_time']=$request['arrival_time'];
            $obj['customer_complaints']=$request['customer_complaints'];
            $obj['status']='Pending';

            if($request['id']>0){
                try {
                    
                    $job_card=JobCard::findOrFail($request['id']);
                    $job_card->update($obj);

                    // Creating Activities
                    $activity=new ActivityService;
                    $activity->activityCreateUpdate('Job Cart',$job_card['id'],'Updated');

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

                $obj['job_card_no']=$request['job_card_no'];

                $job_card=JobCard::create($obj);

                $module='job_card';

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

                 // Creating Activities
                $activity=new ActivityService;
                $activity->activityCreateUpdate('Job Cart',$job_card['id'],'Created');
            }

            $response=[
                'success'=>true,
                'message'=> $request['id']>0 ? 'Job Card Updated Successfully' : 'Job Card Created Successfully',
                'data'=>$job_card
            ];
            return response()->json($response);
        }   
    }

    // Job Card List
    public function jobcardList(Request $request){

        $job_card=JobCard::where('rolledback',0);
            
        if(isset($request['id']) && $request['id']>0){
            $job_card=$job_card->where('id',$request['id']);
        }

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

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

            $job_card = $job_card->where(function ($query) use ($request) {

                $query->where('job_card_no', 'LIKE', '%' . $request['search'] . '%')

                ->orWhereHas('vehicle', function ($query) use ($request) {
                    $query->where('vehicle_id', 'LIKE', '%' . $request['search'] . '%');
                });
            });
        }

        $count=$job_card->count();

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

        $response=[
            'success'=>true,
            'total'=>$count,
            'data'=>$job_card
        ];

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

    }

    // Job Card Details
    public function jobCarddetails(Request $request){
         // Validation user and name  of organisation

         $validator=validator($request->all(),[
            'id'=>'required',
        ]);

        if ($validator->fails()) { 

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

        } else {

            $job_card = JobCard::where('id',$request['id'])
                ->with('customer','vehicle','driver')
                ->first();

            $response=[
                'success'=>true,
                'message'=>'Job Card Details Fetched Successfully',
                'job_card'=>$job_card

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

    // Update Job Card Status
    public function jobCardStatus(Request $request){
          $validator=validator($request->all(),[
            'id'=>'required',
            'status'=>'required',
        ]);

        if ($validator->fails()) { 

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

        } else {
            try {
                $job_card=JobCard::findOrFail($request['id']);
            

                // $job_card=JobCard::findOrFail($request['id']);

                $job_card['status']=$request['status'];

                $job_card->update();

                $response=[
                    'success'=>true,
                    'message'=>"Job Card Status Updated Successfully",
                    'data'=>$job_card
                ];
            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['message' => 'Invalid Id to update '], 404);
            }
        }
    }

}
