<?php

namespace App\Livewire\JobCards;

use Livewire\Component;
use App\Models\JobCard;
use App\Models\Customer;
use App\Models\Vehicle;
use App\Models\User;
use App\Services\WorkflowService;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Create extends Component
{
    use AuthorizesRequests;
    public $customer_id = '';
    public $vehicle_id = '';
    public $service_advisor_id = '';
    public $branch_code = '';
    public $arrival_datetime = '';
    public $expected_completion_date = '';
    public $mileage_in = '';
    public $fuel_level_in = '';
    public $customer_reported_issues = '';
    public $vehicle_condition_notes = '';
    public $keys_location = '';
    public $personal_items_removed = false;
    public $photos_taken = false;
    public $priority = 'medium';
    public $notes = '';

    // Inspection fields
    public $perform_inspection = true;
    public $inspector_id = '';
    public $overall_condition = '';
    public $inspection_notes = '';
    public $inspection_checklist = [];

    public $customers = [];
    public $vehicles = [];
    public $serviceAdvisors = [];
    public $inspectors = [];

    protected function rules()
    {
        return [
            'customer_id' => 'required|exists:customers,id',
            'vehicle_id' => 'required|exists:vehicles,id',
            'service_advisor_id' => 'required|exists:users,id',
            'branch_code' => 'required|string|max:10',
            'arrival_datetime' => 'required|date',
            'expected_completion_date' => 'nullable|date|after:arrival_datetime',
            'mileage_in' => 'nullable|integer|min:0',
            'fuel_level_in' => 'nullable|string|max:20',
            'customer_reported_issues' => 'required|string|max:2000',
            'vehicle_condition_notes' => 'nullable|string|max:1000',
            'keys_location' => 'nullable|string|max:255',
            'personal_items_removed' => 'boolean',
            'photos_taken' => 'boolean',
            'priority' => 'required|in:low,medium,high,urgent',
            'notes' => 'nullable|string|max:2000',
            'inspector_id' => 'required_if:perform_inspection,true|exists:users,id',
            'overall_condition' => 'required_if:perform_inspection,true|string|max:500',
            'inspection_notes' => 'nullable|string|max:1000',
        ];
    }

    public function mount()
    {
        // Check if user has permission to create job cards
        $this->authorize('create', JobCard::class);
        
        $this->branch_code = auth()->user()->branch_code ?? config('app.default_branch_code', 'ACC');
        $this->arrival_datetime = now()->format('Y-m-d\TH:i');
        $this->loadData();
        $this->initializeInspectionChecklist();
    }

    public function loadData()
    {
        $user = auth()->user();
        
        $this->customers = Customer::orderBy('first_name')->get();
        
        // Filter service advisors based on user's permissions and branch
        $this->serviceAdvisors = User::whereIn('role', ['service_advisor', 'service_supervisor'])
            ->where('status', 'active')
            ->when(!$user->hasPermission('job-cards.view-all'), function ($query) use ($user) {
                return $query->where('branch_code', $user->branch_code);
            })
            ->orderBy('name')
            ->get();
            
        $this->inspectors = User::whereIn('role', ['service_supervisor', 'quality_inspector'])
            ->where('status', 'active')
            ->when(!$user->hasPermission('job-cards.view-all'), function ($query) use ($user) {
                return $query->where('branch_code', $user->branch_code);
            })
            ->orderBy('name')
            ->get();
    }

    public function updatedCustomerId()
    {
        if ($this->customer_id) {
            $this->vehicles = Vehicle::where('customer_id', $this->customer_id)
                ->orderBy('year', 'desc')
                ->orderBy('make')
                ->orderBy('model')
                ->get();
        } else {
            $this->vehicles = [];
            $this->vehicle_id = '';
        }
    }

    public function initializeInspectionChecklist()
    {
        $this->inspection_checklist = [
            'exterior_damage' => false,
            'interior_condition' => false,
            'tire_condition' => false,
            'fluid_levels' => false,
            'lights_working' => false,
            'battery_condition' => false,
            'belts_hoses' => false,
            'air_filter' => false,
            'brake_condition' => false,
            'suspension' => false,
        ];
    }

    public function save()
    {
        // Check if user still has permission to create job cards
        $this->authorize('create', JobCard::class);
        
        $this->validate();

        try {
            $workflowService = app(WorkflowService::class);
            
            $data = [
                'customer_id' => $this->customer_id,
                'vehicle_id' => $this->vehicle_id,
                'service_advisor_id' => $this->service_advisor_id,
                'branch_code' => $this->branch_code,
                'arrival_datetime' => $this->arrival_datetime,
                'expected_completion_date' => $this->expected_completion_date,
                'mileage_in' => $this->mileage_in,
                'fuel_level_in' => $this->fuel_level_in,
                'customer_reported_issues' => $this->customer_reported_issues,
                'vehicle_condition_notes' => $this->vehicle_condition_notes,
                'keys_location' => $this->keys_location,
                'personal_items_removed' => $this->personal_items_removed,
                'photos_taken' => $this->photos_taken,
                'priority' => $this->priority,
                'notes' => $this->notes,
            ];

            if ($this->perform_inspection) {
                $data['inspector_id'] = $this->inspector_id;
                $data['inspection_checklist'] = $this->inspection_checklist;
                $data['overall_condition'] = $this->overall_condition;
                $data['inspection_notes'] = $this->inspection_notes;
            }

            $jobCard = $workflowService->createJobCard($data);

            session()->flash('success', 'Job card created successfully! Job Card #: ' . $jobCard->job_card_number);
            
            return redirect()->route('job-cards.show', $jobCard);

        } catch (\Exception $e) {
            session()->flash('error', 'Failed to create job card: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.job-cards.create');
    }
}
