<?php

namespace App\Livewire\JobCards;

use Livewire\Component;
use App\Models\JobCard;
use App\Models\Customer;
use App\Models\Vehicle;
use App\Models\User;

class Edit extends Component
{
    public JobCard $jobCard;
    public $customers = [];
    public $vehicles = [];
    public $serviceAdvisors = [];
    
    public $form = [];

    public function mount(JobCard $jobCard)
    {
        $this->jobCard = $jobCard;
        $this->loadData();
        $this->initializeForm();
    }

    public function initializeForm()
    {
        $this->form = [
            'customer_id' => $this->jobCard->customer_id,
            'vehicle_id' => $this->jobCard->vehicle_id,
            'service_advisor_id' => $this->jobCard->service_advisor_id,
            'status' => $this->jobCard->status,
            'arrival_datetime' => $this->jobCard->arrival_datetime ? $this->jobCard->arrival_datetime->format('Y-m-d\TH:i') : '',
            'expected_completion_date' => $this->jobCard->expected_completion_date ? $this->jobCard->expected_completion_date->format('Y-m-d\TH:i') : '',
            'completion_datetime' => $this->jobCard->completion_datetime ? $this->jobCard->completion_datetime->format('Y-m-d\TH:i') : '',
            'priority' => $this->jobCard->priority,
            'mileage_in' => $this->jobCard->mileage_in,
            'mileage_out' => $this->jobCard->mileage_out,
            'fuel_level_in' => $this->jobCard->fuel_level_in,
            'fuel_level_out' => $this->jobCard->fuel_level_out,
            'keys_location' => $this->jobCard->keys_location,
            'delivery_method' => $this->jobCard->delivery_method,
            'customer_reported_issues' => $this->jobCard->customer_reported_issues,
            'vehicle_condition_notes' => $this->jobCard->vehicle_condition_notes,
            'notes' => $this->jobCard->notes,
            'customer_satisfaction_rating' => $this->jobCard->customer_satisfaction_rating,
            'personal_items_removed' => (bool) $this->jobCard->personal_items_removed,
            'photos_taken' => (bool) $this->jobCard->photos_taken,
        ];
    }

    public function loadData()
    {
        $user = auth()->user();
        
        $this->customers = Customer::orderBy('first_name')->get();
        $this->vehicles = Vehicle::orderBy('make')->orderBy('model')->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->hasRole(['admin', 'manager']), function ($query) use ($user) {
                return $query->where('branch_code', $user->branch_code);
            })
            ->orderBy('name')
            ->get();
    }

    protected function rules()
    {
        return [
            'form.customer_id' => 'required|exists:customers,id',
            'form.vehicle_id' => 'required|exists:vehicles,id',
            'form.service_advisor_id' => 'nullable|exists:users,id',
            'form.status' => 'required|string|in:received,in_diagnosis,estimate_sent,approved,in_progress,quality_check,completed,delivered,cancelled',
            'form.arrival_datetime' => 'required|date',
            'form.expected_completion_date' => 'nullable|date|after:form.arrival_datetime',
            'form.completion_datetime' => 'nullable|date',
            'form.priority' => 'required|in:low,medium,high,urgent',
            'form.mileage_in' => 'nullable|integer|min:0',
            'form.mileage_out' => 'nullable|integer|min:0|gte:form.mileage_in',
            'form.fuel_level_in' => 'nullable|string|in:empty,1/4,1/2,3/4,full',
            'form.fuel_level_out' => 'nullable|string|in:empty,1/4,1/2,3/4,full',
            'form.keys_location' => 'nullable|string|max:255',
            'form.delivery_method' => 'nullable|string|in:pickup,delivery,towing',
            'form.customer_reported_issues' => 'nullable|string|max:2000',
            'form.vehicle_condition_notes' => 'nullable|string|max:1000',
            'form.notes' => 'nullable|string|max:2000',
            'form.customer_satisfaction_rating' => 'nullable|integer|min:1|max:5',
            'form.personal_items_removed' => 'boolean',
            'form.photos_taken' => 'boolean',
        ];
    }

    public function save()
    {
        try {
            // Debug: Log form data
            \Log::info('Form data before validation:', $this->form);
            
            $this->validate();

            // Filter out empty values for optional fields
            $updateData = [
                'customer_id' => $this->form['customer_id'],
                'vehicle_id' => $this->form['vehicle_id'],
                'status' => $this->form['status'],
                'arrival_datetime' => $this->form['arrival_datetime'],
                'priority' => $this->form['priority'],
                'personal_items_removed' => (bool) ($this->form['personal_items_removed'] ?? false),
                'photos_taken' => (bool) ($this->form['photos_taken'] ?? false),
            ];

            // Add service advisor if provided
            if (!empty($this->form['service_advisor_id'])) {
                $updateData['service_advisor_id'] = $this->form['service_advisor_id'];
            }

            // Add optional fields only if they have values
            if (!empty($this->form['expected_completion_date'])) {
                $updateData['expected_completion_date'] = $this->form['expected_completion_date'];
            }

            if (!empty($this->form['completion_datetime'])) {
                $updateData['completion_datetime'] = $this->form['completion_datetime'];
            }

            if (!empty($this->form['mileage_in'])) {
                $updateData['mileage_in'] = (int) $this->form['mileage_in'];
            }

            if (!empty($this->form['mileage_out'])) {
                $updateData['mileage_out'] = (int) $this->form['mileage_out'];
            }

            if (!empty($this->form['fuel_level_in'])) {
                $updateData['fuel_level_in'] = $this->form['fuel_level_in'];
            }

            if (!empty($this->form['fuel_level_out'])) {
                $updateData['fuel_level_out'] = $this->form['fuel_level_out'];
            }

            if (!empty($this->form['keys_location'])) {
                $updateData['keys_location'] = $this->form['keys_location'];
            }

            if (!empty($this->form['delivery_method'])) {
                $updateData['delivery_method'] = $this->form['delivery_method'];
            }

            if (!empty($this->form['customer_satisfaction_rating'])) {
                $updateData['customer_satisfaction_rating'] = (int) $this->form['customer_satisfaction_rating'];
            }

            // Add text fields even if empty (they can be null)
            $updateData['customer_reported_issues'] = $this->form['customer_reported_issues'] ?? null;
            $updateData['vehicle_condition_notes'] = $this->form['vehicle_condition_notes'] ?? null;
            $updateData['notes'] = $this->form['notes'] ?? null;

            \Log::info('Update data:', $updateData);
            
            $this->jobCard->update($updateData);

            session()->flash('success', 'Job card updated successfully!');
            
            return redirect()->route('job-cards.show', $this->jobCard);

        } catch (\Illuminate\Validation\ValidationException $e) {
            \Log::error('Validation error:', $e->errors());
            // Re-throw validation exceptions so they are handled by Livewire
            throw $e;
        } catch (\Exception $e) {
            \Log::error('Update error:', ['message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
            session()->flash('error', 'Failed to update job card: ' . $e->getMessage());
            $this->dispatch('show-error', message: 'Failed to update job card: ' . $e->getMessage());
        }
    }

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