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

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

// Validation: ID is strictly required for updating
if (empty($_POST['id']) || empty($_POST['title']) || empty($_POST['destination']) || empty($_POST['startingPrice'])) {
    sendResponse(400, 'error', 'Missing required fields (ID, title, destination, or price).');
}

// Handle Image Upload
$imagePath = $_POST['existing_image'] ?? null;

if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = '../uploads/packages/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $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;
    }
}

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

try {
    $query = "UPDATE holiday_packages SET 
        title = :title, 
        destination = :destination, 
        duration_text = :duration_text, 
        days = :days, 
        nights = :nights, 
        starting_price = :starting_price, 
        category = :category, 
        image_url = :image, 
        is_featured = :featured, 
        overview = :overview, 
        highlights = :highlights, 
        places_covered = :places, 
        itinerary = :itinerary, 
        pricing = :pricing 
        WHERE id = :id";

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

    $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']),
        
        ':highlights'     => $_POST['highlights'] ?? '[]',
        ':places'         => $_POST['placesCovered'] ?? '[]',
        ':itinerary'      => $_POST['itinerary'] ?? '[]',
        ':pricing'        => $_POST['pricing'] ?? '[]',
        
        ':id'             => $_POST['id']
    ]);

    sendResponse(200, 'success', 'Package updated successfully');

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