<?php

namespace App\Livewire\Branches;

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

class Index extends Component
{
    use WithPagination, AuthorizesRequests;

    public $search = '';
    public $sortField = 'name';
    public $sortDirection = 'asc';
    public $showInactive = false;

    protected $queryString = [
        'search' => ['except' => ''],
        'sortField' => ['except' => 'name'],
        'sortDirection' => ['except' => 'asc'],
        'showInactive' => ['except' => false],
    ];

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

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

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

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

    public function toggleStatus($branchId)
    {
        $branch = Branch::findOrFail($branchId);
        $this->authorize('update', $branch);
        
        $branch->update(['is_active' => !$branch->is_active]);
        
        session()->flash('success', 'Branch status updated successfully.');
    }

    public function deleteBranch($branchId)
    {
        $branch = Branch::findOrFail($branchId);
        $this->authorize('delete', $branch);
        
        // Check if branch has any users
        if ($branch->users()->exists()) {
            session()->flash('error', 'Cannot delete branch with assigned users. Please reassign users first.');
            return;
        }
        
        // Check if branch has any job cards
        if (\App\Models\JobCard::where('branch_code', $branch->code)->exists()) {
            session()->flash('error', 'Cannot delete branch with existing job cards.');
            return;
        }
        
        $branch->delete();
        session()->flash('success', 'Branch deleted successfully.');
    }

    public function render()
    {
        $branches = Branch::query()
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('name', 'like', '%' . $this->search . '%')
                      ->orWhere('code', 'like', '%' . $this->search . '%')
                      ->orWhere('city', 'like', '%' . $this->search . '%')
                      ->orWhere('manager_name', 'like', '%' . $this->search . '%');
                });
            })
            ->when(!$this->showInactive, function ($query) {
                $query->where('is_active', true);
            })
            ->orderBy($this->sortField, $this->sortDirection)
            ->paginate(10);

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