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

// Initialize variables to hold booking and family member details
$row = null;
$familyMembers = [];
$isPaymentComplete = false;
$totalPaid = 0;
$remainingBalance = 0;
$isPaymentComplete = false;

// Check if booking_id is set in the URL
if (isset($_GET['booking_id'])) {
    // Retrieve the booking_id from the URL
    $booking_id = intval($_GET['booking_id']);

    // Prepare the SQL query to fetch booking details based on the booking_id
    $query = "
        SELECT
            b.booking_id,
            b.booking_code,
            c.first_name,
            c.last_name,
            c.city,
            c.phone_number,
            c.email,
            c.country,
            f.flight_number,
            b.booking_date,
            b.status,
            b.total_passengers,
            b.total_amount,
            b.payment_status,
            b.remaining_balance,
            (SELECT COUNT(*) FROM family_members fm WHERE fm.booking_id = b.booking_id) as family_member_count
        FROM
            bookings b
        JOIN
            customers c ON b.customer_id = c.customer_id
        JOIN
            flights f ON b.flight_id = f.flight_id
        WHERE
            b.booking_id = ?";

    // Prepare the statement
    if ($stmt = $conn->prepare($query)) {
        // Bind the parameter to the query
        $stmt->bind_param("i", $booking_id);

        // Execute the query
        $stmt->execute();

        // Get the result
        $result = $stmt->get_result();

        // Check if a booking was found
        if ($result->num_rows > 0) {
            // Fetch the booking data
            $row = $result->fetch_assoc();
        } else {
            echo "<p>No booking found with ID: $booking_id</p>";
        }

        // Close the statement
        $stmt->close();
    } else {
        echo "<p>Failed to prepare the SQL query.</p>";
    }

    // Prepare the SQL query to fetch family member details
    $familyQuery = "SELECT name, relation, gender, age, passport_number FROM family_members WHERE booking_id = ?";
    if ($familyStmt = $conn->prepare($familyQuery)) {
        // Bind the parameter to the query
        $familyStmt->bind_param("i", $booking_id);
        // Execute the query
        $familyStmt->execute();
        // Get the result
        $familyResult = $familyStmt->get_result();

        // Check if family members were found
        while ($familyRow = $familyResult->fetch_assoc()) {
            $familyMembers[] = $familyRow; // Store each family member's details
        }

        // Close the statement
        $familyStmt->close();
    } else {
        echo "<p>Failed to prepare family member query.</p>";
    }

    // Calculate the total amount paid
$paymentQuery = "SELECT SUM(amount) AS total_paid FROM payments WHERE booking_id = ?";
if ($paymentStmt = $conn->prepare($paymentQuery)) {
    $paymentStmt->bind_param("i", $booking_id);
    $paymentStmt->execute();
    $paymentResult = $paymentStmt->get_result();

    if ($paymentResult->num_rows > 0) {
        $paymentData = $paymentResult->fetch_assoc();
        $totalPaid = $paymentData['total_paid'] ?? 0;
    }

    $paymentStmt->close();
} else {
    echo "<p>Failed to prepare payment query.</p>";
}

// Determine if payment is complete
if (isset($row['total_amount']) && isset($row['remaining_balance'])) {
    $totalAmount = floatval($row['total_amount']);
    $remainingBalance = floatval($row['remaining_balance']);
    
    // Check if remaining balance is 0 or less
    $isPaymentComplete = ($remainingBalance <= 0);
    
    // If total_amount is 0 but remaining_balance is positive, consider payment incomplete
    if ($totalAmount == 0 && $remainingBalance > 0) {
        $isPaymentComplete = false;
    }
} else {
    // If either total_amount or remaining_balance is not set, consider payment incomplete
    $isPaymentComplete = false;
}

} else {
    echo "<p>No booking ID specified in the URL.</p>";
}

// Close the database connection
//$conn->close();
?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Booking View ')); ?>

    <!--datatable css-->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" />
    <!--datatable responsive css-->
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.bootstrap.min.css" />

    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">

    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Bookings Management', 'title' => 'Booking View')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center flex-wrap gap-2">
                                        <div class="flex-grow-1">
                                            Booking ID: <?php echo $booking_id;?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!--end col-->
                        <div class="col-xxl-9">
                            <div class="card" id="contactList">
                                <div class="card-header">
                                    <div class="row g-3">
                                        <div class="col-md-4">
                                            <div class="flight-info-box">
                                                <h5>Flight Details</h5>
                                                <?php
                                                // Initialize variables for flight details
                                                $flightDepartureTime = '';
                                                $flightDestination = '';

                                                // Check if booking_id is set and fetch flight details
                                                if (isset($row)) {
                                                    $flight_id = $row['flight_number']; // Retrieve flight_number from booking details

                                                    // Prepare the SQL query to fetch flight details based on flight_number
                                                    $flightQuery = "
                                                        SELECT
                                                            fs.departure_time,
                                                            a.airport_name AS destination_name
                                                        FROM
                                                            flight_schedules fs
                                                        JOIN
                                                            airports a ON fs.destination_id = a.airport_id
                                                        WHERE
                                                            fs.flight_number = ?";

                                                    if ($flightStmt = $conn->prepare($flightQuery)) {
                                                        // Bind the parameter to the query
                                                        $flightStmt->bind_param("s", $flight_id); // flight_number is a varchar
                                                        // Execute the query
                                                        $flightStmt->execute();
                                                        // Get the result
                                                        $flightResult = $flightStmt->get_result();

                                                        // Check if a flight was found
                                                        if ($flightResult->num_rows > 0) {
                                                            $flightData = $flightResult->fetch_assoc();
                                                            $flightDepartureTime = $flightData['departure_time'];
                                                            $flightDestination = $flightData['destination_name'];
                                                        }
                                                        $flightStmt->close();
                                                    } else {
                                                        echo "<p>Failed to prepare flight details query.</p>";
                                                    }
                                                }
                                                ?>

                                                <p><h5>Departure Time:<span class="badge bg-dark-subtle text-body"><?php echo isset($flightDepartureTime) ? htmlspecialchars($flightDepartureTime) : 'N/A'; ?></span></h5></p>
                                                <p><h5>Destination:<span class="badge bg-success"><?php echo isset($flightDestination) ? htmlspecialchars($flightDestination) : 'N/A'; ?></span></h5></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div>
                                        <div class="table-responsive table-card mb-3">
                                            <table class="table align-middle table-nowrap mb-0" id="customerTable">
                                                <thead>
                                                    <tr>
                                                        <th>#</th>
                                                        <th>Booking ID</th>
                                                        <th>Booking Code</th>
                                                        <th>Customer</th>
                                                        <th>Flight Number</th>
                                                        <th>Booking Date</th>
                                                        <th>Status</th>
                                                        <th>Passengers</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    if ($row) { // Check if $row is set
                                                        echo "<tr>";
                                                        echo "<td></td>"; // You can leave this empty or populate with an index
                                                        echo "<td>{$row['booking_id']}</td>";
                                                        echo "<td>{$row['booking_code']}</td>";
                                                        echo "<td>{$row['first_name']} {$row['last_name']}</td>";
                                                        echo "<td>{$row['flight_number']}</td>";
                                                        echo "<td>{$row['booking_date']}</td>";
                                                        echo "<td>{$row['status']}</td>";
                                                        echo "<td>{$row['total_passengers']} (+" . $row['family_member_count'] . " family)</td>";
                                                        echo "</tr>";

                                                        // Nested table for family members
                                                        if (!empty($familyMembers)) {
                                                            echo "<tr>";
                                                            echo "<td colspan='8'>";
                                                            echo "<table class='table table-bordered mt-2'>";
                                                            echo "<thead><tr><th>Family Member Name</th><th>Relation</th><th>Gender</th><th>Age</th><th>Passport</th></tr></thead>";
                                                            echo "<tbody>";
                                                            foreach ($familyMembers as $member) {
                                                                echo "<tr>";
                                                                echo "<td>" . htmlspecialchars($member['name']) . "</td>";
                                                                echo "<td>" . htmlspecialchars($member['relation']) . "</td>";
                                                                echo "<td>" . htmlspecialchars($member['gender']) . "</td>";
                                                                echo "<td>" . htmlspecialchars($member['age']) . "</td>";
                                                                echo "<td>" . htmlspecialchars($member['passport_number']) . "</td>";
                                                                echo "</tr>";
                                                            }
                                                            echo "</tbody></table>";
                                                            echo "</td>";
                                                            echo "</tr>";
                                                        }
                                                    } else {
                                                        // If no bookings are found, output a message
                                                        echo "<tr><td colspan='8'>No booking found</td></tr>";
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        <div class="d-flex justify-content-end mt-3">
                                            <button id="printTicketsBtn" class="btn btn-primary">Print Tickets</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!--end card-->
                        </div>
                        <!--end col-->
                        <div class="col-xxl-3">
                            <div class="card" id="contact-view-detail">
                                <div class="card-body text-center">
                                    <div class="position-relative d-inline-block">
                                        <img src="assets/images/users/avatar-10.jpg" alt="" class="avatar-lg rounded-circle img-thumbnail">
                                        <span class="contact-active position-absolute rounded-circle bg-success"><span class="visually-hidden"></span>
                                    </div>
                                    <h5 class="mt-4 mb-1">
                                        <?php
                                        // Check if $row is set to avoid errors
                                        if (isset($row)) {
                                            // Display first and last name
                                            echo htmlspecialchars($row['first_name']) . ' ' . htmlspecialchars($row['last_name']);
                                        } else {
                                            echo "Customer not found.";
                                        }
                                        ?>
                                    </h5>
                                    <p class="text-muted">Booking Code:
                                        <?php
                                        // Display the booking code, if it exists
                                        if (isset($row)) {
                                            echo htmlspecialchars($row['booking_code']);
                                        } else {
                                            echo "N/A";
                                        }
                                        ?>
                                    </p>

                                    <ul class="list-inline mb-0">
                                        <li class="list-inline-item avatar-xs">
                                            <a href="javascript:void(0);" class="avatar-title bg-success-subtle text-success fs-15 rounded">
                                                <i class="ri-phone-line"></i>
                                            </a>
                                        </li>
                                        <li class="list-inline-item avatar-xs">
                                            <a href="javascript:void(0);" class="avatar-title bg-danger-subtle text-danger fs-15 rounded">
                                                <i class="ri-mail-line"></i>
                                            </a>
                                        </li>
                                        <li class="list-inline-item avatar-xs">
                                            <a href="javascript:void(0);" class="avatar-title bg-warning-subtle text-warning fs-15 rounded">
                                                <i class="ri-question-answer-line"></i>
                                            </a>
                                        </li>
                                    </ul>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive table-card">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                
												<tr>
                                                    <td class="fw-semibold" scope="row">City</td>
                                                    <td>
                                                        <?php
                                                        // Check if $row is set to avoid errors
                                                        if (isset($row)) {
                                                            echo htmlspecialchars($row['city']); // Display customer's city
                                                        } else {
                                                            echo "N/A"; // Fallback message
                                                        }
                                                        ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-semibold" scope="row">Email Address</td>
                                                    <td>
                                                        <?php
                                                        // Display customer's email address
                                                        if (isset($row)) {
                                                            echo htmlspecialchars($row['email']); // Display customer's email
                                                        } else {
                                                            echo "N/A"; // Fallback message
                                                        }
                                                        ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-semibold" scope="row">Phone No</td>
                                                    <td>
                                                        <?php
                                                        // Display customer's phone number
                                                        if (isset($row)) {
                                                            echo htmlspecialchars($row['phone_number']); // Display customer's phone number
                                                        } else {
                                                            echo "N/A"; // Fallback message
                                                        }
                                                        ?>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-semibold" scope="row">Country</td>
                                                    <td>
                                                        <?php
                                                        // Display customer's country
                                                        if (isset($row)) {
                                                            echo htmlspecialchars($row['country']); // Display customer's country
                                                        } else {
                                                            echo "N/A"; // Fallback message
                                                        }
                                                        ?>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <!--end card-->
                        </div>
                        <!--end col-->
                    </div>
                    <!--end row-->
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <script src="assets/libs/list.js/list.min.js"></script>
    <script src="assets/libs/list.pagination.js/list.pagination.min.js"></script>

    <script src="assets/js/pages/crm-contact.init.js"></script>
    <!-- App js -->
    <script src="assets/js/app.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const printTicketsBtn = document.getElementById('printTicketsBtn');
        const isPaymentComplete = <?php echo $isPaymentComplete ? 'true' : 'false'; ?>;
        const bookingId = <?php echo $booking_id; ?>;  // Assuming you have $booking_id available
        
        console.log("Is Payment Complete:", isPaymentComplete);
        console.log("Total Amount:", <?php echo floatval($row['total_amount']); ?>);
        console.log("Remaining Balance:", <?php echo floatval($row['remaining_balance']); ?>);
        console.log("Total Paid:", <?php echo $totalPaid; ?>);
        
        // Enable or disable the button based on payment status
        printTicketsBtn.disabled = !isPaymentComplete;

        // Add booking_id as a URL parameter when the button is clicked
        if (isPaymentComplete) {
            printTicketsBtn.addEventListener('click', function() {
                window.location.href = 'print_tickets.php?booking_id=' + bookingId;
            });
        }
    });
</script>

</body>
</html>