<?php

namespace App\Livewire\JobCards;

use App\Models\Branch;
use App\Models\JobCard;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use AuthorizesRequests, WithPagination;

    public $search = '';

    public $statusFilter = '';

    public $branchFilter = '';

    public $sortBy = 'created_at';

    public $sortDirection = 'desc';

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

    public function mount()
    {
        $this->authorize('viewAny', JobCard::class);
    }

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

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

    public function updatingBranchFilter()
    {
        $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 getJobCardsProperty()
    {
        $user = auth()->user();
        $query = JobCard::with(['customer', 'vehicle'])
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('job_card_number', 'like', '%'.$this->search.'%')
                        ->orWhereHas('customer', function ($customerQuery) {
                            $customerQuery->where('name', 'like', '%'.$this->search.'%')
                                ->orWhere('phone', 'like', '%'.$this->search.'%');
                        })
                        ->orWhereHas('vehicle', function ($vehicleQuery) {
                            $vehicleQuery->where('license_plate', 'like', '%'.$this->search.'%')
                                ->orWhere('make', 'like', '%'.$this->search.'%')
                                ->orWhere('model', 'like', '%'.$this->search.'%');
                        });
                });
            })
            ->when($this->statusFilter, function ($query) {
                $query->where('status', $this->statusFilter);
            })
            ->when($this->branchFilter, function ($query) {
                $query->where('branch_code', $this->branchFilter);
            });

        // Apply permissions
        if (! $user->hasPermission('job-cards.view-all')) {
            if ($user->hasPermission('job-cards.view-own')) {
                $query->where('service_advisor_id', $user->id);
            } elseif ($user->branch_code) {
                $query->where('branch_code', $user->branch_code);
            }
        }

        return $query->orderBy($this->sortBy, $this->sortDirection);
    }

    public function getStatisticsProperty()
    {
        $user = auth()->user();
        $baseQuery = JobCard::query();

        // Apply same permission filters as main query
        if (! $user->hasPermission('job-cards.view-all')) {
            if ($user->hasPermission('job-cards.view-own')) {
                $baseQuery->where('service_advisor_id', $user->id);
            } elseif ($user->branch_code) {
                $baseQuery->where('branch_code', $user->branch_code);
            }
        }

        return [
            'total' => (clone $baseQuery)->count(),
            'received' => (clone $baseQuery)->where('status', JobCard::STATUS_RECEIVED)->count(),
            'in_progress' => (clone $baseQuery)->whereIn('status', [
                JobCard::STATUS_IN_DIAGNOSIS,
                JobCard::STATUS_IN_PROGRESS,
                JobCard::STATUS_PARTS_PROCUREMENT,
            ])->count(),
            'completed_today' => (clone $baseQuery)->where('status', JobCard::STATUS_COMPLETED)
                ->whereDate('updated_at', today())->count(),
            'pending_approval' => (clone $baseQuery)->where('status', JobCard::STATUS_ESTIMATE_SENT)->count(),
        ];
    }

    public function render()
    {
        $jobCards = $this->jobCards->paginate(15);

        $statusOptions = JobCard::getStatusOptions();

        $branchOptions = Branch::active()
            ->orderBy('name')
            ->pluck('name', 'code')
            ->toArray();

        return view('livewire.job-cards.index', [
            'jobCards' => $jobCards,
            'statistics' => $this->statistics,
            'statusOptions' => $statusOptions,
            'branchOptions' => $branchOptions,
        ]);
    }
}
