<?php
include 'layouts/dbconn.php';

// Set JSON header for AJAX requests
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    header('Content-Type: application/json');
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $conn->begin_transaction();
    try {
        // Validate required fields
        $requiredFields = ['customer_id', 'user_id', 'flight_id', 'status'];
        foreach ($requiredFields as $field) {
            if (!isset($_POST[$field]) || empty($_POST[$field])) {
                throw new Exception("Missing required field: {$field}");
            }
        }

        // Get and sanitize main booking data
        $customerId = filter_var($_POST['customer_id'], FILTER_SANITIZE_NUMBER_INT);
        $userId = filter_var($_POST['user_id'], FILTER_SANITIZE_NUMBER_INT);
        $flightId = filter_var($_POST['flight_id'], FILTER_SANITIZE_NUMBER_INT);
        $promotionId = !empty($_POST['promotion_id']) ? filter_var($_POST['promotion_id'], FILTER_SANITIZE_NUMBER_INT) : null;
        $status = filter_var($_POST['status'], FILTER_SANITIZE_STRING);
        
        // Get agency fee data
        $agencyFeePercentage = filter_var($_POST['agency_fee_percentage'] ?? 0, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
        $agencyFeeAmount = filter_var($_POST['agency_fee_amount'] ?? 0, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

        // Check for existing booking
        $checkStmt = $conn->prepare("SELECT booking_id FROM bookings WHERE customer_id = ? AND flight_id = ?");
        $checkStmt->bind_param("ii", $customerId, $flightId);
        $checkStmt->execute();
        if ($checkStmt->get_result()->num_rows > 0) {
            throw new Exception("This customer already has a booking for this flight.");
        }
        $checkStmt->close();

        // Generate booking code
        $conn->query("UPDATE booking_code_sequence SET next_val = LAST_INSERT_ID(next_val + 1)");
        $sequenceRow = $conn->query("SELECT LAST_INSERT_ID() as next_val")->fetch_assoc();
        $bookingCode = sprintf("MIB%03d", $sequenceRow['next_val']);

        // Calculate total passengers
        $totalPassengers = 1; // Start with main customer
        $familyMembers = isset($_POST['family_members']) && is_array($_POST['family_members']) ? 
                        array_filter($_POST['family_members'], function($member) {
                            return !empty($member['name']) && !empty($member['relation']);
                        }) : [];
        $totalPassengers += count($familyMembers);

        // Get flight price and calculate total amount
        $flightStmt = $conn->prepare("SELECT price FROM flights WHERE flight_id = ?");
        $flightStmt->bind_param("i", $flightId);
        $flightStmt->execute();
        $flightResult = $flightStmt->get_result();
        
        if (!$flightResult->num_rows) {
            throw new Exception("Invalid flight selected.");
        }
        
        $flight = $flightResult->fetch_assoc();
        $basePrice = $flight['price'];
        $flightStmt->close();

        // Calculate total amount with taxes and fees
        $taxRate = 0.16; // 16% tax rate
        $pricePerPassenger = $basePrice * (1 + $taxRate);
        $totalAmount = $pricePerPassenger * $totalPassengers;

        // Apply promotion if exists
        if ($promotionId) {
            $promoStmt = $conn->prepare("SELECT discount_percentage FROM promotions WHERE promotion_id = ? AND active = 1");
            $promoStmt->bind_param("i", $promotionId);
            $promoStmt->execute();
            $promoResult = $promoStmt->get_result();
            if ($promoResult->num_rows > 0) {
                $promotion = $promoResult->fetch_assoc();
                $discountRate = $promotion['discount_percentage'] / 100;
                $totalAmount = $totalAmount * (1 - $discountRate);
            }
            $promoStmt->close();
        }

        // Add agency fees to total amount
        $totalWithFees = $totalAmount + $agencyFeeAmount;

        // Insert booking
        $stmt = $conn->prepare("INSERT INTO bookings (customer_id, user_id, flight_id, promotion_id, status, 
                               total_passengers, booking_code, total_amount, created_at) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
        $stmt->bind_param("iiissisi", $customerId, $userId, $flightId, $promotionId, $status, 
                         $totalPassengers, $bookingCode, $totalWithFees);
        
        if (!$stmt->execute()) {
            throw new Exception("Error creating booking: " . $stmt->error);
        }
        
        $bookingId = $conn->insert_id;
        $stmt->close();

        // Insert agency fees record
        if ($agencyFeeAmount > 0) {
            $feeStmt = $conn->prepare("INSERT INTO booking_fees (booking_id, agency_fee_percentage, agency_fee_amount) 
                                     VALUES (?, ?, ?)");
            $feeStmt->bind_param("idd", $bookingId, $agencyFeePercentage, $agencyFeeAmount);
            if (!$feeStmt->execute()) {
                throw new Exception("Error saving agency fees: " . $feeStmt->error);
            }
            $feeStmt->close();
        }

        // Insert family members if any
        if (!empty($familyMembers)) {
            $familyStmt = $conn->prepare("INSERT INTO family_members (booking_id, name, relation, gender, age, passport_number) 
                                        VALUES (?, ?, ?, ?, ?, ?)");
            
            foreach ($familyMembers as $member) {
                $familyStmt->bind_param("isssss", 
                    $bookingId,
                    $member['name'],
                    $member['relation'],
                    $member['gender'],
                    $member['age'],
                    $member['passport_number']
                );
                
                if (!$familyStmt->execute()) {
                    throw new Exception("Error adding family member: " . $familyStmt->error);
                }
            }
            $familyStmt->close();
        }

        // Update flight available seats
        $updateSeatsStmt = $conn->prepare("UPDATE flights SET available_seats = available_seats - ? WHERE flight_id = ?");
        $updateSeatsStmt->bind_param("ii", $totalPassengers, $flightId);
        if (!$updateSeatsStmt->execute()) {
            throw new Exception("Error updating available seats: " . $updateSeatsStmt->error);
        }
        $updateSeatsStmt->close();

        $conn->commit();
        
        // Success response
        $response = [
            'status' => 'success',
            'message' => 'Booking saved successfully! Booking Code: ' . $bookingCode,
            'booking_id' => $bookingId,
            'booking_code' => $bookingCode,
            'total_amount' => number_format($totalWithFees, 2),
            'base_amount' => number_format($totalAmount, 2),
            'agency_fee' => number_format($agencyFeeAmount, 2)
        ];
        
        if (isset($_SESSION)) {
            $_SESSION['success_message'] = $response['message'];
        }

        echo json_encode($response);
        
    } catch (Exception $e) {
        $conn->rollback();
        
        $errorResponse = [
            'status' => 'error',
            'message' => $e->getMessage()
        ];
        
        if (isset($_SESSION)) {
            $_SESSION['error_message'] = $errorResponse['message'];
        }

        echo json_encode($errorResponse);
    }
}

$conn->close();
?>