<?php

namespace App\Livewire\Customers;

use App\Models\Customer;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $status = '';
    public $sortBy = 'created_at';
    public $sortDirection = 'desc';

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

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

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

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

    public function deleteCustomer($customerId)
    {
        $customer = Customer::findOrFail($customerId);
        
        // Check if customer has any service orders or vehicles
        if ($customer->serviceOrders()->count() > 0 || $customer->vehicles()->count() > 0) {
            session()->flash('error', 'Cannot delete customer with existing vehicles or service orders. Please remove or transfer them first.');
            return;
        }
        
        $customerName = $customer->full_name;
        
        // Also delete associated user account if exists
        if ($customer->user) {
            $customer->user->delete();
        }
        
        $customer->delete();
        
        session()->flash('success', "Customer {$customerName} and associated user account have been deleted successfully.");
    }

    public function render()
    {
        $customers = Customer::query()
            ->with(['vehicles', 'user'])
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('first_name', 'like', '%' . $this->search . '%')
                      ->orWhere('last_name', 'like', '%' . $this->search . '%')
                      ->orWhere('email', 'like', '%' . $this->search . '%')
                      ->orWhere('phone', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->status, function ($query) {
                $query->where('status', $this->status);
            })
            ->orderBy($this->sortBy, $this->sortDirection)
            ->paginate(15);

        return view('livewire.customers.index', [
            'customers' => $customers,
        ]);
    }
}
