<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use App\Models\Coach;

class Coaches extends Component
{
    use WithPagination, WithFileUploads;

    protected $paginationTheme = 'tailwind';

    public $search = '';
    public $showModal = false;
    public $editMode = false;

    public $coachId;
    public $name;
    public $bio;
    public $photo;
    public $is_active = true;

    protected function rules()
    {
        return [
            'name' => 'required|string|min:3',
            'bio' => 'nullable|string',
            'photo' => $this->editMode
                ? 'nullable|image|max:2048'
                : 'required|image|max:2048',
        ];
    }

    public function render()
    {
        return view('livewire.admin.coaches', [
            'coaches' => Coach::where('name', 'like', "%{$this->search}%")
                ->paginate(10),
        ]);
    }

    public function create()
    {
        $this->resetFields();
        $this->editMode = false;
        $this->showModal = true;
    }

    public function edit(Coach $coach)
    {
        $this->coachId = $coach->id;
        $this->name = $coach->name;
        $this->bio = $coach->bio;
        $this->is_active = $coach->is_active;
        $this->photo = null;

        $this->editMode = true;
        $this->showModal = true;
    }

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

        if ($this->photo) {
            $photoPath = $this->photo->store('coaches', 'public');
        }

        if ($this->editMode) {
            $coach = Coach::findOrFail($this->coachId);

            $data = [
                'name' => $this->name,
                'bio' => $this->bio,
                'is_active' => $this->is_active,
            ];

            if (isset($photoPath)) {
                $data['photo'] = $photoPath;
            }

            $coach->update($data);
        } else {
            Coach::create([
                'name' => $this->name,
                'bio' => $this->bio,
                'photo' => $photoPath ?? null,
                'is_active' => true,
            ]);
        }

        $this->showModal = false;
        $this->resetFields();
    }

    public function toggleStatus(Coach $coach)
    {
        $coach->update([
            'is_active' => ! $coach->is_active
        ]);
    }

    private function resetFields()
    {
        $this->reset([
            'coachId',
            'name',
            'bio',
            'photo',
            'is_active',
        ]);
    }
}
