<?php
/**
 * Destination Categories Endpoints
 */
$db = Database::getInstance()->getConnection();

// GET all categories (public - needed for destination forms)
if ($method === 'GET' && !$id) {
    $stmt = $db->query('SELECT id, name FROM destination_categories ORDER BY name');
    jsonResponse($stmt->fetchAll());
}

// POST add category (admin)
if ($method === 'POST') {
    requireAuth();
    $input = getJsonInput();
    $errors = validateRequired($input, ['name']);
    if (!empty($errors)) jsonResponse(['error' => implode(', ', $errors)], 400);
    $name = sanitizeString($input['name']);
    try {
        $stmt = $db->prepare('INSERT INTO destination_categories (name) VALUES (?)');
        $stmt->execute([$name]);
        $newId = $db->lastInsertId();
        jsonResponse(['id' => $newId, 'name' => $name], 201);
    } catch (Exception $e) {
        jsonResponse(['error' => 'Category already exists'], 409);
    }
}

// PUT rename category (admin) - also updates all destinations using it
if ($method === 'PUT' && $id) {
    requireAuth();
    $input = getJsonInput();
    $errors = validateRequired($input, ['name']);
    if (!empty($errors)) jsonResponse(['error' => implode(', ', $errors)], 400);
    $newName = sanitizeString($input['name']);
    $stmt = $db->prepare('SELECT name FROM destination_categories WHERE id = ?');
    $stmt->execute([$id]);
    $old = $stmt->fetch();
    if (!$old) jsonResponse(['error' => 'Category not found'], 404);
    try {
        $db->prepare('UPDATE destination_categories SET name = ? WHERE id = ?')->execute([$newName, $id]);
        $db->prepare('UPDATE destinations SET category = ? WHERE category = ?')->execute([$newName, $old['name']]);
        jsonResponse(['id' => $id, 'name' => $newName]);
    } catch (Exception $e) {
        jsonResponse(['error' => 'Category name already exists'], 409);
    }
}

// DELETE category (admin) - only if no destinations use it
if ($method === 'DELETE' && $id) {
    requireAuth();
    $stmt = $db->prepare('SELECT name FROM destination_categories WHERE id = ?');
    $stmt->execute([$id]);
    $cat = $stmt->fetch();
    if (!$cat) jsonResponse(['error' => 'Category not found'], 404);
    $stmt = $db->prepare('SELECT COUNT(*) FROM destinations WHERE category = ?');
    $stmt->execute([$cat['name']]);
    if ($stmt->fetchColumn() > 0) jsonResponse(['error' => 'Cannot delete — destinations are using this category'], 400);
    $db->prepare('DELETE FROM destination_categories WHERE id = ?')->execute([$id]);
    jsonResponse(['message' => 'Category deleted']);
}

jsonResponse(['error' => 'Invalid categories endpoint'], 404);
