<?php
require_once '../config/headers.php';
require_once '../config/database.php';
require_once '../utils/response.php';

// Only allow GET requests for fetching data
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendResponse(405, 'error', 'Method not allowed');
}

$database = new Database();
$db = $database->getConnection();

try {
    // Fetch all packages, newest first
    $query = "SELECT * FROM holiday_packages ORDER BY created_at DESC";
    $stmt = $db->prepare($query);
    $stmt->execute();
    
    $packages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the database rows to exactly match the React frontend's TypeScript interface
    $formatted_packages = array_map(function($pkg) {
        return [
            'id' => $pkg['id'],
            'title' => $pkg['title'],
            'destination' => $pkg['destination'],
            'duration' => $pkg['duration_text'],             // Maps duration_text -> duration
            'days' => (int)$pkg['days'],
            'nights' => (int)$pkg['nights'],
            'startingPrice' => (float)$pkg['starting_price'],// Maps starting_price -> startingPrice
            'category' => $pkg['category'],
            'image' => $pkg['image_url'],                    // Maps image_url -> image
            'featured' => (bool)$pkg['is_featured'],         // Converts 1/0 to true/false
            'overview' => $pkg['overview'],
            'status' => $pkg['status'],
            
            // Decode the JSON strings back into actual PHP arrays so they parse correctly in React
            'highlights' => json_decode($pkg['highlights']) ?: [],
            'placesCovered' => json_decode($pkg['places_covered']) ?: [],
            'itinerary' => json_decode($pkg['itinerary']) ?: [],
            'pricing' => json_decode($pkg['pricing']) ?: []
        ];
    }, $packages);

    sendResponse(200, 'success', 'Packages fetched successfully', $formatted_packages);

} catch (PDOException $e) {
    sendResponse(500, 'error', 'Database error: ' . $e->getMessage());
}
?>