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

// 1. Check Request Method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(405, 'error', 'Method not allowed');
}

// 2. Validate Required Fields from $_POST (Since we are using FormData now)
if (
    empty($_POST['title']) || 
    empty($_POST['destination']) || 
    empty($_POST['duration']) || 
    empty($_POST['startingPrice']) || 
    empty($_POST['overview'])
) {
    sendResponse(400, 'error', 'Missing required fields: title, destination, duration, price, or overview.');
}

// 3. Handle Image Upload
$imagePath = null;
if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {$uploadDir = '../uploads/packages/';
    // Create directory if it doesn't exist
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    // Generate unique filename
    $fileExtension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $fileName = time() . '_' . uniqid() . '.' . $fileExtension;
    $targetPath = $uploadDir .$fileName;
    
    if (move_uploaded_file($_FILES['image']['tmp_name'],$targetPath)) {
        $imagePath = '/api/uploads/packages/' .$fileName;
    } else {
        sendResponse(500, 'error', 'Failed to save uploaded image.');
    }
} else if (!empty($_POST['existing_image'])) {
    $imagePath =$_POST['existing_image'];
}

// 4. Connect to Database
$database = new Database();
$db =$database->getConnection();

try {
    // 5. Prepare the SQL Query
    $query = "INSERT INTO holiday_packages 
        (title, destination, duration_text, days, nights, starting_price, category, image_url, is_featured, overview, highlights, places_covered, itinerary, pricing) 
        VALUES 
        (:title, :destination, :duration_text, :days, :nights, :starting_price, :category, :image, :featured, :overview, :highlights, :places, :itinerary, :pricing)";

    $stmt = $db->prepare($query);

    // 6. Bind the values and execute
    $stmt->execute([
        ':title'          => trim($_POST['title']),
        ':destination'    => trim($_POST['destination']),
        ':duration_text'  => trim($_POST['duration']),
        ':days'           => isset($_POST['days']) ? (int)$_POST['days'] : 0,         ':nights'         => isset($_POST['nights']) ? (int)$_POST['nights'] : 0,         ':starting_price' => (float)$_POST['startingPrice'],
        ':category'       => isset($_POST['category']) ?$_POST['category'] : 'domestic',
        ':image'          => $imagePath,
        ':featured'       => (isset($_POST['featured']) && $_POST['featured'] === 'true') ? 1 : 0,         ':overview'       => trim($_POST['overview']),
        
        // These come as stringified JSON from FormData, so we pass them directly
        ':highlights'     => $_POST['highlights'] ?? '[]',
        ':places'         => $_POST['placesCovered'] ?? '[]',
        ':itinerary'      => $_POST['itinerary'] ?? '[]',
        ':pricing'        => $_POST['pricing'] ?? '[]'
    ]);

    $newPackageId =$db->lastInsertId();
    sendResponse(201, 'success', 'Package created successfully', ['id' => $newPackageId]);

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