<?php

namespace App\Http\Controllers\Api\Workshop;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Workshop\WorkshopVisualInspection;
use App\Models\Workshop\WorkshopInspectionChecklist;
use App\Models\Workshop\JobCard;
use App\Models\Workshop\WorkshopEstimate;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;

class WorkshopEstimatesController extends Controller
{
    // Get estimates for a job card
    public function getEstimates(Request $request)
    {
         $validator=validator($request->all(),[
            'job_card_id'=>'required'
        ]);

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

        } else {

            try {
                // Validate the job_card_id
            
                //job card
                $job_card=JobCard::findOrFail($request['job_card_id']);

                if($job_card){
                    
                    // Get estimates for the Visual Inspection
                    $visual_product_estimates = WorkshopVisualInspection::where('job_card_id', $job_card->id)
                        ->where('rolledback',0)
                        ->where('product_id', '!=', 0)
                        ->with('product');
                    
                    $visual_product_sum = $visual_product_estimates->sum('price');

                    $visual_product_estimates = $visual_product_estimates->get();

                    $visual_labour_estimates = WorkshopVisualInspection::where('job_card_id', $job_card->id)
                        ->where('labour_costs', '>', 0)
                        ->where('rolledback', 0);

                    $visual_labour_sum = $visual_labour_estimates->sum('labour_costs');
                    $visual_labour_hours = $visual_labour_estimates->sum('labour_hour');

                    $visual_labour_estimates = $visual_labour_estimates->get();

                    // Get estimates for the Inspection Checklist
                    $checklist_product_estimates = WorkshopInspectionChecklist::where('job_card_id', $job_card->id)
                        ->where('rolledback', 0)
                        ->where('product_id', '!=', 0)
                        ->with('product');

                    $checklist_product_sum = $checklist_product_estimates->sum('product_cost');
                    $checklist_product_estimates = $checklist_product_estimates->get();

                    $checklist_labour_estimates = WorkshopInspectionChecklist::where('job_card_id', $job_card->id)
                        ->where('estimated_cost', '>', 0)
                        ->where('rolledback', 0);

                    $checklist_labour_sum = $checklist_labour_estimates->sum('estimated_cost');
                    $checklist_labour_hours = $checklist_labour_estimates->sum('estimated_hrs');
                    $checklist_labour_estimates = $checklist_labour_estimates->get();

                    return [
                        'success' => true,
                        'message' => 'Estimates retrieved successfully',
                        'data' => [
                            'total_estimate_hours' => $visual_labour_hours + $checklist_labour_hours,
                            'total_labour_cost' =>  $visual_labour_sum + $checklist_labour_sum,
                            'total_product_cost' => $visual_product_sum + $checklist_product_sum,
                            'visual_product_estimates' => $visual_product_estimates,
                            'visual_product_sum' => $visual_product_sum,
                            'visual_labour_estimates' => $visual_labour_estimates,
                            'visual_labour_sum' => $visual_labour_sum,
                            'visual_labour_hours' => $visual_labour_hours,
                            'checklist_product_estimates' => $checklist_product_estimates,
                            'checklist_product_sum' => $checklist_product_sum,
                            'checklist_labour_estimates' => $checklist_labour_estimates,
                            'checklist_labour_sum' => $checklist_labour_sum,
                            'checklist_labour_hours' => $checklist_labour_hours,
                            'job_card' => $job_card
                        ]
                    ];
                } else {
                    return [
                        'success' => false,
                        'message' => 'Job Card not found'
                    ];
                }
            } catch (\Exception $e) {
                return [
                    'success' => false,
                    'message' => 'Invalid job card ID'
                ];
            }
        }
    }

    // Create and save a new estimate
    public function createEstimate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'job_card_id' => 'required|exists:job_cards,id',
            'total_product_cost' => 'nullable|numeric|min:0',
            'total_labour_cost' => 'nullable|numeric|min:0',
            'total_estimate_hours' => 'nullable|numeric|min:0',
        ]);
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];  
        }

        // Check if the job card exists
        $job_card = WorkshopEstimate::where('rolledback',0)->find($request->input('job_card_id'));
        if ($job_card) {
            return [
                'success' => false,
                'message' => 'Estimate For the Job Card Already exists'
            ];
        }

        $obj['job_card_id'] = $request->input('job_card_id');
        $obj['total_product_cost'] = $request->input('total_product_cost');
        $obj['total_labour_cost'] = $request->input('total_labour_cost');
        $obj['total_estimate_hours'] = $request->input('total_estimate_hours');
        $obj['charges'] = $request->input('charges');
        $obj['total_estimate'] = $request->input('total_estimate');

        if($request['id']>0){
            $estimates = WorkshopEstimate::find($request['id']);
            if(!$estimates){
                return [
                    'success' => false,
                    'message' => 'Estimate not found'
                ];
            }
            $estimates->update($obj);
        } else {
            $estimates=WorkshopEstimate::create($obj);
        }

        if (!$estimates) {
            return [
                'success' => false,
                'message' => 'Failed to create estimate'
            ];
        }
        return [
            'success' => true,
            'message' => 'Estimate created successfully',
            'data' => $estimates
        ];  

    }

    // Get all estimates
    public function getAllEstimates(Request $request)
    {
        $estimates = WorkshopEstimate::where('rolledback',0)->with('job_card');

        if($request['search']) {
            $search = $request['search'];
            $estimates = $estimates->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 = $estimates->count();
      
        $estimates = $estimates->orderBy('id', 'desc')
            ->skip($request['noofrec'] * ($request['currentpage'] - 1))
            ->take($request['noofrec'] ?? 100)
            ->get();

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

        return [
            'success' => true,
            'total' => $count,
            'message' => 'Estimates retrieved successfully',
            'data' => $estimates
        ];
    }

    // Get estimate details by ID
    public function getEstimateDetails(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|exists:workshop_estimates,id'
        ]);
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];
        }

        $estimate = WorkshopEstimate::with('job_card')->find($request->input('id'));

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

        return [
            'success' => true,
            'message' => 'Estimate retrieved successfully',
            'data' => $estimate
        ];
    }

    // Delete an estimate
    public function deleteEstimate(Request $request){

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

        $estimate = WorkshopEstimate::find($request->input('id'));

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

        $estimate['rolledback'] = 1;
        $estimate->save();

        return [
            'success' => true,
            'message' => 'Estimate deleted successfully'
        ];
    }

    //Estimates Approve by Customer
    public function approveEstimate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|exists:workshop_estimates,id',
            'approval_method' => 'required',

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

        $estimate = WorkshopEstimate::find($request->input('id'));
        if (!$estimate) {
            return [
                'success' => false,
                'message' => 'Estimate not found'
            ];
        }

        $estimate['status'] = 1; // Set status to approved
        $estimate['approval_method'] = $request->input('approval_method');     //Verbal , Written, Email, WhatsApp , Digital
        $estimate['customer_comments'] = $request->input('customer_comments');     
        $estimate['approval_date_time'] = Carbon::now(); // Set the approval date and time to now
        $estimate->save();

        return [
            'success' => true,
            'message' => 'Estimate approved successfully',
            'data' => $estimate
        ];
    }

    // Estimates Reject by customer
    public function rejectEstimate(Request $request){

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

        $estimate = WorkshopEstimate::find($request->input('id'));

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

        $estimate['status'] = 2; // Set status to Reject
        $estimate['customer_comments'] = $request->input('customer_comments');     
        $estimate['approval_date_time'] = Carbon::now(); // Set the approval date and time to now
        $estimate->save();

        return [
            'success' => true,
            'message' => 'Estimate rejected successfully',
            'data' => $estimate
        ];
    }
}