<?php
/**
 * Destinations CRUD Endpoints
 */

$db = Database::getInstance()->getConnection();

// GET all destinations or single destination
if ($method === 'GET') {
    if ($id) {
        // Get single destination
        $stmt = $db->prepare("SELECT * FROM destinations WHERE id = ?");
        $stmt->execute([$id]);
        $destination = $stmt->fetch();
        
        if (!$destination) {
            jsonResponse(['error' => 'Destination not found'], 404);
        }
        
        jsonResponse($destination);
    } else {
        // Get all destinations with optional filtering
        $category = isset($_GET['category']) ? sanitizeString($_GET['category']) : null;
        $search = isset($_GET['search']) ? sanitizeString($_GET['search']) : null;
        
        $sql = "SELECT * FROM destinations WHERE 1=1";
        $params = [];
        
        if ($category && $category !== 'All') {
            $sql .= " AND category = ?";
            $params[] = $category;
        }
        
        if ($search) {
            $sql .= " AND (name LIKE ? OR location LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        
        $sql .= " LIMIT 100";
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $destinations = $stmt->fetchAll();
        
        jsonResponse($destinations);
    }
}

// POST create new destination (admin only)
if ($method === 'POST') {
    requireAuth();
    
    $input = getJsonInput();
    
    $errors = validateRequired($input, ['name', 'location', 'description', 'image', 'category', 'rating', 'price']);
    if (!empty($errors)) {
        jsonResponse(['error' => implode(', ', $errors)], 400);
    }
    
    $id = generateUuid();
    $stmt = $db->prepare("
        INSERT INTO destinations (id, name, location, description, image, category, rating, price, currency, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $stmt->execute([
        $id,
        sanitizeString($input['name']),
        sanitizeString($input['location']),
        $input['description'],
        $input['image'],
        $input['category'],
        $input['rating'],
        $input['price'],
        isset($input['currency']) ? $input['currency'] : 'USD'
    ]);
    
    // Fetch created destination
    $stmt = $db->prepare("SELECT * FROM destinations WHERE id = ?");
    $stmt->execute([$id]);
    $destination = $stmt->fetch();
    
    jsonResponse($destination, 201);
}

// PUT update destination (admin only)
if ($method === 'PUT' && $id) {
    requireAuth();
    
    $input = getJsonInput();
    
    // Build update query dynamically
    $updates = [];
    $params = [];
    
    $allowedFields = ['name', 'location', 'description', 'image', 'category', 'rating', 'price', 'currency'];
    
    foreach ($allowedFields as $field) {
        if (isset($input[$field])) {
            $updates[] = "$field = ?";
            $params[] = $field === 'description' ? $input[$field] : sanitizeString($input[$field]);
        }
    }
    
    if (empty($updates)) {
        jsonResponse(['error' => 'No fields to update'], 400);
    }
    
    $params[] = $id;
    
    $sql = "UPDATE destinations SET " . implode(', ', $updates) . " WHERE id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    
    // Fetch updated destination
    $stmt = $db->prepare("SELECT * FROM destinations WHERE id = ?");
    $stmt->execute([$id]);
    $destination = $stmt->fetch();
    
    jsonResponse($destination);
}

// DELETE destination (admin only)
if ($method === 'DELETE' && $id) {
    requireAuth();
    
    // Delete destination (cascades to specials)
    $stmt = $db->prepare("DELETE FROM destinations WHERE id = ?");
    $stmt->execute([$id]);
    
    if ($stmt->rowCount() === 0) {
        jsonResponse(['error' => 'Destination not found'], 404);
    }
    
    jsonResponse(['message' => 'Destination deleted successfully']);
}

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