<?php

namespace App\Livewire\ServiceOrders;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\ServiceOrder;
use App\Models\Customer;
use App\Models\Vehicle;
use App\Models\Technician;

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $status = '';
    public $priority = '';
    public $technician_id = '';
    public $date_from = '';
    public $date_to = '';
    public $sortBy = 'created_at';
    public $sortDirection = 'desc';

    protected $queryString = [
        'search' => ['except' => ''],
        'status' => ['except' => ''],
        'priority' => ['except' => ''],
        'technician_id' => ['except' => ''],
        'date_from' => ['except' => ''],
        'date_to' => ['except' => ''],
        'sortBy' => ['except' => 'created_at'],
        'sortDirection' => ['except' => 'desc'],
    ];

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingStatus()
    {
        $this->resetPage();
    }

    public function updatingPriority()
    {
        $this->resetPage();
    }

    public function updatingTechnicianId()
    {
        $this->resetPage();
    }

    public function sortBy($field)
    {
        if ($this->sortBy === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $field;
            $this->sortDirection = 'asc';
        }
        $this->resetPage();
    }

    public function deleteServiceOrder($id)
    {
        $serviceOrder = ServiceOrder::find($id);
        
        if ($serviceOrder) {
            $serviceOrder->delete();
            session()->flash('success', 'Service order deleted successfully!');
        } else {
            session()->flash('error', 'Service order not found.');
        }
    }

    public function updateStatus($id, $status)
    {
        $serviceOrder = ServiceOrder::find($id);
        
        if ($serviceOrder) {
            $serviceOrder->status = $status;
            
            if ($status === 'in_progress' && !$serviceOrder->started_at) {
                $serviceOrder->started_at = now();
            } elseif ($status === 'completed' && !$serviceOrder->completed_at) {
                $serviceOrder->completed_at = now();
            }
            
            $serviceOrder->save();
            session()->flash('success', 'Service order status updated successfully!');
        }
    }

    public function render()
    {
        $query = ServiceOrder::query()
            ->with(['customer', 'vehicle', 'assignedTechnician', 'serviceItems', 'parts']);

        // Apply search filter
        if ($this->search) {
            $query->where(function($q) {
                $q->where('order_number', 'like', '%' . $this->search . '%')
                  ->orWhere('customer_complaint', 'like', '%' . $this->search . '%')
                  ->orWhereHas('customer', function($q) {
                      $q->where('first_name', 'like', '%' . $this->search . '%')
                        ->orWhere('last_name', 'like', '%' . $this->search . '%');
                  })
                  ->orWhereHas('vehicle', function($q) {
                      $q->where('make', 'like', '%' . $this->search . '%')
                        ->orWhere('model', 'like', '%' . $this->search . '%')
                        ->orWhere('license_plate', 'like', '%' . $this->search . '%');
                  });
            });
        }

        // Apply filters
        if ($this->status) {
            $query->where('status', $this->status);
        }

        if ($this->priority) {
            $query->where('priority', $this->priority);
        }

        if ($this->technician_id) {
            $query->where('assigned_technician_id', $this->technician_id);
        }

        if ($this->date_from) {
            $query->whereDate('created_at', '>=', $this->date_from);
        }

        if ($this->date_to) {
            $query->whereDate('created_at', '<=', $this->date_to);
        }

        // Apply sorting
        $query->orderBy($this->sortBy, $this->sortDirection);

        $serviceOrders = $query->paginate(15);
        
        // Load additional data for filters
        $technicians = Technician::where('status', 'active')->orderBy('first_name')->get();
        
        // Quick stats
        $stats = [
            'total' => ServiceOrder::count(),
            'pending' => ServiceOrder::where('status', 'pending')->count(),
            'in_progress' => ServiceOrder::where('status', 'in_progress')->count(),
            'completed_today' => ServiceOrder::where('status', 'completed')
                ->whereDate('completed_at', today())->count(),
        ];

        return view('livewire.service-orders.index', [
            'serviceOrders' => $serviceOrders,
            'technicians' => $technicians,
            'stats' => $stats,
        ]);
    }
}
