<?php 
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include __DIR__ . '/../inc/db.php'; 

if (isset($_POST['quotation_id'])) {
    $quotation_id = mysqli_real_escape_string($conn, $_POST['quotation_id']); // prevent SQL injection
    
    // Fetch quotation details
    $quotationQuery = "SELECT * FROM quotations WHERE id = '$quotation_id' AND status = 'accepted' LIMIT 1";
    $quotationResult = $conn->query($quotationQuery);

    if ($quotationResult && $quotationResult->num_rows > 0) {
        $quotation = $quotationResult->fetch_assoc();

        // Fetch hotel data
        $hotels = [];
        $hotelsQuery = "SELECT * FROM quotation_hotels WHERE quotation_id = '$quotation_id'";
        $hotelsResult = $conn->query($hotelsQuery);

        if ($hotelsResult && $hotelsResult->num_rows > 0) {
            while ($hotel = $hotelsResult->fetch_assoc()) {
                $hotels[] = [
                    'hotel_name' => $hotel['hotel_name'],
                    'hotel_location' => $hotel['hotel_location'],
                    'hotel_rooms' => $hotel['hotel_rooms'],
                    'hotel_type' => $hotel['hotel_type'],
                    'meal_plan' => $hotel['meal_plan'],
                ];
            }
        } else {
            error_log("No hotels found for quotation_id: $quotation_id");
        }

        echo json_encode([
            'status' => 'success',
            'data' => [
                'quotation' => [
					'customer_id' => $quotation['customer_id'],
                    'package_name' => $quotation['package_name'],
                    'destination' => $quotation['destination'],
                    'travel_date' => $quotation['travel_date'],
                    'nights' => $quotation['nights'],
                    'rooms' => $quotation['rooms'],
                    'adults' => $quotation['adults'],
                    'child' => $quotation['child'],
                    'extrabed' => $quotation['extrabed'],
                    'adult_price' => $quotation['adult_price'],
                    'child_price' => $quotation['child_price'],
                    'extra_bed_price' => $quotation['extra_bed_price'],
                    'transport_type' => $quotation['transport_type'],
                    'transport_charges' => $quotation['transport_charges'],
                    'gst_included' => $quotation['gst_included'],
                    'discount' => $quotation['discount'],
                    'grand_total' => $quotation['grand_total'],
                ],
                'hotels' => $hotels
            ]
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Quotation not found.']);
    }
}
?>
