<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Csrf;
use App\Repositories\Container;

class AdminArtistsController
{
    public function index(): void
    {
        $artists = Container::artists()->all();
        render('admin', 'admin.artists', compact('artists'), t('admin.artists.title'));
    }

    public function create(): void
    {
        Csrf::requireValid();
        $name = trim((string)($_POST['display_name'] ?? ''));
        if (!$name) redirect('/admin/artists');
        Container::artists()->save([
            'display_name' => $name,
            'bio' => trim((string)($_POST['bio'] ?? '')),
            'specialties' => array_filter(array_map('trim', explode(',', $_POST['specialties'] ?? ''))),
            'instagram_handle' => ltrim(trim((string)($_POST['instagram_handle'] ?? '')), '@'),
            'avatar_url' => $_POST['avatar_url'] ?? null,
            'is_active' => true,
        ]);
        $_SESSION['_flash']['success'] = t('admin.artists.created');
        redirect('/admin/artists');
    }

    public function edit(array $params): void
    {
        $artist = Container::artists()->find($params['id'] ?? '');
        if (!$artist) { http_response_code(404); require MAT_ROOT . '/src/Views/errors/404.php'; return; }
        render('admin', 'admin.artist-edit', compact('artist'), $artist['display_name'] ?? '');
    }

    public function update(array $params): void
    {
        Csrf::requireValid();
        $artist = Container::artists()->find($params['id'] ?? '');
        if (!$artist) redirect('/admin/artists');
        $avatar = $artist['avatar_url'] ?? null;
        if (!empty($_FILES['avatar']['tmp_name'])) {
            $ext = pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION) ?: 'jpg';
            $name = uuid() . '.' . strtolower($ext);
            $dest = config('upload_path') . '/avatars/' . $name;
            if (@move_uploaded_file($_FILES['avatar']['tmp_name'], $dest)) {
                $avatar = config('upload_url') . '/avatars/' . $name;
            }
        }
        Container::artists()->save(array_merge($artist, [
            'display_name' => trim((string)($_POST['display_name'] ?? $artist['display_name'])),
            'bio' => trim((string)($_POST['bio'] ?? '')),
            'specialties' => array_filter(array_map('trim', explode(',', $_POST['specialties'] ?? ''))),
            'instagram_handle' => ltrim(trim((string)($_POST['instagram_handle'] ?? '')), '@'),
            'avatar_url' => $avatar,
            'is_active' => !empty($_POST['is_active']),
        ]));
        $_SESSION['_flash']['success'] = t('admin.artists.updated');
        redirect('/admin/artists/' . $artist['id']);
    }

    public function delete(array $params): void
    {
        Csrf::requireValid();
        Container::artists()->delete($params['id'] ?? '');
        redirect('/admin/artists');
    }
}
