<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Coach;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class CoachController extends Controller
{
    public function index(): View
    {
        return view('admin.coaches.index', [
            'items' => Coach::query()->orderBy('sort_order')->get(),
        ]);
    }

    public function create(): View
    {
        return view('admin.coaches.form', ['item' => new Coach]);
    }

    public function store(Request $request): RedirectResponse
    {
        Coach::query()->create($this->validated($request));

        return redirect()->route('admin.coaches.index')->with('success', 'Coach created.');
    }

    public function edit(Coach $coach): View
    {
        return view('admin.coaches.form', ['item' => $coach]);
    }

    public function update(Request $request, Coach $coach): RedirectResponse
    {
        $coach->update($this->validated($request, $coach));

        return redirect()->route('admin.coaches.index')->with('success', 'Coach updated.');
    }

    public function destroy(Coach $coach): RedirectResponse
    {
        $this->deleteUploadedPhoto($coach->photo_path);

        $coach->delete();

        return redirect()->route('admin.coaches.index')->with('success', 'Coach deleted.');
    }

    /** @return array<string, mixed> */
    private function validated(Request $request, ?Coach $existing = null): array
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:255',
            'role' => 'required|string|max:255',
            'bio' => 'nullable|string',
            'photo' => 'nullable|image|max:5120',
            'media_tag' => 'nullable|string|max:255',
            'tags' => 'nullable|string',
            'sort_order' => 'required|integer|min:0',
            'show_on_home' => 'sometimes|boolean',
            'show_on_about' => 'sometimes|boolean',
            'is_active' => 'sometimes|boolean',
        ]);

        $tags = collect(explode(',', $data['tags'] ?? ''))
            ->map(fn (string $tag) => trim($tag))
            ->filter()
            ->values()
            ->all();

        unset($data['tags'], $data['photo']);

        if ($request->hasFile('photo')) {
            $this->deleteUploadedPhoto($existing?->photo_path);
            $data['photo_path'] = $request->file('photo')->store('coaches', 'public');
        } elseif ($existing) {
            $data['photo_path'] = $existing->photo_path;
        } else {
            $data['photo_path'] = null;
        }

        return $data + [
            'tags' => $tags ?: null,
            'show_on_home' => $request->boolean('show_on_home'),
            'show_on_about' => $request->boolean('show_on_about'),
            'is_active' => $request->boolean('is_active'),
        ];
    }

    private function deleteUploadedPhoto(?string $photoPath): void
    {
        if ($photoPath && str_starts_with($photoPath, 'coaches/')) {
            Storage::disk('public')->delete($photoPath);
        }
    }
}
