<?php

namespace App\Http\Controllers\Api\Workshop;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Workshop\WorkshopJobAllocation;
use Carbon\Carbon;
use Validator;

class JobAllocationController extends Controller
{
    //Create Job Allocation
    public function createJobAllocation(Request $request){

        $validator = Validator::make($request->all(), [
            'job_card_id' => 'required|exists:job_cards,id',
        ]);
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];  
        }

        $obj['job_card_id']=$request['job_card_id'];
        $obj['job_user_type']=$request['job_user_type'];
        $obj['user_id']=$request['user_id']??0;
        $obj['user_name']=$request['user_name']??null;
        $obj['allocated_by']=$request['allocated_by']??0;
        $obj['priority_level']=$request['priority_level'];   //Urgent, Standard , Low
        $obj['planned_start_time']=$request['planned_start_time']??null;
        $obj['planned_end_time']=$request['planned_end_time']??null;

        $obj['job_status']='Assigned';    //Assigned  ,2-In Prgress , 3-On hold , 4-Completed
        $obj['remarks']=$request['remarks']??null;    

        if($request['id']>0){
            $job_allocation = WorkshopJobAllocation::find($request['id']);

            if(!$job_allocation){
                return [
                    'success' => false,
                    'message' => 'Job Allocation not found'
                ];
            }

            $job_allocation->update($obj);

        }else{
            $job_allocation=WorkshopJobAllocation::create($obj);
        }

        return [
            'success' => true,
            'message' => 'Job allocated successfully',
            'data'=> $job_allocation
        ];

    }

    // Job Allocation Lists
    public function jobAllocationLists(Request $request){

        $job_allocation=WorkshopJobAllocation::where('rolledback',0)
            ->with('job_card','user:id,display_name');

         if($request['search']) {
            $search = $request['search'];
            $job_allocation = $job_allocation->where(function($query) use ($search) {
                $query->where('id', 'LIKE', "%{$search}%")
                      ->orWhereHas('job_card', function($q) use ($search) {
                          $q->where('job_card_no', 'LIKE', "%{$search}%");
                      });
            });
        }

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

        if ($job_allocation->isEmpty()) {
            return [
                'success' => false,
                'message' => 'No Job allocation found'
            ];
        }

        return [
            'success' => true,
            'total' => $count,
            'message' => 'Job Allocations retrieved successfully',
            'data' => $job_allocation
        ];

    }

    // Job Allocation Details
    public function jobAllocationDetails(Request $request){

        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];  
        }

         $job_allocation = WorkshopJobAllocation::with('job_card','user')->find($request->input('id'));

        if (!$job_allocation) {
            return [
                'success' => false,
                'message' => 'Job Allocation not found'
            ];
        }
         return [
            'success' => true,
            'message' => 'Job Allocation Detail fetched successfully',
            'data' => $job_allocation
        ];
    }

    // Job Allocation Start
    public function jobAllocationStart(Request $request){

         $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];  
        }

        $job_allocation = WorkshopJobAllocation::find($request->input('id'));

         if (!$job_allocation) {
            return [
                'success' => false,
                'message' => 'Job Allocation not found to start'
            ];
        }

        $job_allocation['actual_start_time']=$request['actual_start_time']??Carbon::now();

        $job_allocation['job_status']='In Progress';

        $job_allocation->update();

       
         return [
            'success' => true,
            'message' => 'Job Allocation Work Started',
            'data' => $job_allocation
        ];
    }

    // Job Allocation End
    public function jobAllocationEnd(Request $request){

         $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];  
        }

        $job_allocation = WorkshopJobAllocation::find($request->input('id'));

         if (!$job_allocation) {
            return [
                'success' => false,
                'message' => 'Job Allocation not found to start'
            ];
        }

        $job_allocation['actual_end_time']=$request['actual_end_time']??Carbon::now();

        $job_allocation['job_status']='Completed';

        $job_allocation->update();

       
         return [
            'success' => true,
            'message' => 'Job Allocation Work Completed',
            'data' => $job_allocation
        ];
    }

    // Job Allocation Delayed
    public function jobAllocationDelay(Request $request){

         $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];  
        }

        $job_allocation = WorkshopJobAllocation::find($request->input('id'));

        if (!$job_allocation) {
            return [
                'success' => false,
                'message' => 'Job Allocation not found to start'
            ];
        }

        $job_allocation['job_status']='Delayed';
        $job_allocation['delay_reason']=$request['delay_reason']??null;

        $job_allocation->update();

        
         return [
            'success' => true,
            'message' => 'Job Allocation Work delayed reason set',
            'data' => $job_allocation
        ];
    }

}
