<?php
// app/Livewire/StageController.php
namespace App\Livewire;

use App\Models\Stage;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class StageController extends Component
{
    public $stages;
    
    // Form properties
    public $name = '';
    public $description = '';
    public $active = true;
    
    // Edit mode properties
    public $editMode = false;
    public $stageId;
    public $selectedStage;

    protected function rules()
    {
        return [
            'name' => ['required', 'string', 'min:2', 'max:255', 'unique:stages,name' ],
            'description' => ['nullable', 'string'],
            'active' => ['boolean'],
        ];
    }

    protected function messages()
    {
        return [
            'name.required' => 'Stage name is required.',
            'name.min' => 'Stage name must be at least 2 characters.',
            'name.max' => 'Stage name cannot exceed 255 characters.',
            'name.unique' => 'A stage with this name already exists.',
        ];
    }

    public function mount()
    {
        $this->loadStages();
    }

    public function loadStages()
    {
        $this->stages = Stage::with(['createdBy', 'updatedBy'])
            // ->withCount('files')
            ->orderBy('name')
            ->get();
    }

    public function resetForm()
    {
        $this->reset(['name', 'description', 'active', 'editMode', 'stageId']);
        $this->active = true;
    }

    public function view($id)
    {
        $this->selectedStage = Stage::with(['createdBy', 'updatedBy'])
            ->withCount('files')
            ->findOrFail($id);
    }

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

        $stage = new Stage();
        $stage->name = $this->name;
        $stage->description = $this->description;
        $stage->active = $this->active;
        $stage->created_by = Auth::id();
        $stage->updated_by = Auth::id();
        $stage->save();

        $this->loadStages();
        $this->resetForm();

        $this->dispatch('closeModal');
        $this->dispatch('refreshTable');
        $this->dispatch('showSuccess', 'Stage created successfully!');
    }

    public function edit($id)
    {
        $stage = Stage::findOrFail($id);
        
        $this->stageId = $stage->id;
        $this->name = $stage->name;
        $this->description = $stage->description;
        $this->active = $stage->active;
        $this->editMode = true;
    }

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

        $stage = Stage::findOrFail($this->stageId);
        $stage->name = $this->name;
        $stage->description = $this->description;
        $stage->active = $this->active;
        $stage->updated_by = Auth::id();
        $stage->save();

        $this->loadStages();
        $this->resetForm();

        $this->dispatch('closeModal');
        $this->dispatch('refreshTable');
        $this->dispatch('showSuccess', 'Stage updated successfully!');
    }

    public function delete($id)
    {
        $stage = Stage::findOrFail($id);
        
        // Check if stage has any file associations (historical or current)
        // if ($stage->files()->count() > 0) {
        //     $this->dispatch('showError', 'Cannot delete stage because it has been used by files. You can deactivate it instead.');
        //     return;
        // }
        
        $stageName = $stage->name;
        $stage->delete();

        $this->loadStages();
        
        $this->dispatch('refreshTable');
        $this->dispatch('showSuccess', "Stage '{$stageName}' deleted successfully!");
    }

    public function toggleActive($id)
    {
        $stage = Stage::findOrFail($id);
        $stage->active = !$stage->active;
        $stage->updated_by = Auth::id();
        $stage->save();

        $this->loadStages();
        $this->dispatch('showSuccess', 'Stage status updated!');
    }

    public function render()
    {
        return view('livewire.stage-controller');
    }
}