<?php

namespace App\Livewire\Branches;

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

class Edit extends Component
{
    use AuthorizesRequests;

    public Branch $branch;
    public $code = '';
    public $name = '';
    public $address = '';
    public $phone = '';
    public $email = '';
    public $manager_name = '';
    public $city = '';
    public $state = '';
    public $postal_code = '';
    public $is_active = true;

    protected function rules()
    {
        return [
            'code' => 'required|string|max:10|unique:branches,code,' . $this->branch->id,
            'name' => 'required|string|max:255',
            'address' => 'nullable|string|max:500',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'manager_name' => 'nullable|string|max:255',
            'city' => 'nullable|string|max:100',
            'state' => 'nullable|string|max:50',
            'postal_code' => 'nullable|string|max:10',
            'is_active' => 'boolean',
        ];
    }

    protected $messages = [
        'code.required' => 'Branch code is required.',
        'code.unique' => 'This branch code is already taken.',
        'name.required' => 'Branch name is required.',
        'email.email' => 'Please enter a valid email address.',
    ];

    public function mount(Branch $branch)
    {
        $this->authorize('update', $branch);
        
        $this->branch = $branch;
        $this->code = $branch->code;
        $this->name = $branch->name;
        $this->address = $branch->address;
        $this->phone = $branch->phone;
        $this->email = $branch->email;
        $this->manager_name = $branch->manager_name;
        $this->city = $branch->city;
        $this->state = $branch->state;
        $this->postal_code = $branch->postal_code;
        $this->is_active = $branch->is_active;
    }

    public function save()
    {
        $this->authorize('update', $this->branch);
        
        $this->validate();

        try {
            $this->branch->update([
                'code' => strtoupper($this->code),
                'name' => $this->name,
                'address' => $this->address,
                'phone' => $this->phone,
                'email' => $this->email,
                'manager_name' => $this->manager_name,
                'city' => $this->city,
                'state' => $this->state,
                'postal_code' => $this->postal_code,
                'is_active' => $this->is_active,
            ]);

            session()->flash('success', 'Branch updated successfully.');
            
            return redirect()->route('branches.index');

        } catch (\Exception $e) {
            session()->flash('error', 'Failed to update branch: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.branches.edit');
    }
}
