<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Csrf;
use App\Repositories\Container;
use App\Services\Availability;
use App\Services\Booking;

class ApiController
{
    public function availability(): void
    {
        header('Content-Type: application/json');
        $artistId = $_GET['artist'] ?? '';
        $month    = $_GET['month']  ?? date('Y-m');
        $date     = $_GET['date']   ?? null;

        if (!$artistId) {
            $artists = Container::artists()->all(true);
            $monthMap = [];
            foreach ($artists as $a) {
                foreach (Availability::monthAvailability($a['id'], $month) as $d => $count) {
                    $monthMap[$d] = ($monthMap[$d] ?? 0) + $count;
                }
            }
            $slots = [];
            if ($date) {
                foreach ($artists as $a) {
                    foreach (Availability::allSlotsForArtistOnDate($a['id'], $date) as $slot) {
                        $slot['artist_id'] = $a['id'];
                        $slot['artist_name'] = $a['display_name'] ?? '';
                        $slots[] = $slot;
                    }
                }
                usort($slots, fn($x, $y) => strcmp($x['start'], $y['start']));
            }
            echo json_encode(['month' => $monthMap, 'slots' => $slots]);
            return;
        }

        $monthMap = Availability::monthAvailability($artistId, $month);
        $slots = $date ? Availability::allSlotsForArtistOnDate($artistId, $date) : [];
        echo json_encode(['month' => $monthMap, 'slots' => $slots]);
    }

    public function saveDraft(): void
    {
        header('Content-Type: application/json');
        Csrf::requireValid();
        $state = $_SESSION['booking'] ?? [];
        $draft = Booking::saveDraft($state);
        echo json_encode($draft);
    }

    public function uploadReference(): void
    {
        header('Content-Type: application/json');
        Csrf::requireValid();
        if (empty($_FILES['file'])) { http_response_code(400); echo json_encode(['error' => 'no file']); return; }
        $f = $_FILES['file'];
        $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
        $mime = function_exists('mime_content_type') ? (@\mime_content_type($f['tmp_name']) ?: '') : '';
        if (!$mime || !isset($allowed[$mime])) {
            $ext = strtolower(\pathinfo($f['name'] ?? '', PATHINFO_EXTENSION));
            $extMap = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp'];
            $mime = $extMap[$ext] ?? $mime;
        }
        if (!isset($allowed[$mime])) { http_response_code(415); echo json_encode(['error' => 'unsupported type: ' . $mime]); return; }
        if ($f['size'] > 5 * 1024 * 1024) { http_response_code(413); echo json_encode(['error' => 'too large']); return; }
        $name = uuid() . '.' . $allowed[$mime];
        $dest = config('upload_path') . '/references/' . $name;
        if (!@move_uploaded_file($f['tmp_name'], $dest)) { http_response_code(500); echo json_encode(['error' => 'write failed']); return; }
        echo json_encode(['url' => config('upload_url') . '/references/' . $name]);
    }
}
