<?php

namespace App\Livewire\Settings;

use App\Models\Location;
use App\Models\Branch;
use Livewire\Component;
use Livewire\WithPagination;

class LocationsManagement extends Component
{
    use WithPagination;

    protected $paginationTheme = 'bootstrap';

    public string $search = '';
    public ?int $filterBranchId = null;

    // Form
    public bool $showModal = false;
    public ?int $editingId = null;
    public ?int $branchId = null;
    public string $name = '';
    public string $nameAr = '';
    public string $code = '';
    public string $address = '';
    public bool $isDefault = false;
    public bool $isActive = true;

    protected function rules(): array
    {
        return [
            'branchId' => 'required|exists:branches,id',
            'name' => 'required|string|max:255',
            'nameAr' => 'nullable|string|max:255',
            'code' => 'required|string|max:50|unique:locations,code,' . ($this->editingId ?? 'NULL'),
            'address' => 'nullable|string|max:500',
            'isDefault' => 'boolean',
            'isActive' => 'boolean',
        ];
    }

    public function openModal(?int $id = null)
    {
        $this->resetValidation();

        if ($id) {
            $location = Location::findOrFail($id);
            $this->editingId = $location->id;
            $this->branchId = $location->branch_id;
            $this->name = $location->name;
            $this->nameAr = $location->name_ar ?? '';
            $this->code = $location->code;
            $this->address = $location->address ?? '';
            $this->isDefault = $location->is_default;
            $this->isActive = $location->is_active;
        } else {
            $this->reset(['editingId', 'name', 'nameAr', 'code', 'address', 'isDefault', 'isActive']);
            $this->branchId = auth()->user()->branch_id ?? Branch::first()?->id;
            $this->isActive = true;
            // Auto-generate code
            if ($this->branchId) {
                $this->code = Location::generateCode($this->branchId);
            }
        }

        $this->showModal = true;
    }

    public function updatedBranchId()
    {
        if (!$this->editingId && $this->branchId) {
            $this->code = Location::generateCode($this->branchId);
        }
    }

    public function save()
    {
        $this->validate();

        $data = [
            'branch_id' => $this->branchId,
            'name' => $this->name,
            'name_ar' => $this->nameAr ?: null,
            'code' => $this->code,
            'address' => $this->address ?: null,
            'is_default' => $this->isDefault,
            'is_active' => $this->isActive,
        ];

        // If setting as default, unset others in same branch
        if ($this->isDefault) {
            Location::where('branch_id', $this->branchId)
                ->where('id', '!=', $this->editingId)
                ->update(['is_default' => false]);
        }

        if ($this->editingId) {
            Location::findOrFail($this->editingId)->update($data);
            session()->flash('success', __('Location updated successfully.'));
        } else {
            Location::create($data);
            session()->flash('success', __('Location created successfully.'));
        }

        $this->showModal = false;
    }

    public function toggleActive(int $id)
    {
        $location = Location::findOrFail($id);
        $location->update(['is_active' => !$location->is_active]);
    }

    public function delete(int $id)
    {
        $location = Location::findOrFail($id);

        // Check if location has inventory
        if ($location->inventory()->count() > 0) {
            session()->flash('error', __('Cannot delete location with existing inventory. Please transfer stock first.'));
            return;
        }

        $location->delete();
        session()->flash('success', __('Location deleted successfully.'));
    }

    public function render()
    {
        $locations = Location::query()
            ->with('branch')
            ->when($this->search, function ($q) {
                $q->where(function ($q2) {
                    $q2->where('name', 'like', '%' . $this->search . '%')
                       ->orWhere('name_ar', 'like', '%' . $this->search . '%')
                       ->orWhere('code', 'like', '%' . $this->search . '%');
                });
            })
            ->when($this->filterBranchId, fn($q) => $q->where('branch_id', $this->filterBranchId))
            ->orderBy('branch_id')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate(20);

        $branches = Branch::active()->get();

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