<?php
include('include/auth.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
?>

<!doctype html>
<html class="fixed dark">
<?php 
$pagerole = "user";
include('include/head.php'); 

// Fetch API Partners
$api_partners = [];
$partner_query = "SELECT api_partner_id, api_partner_name, api_partner_key FROM api_partner ORDER BY api_partner_name ASC";
$partner_result = $db2->query($partner_query);
while ($row = $partner_result->fetch_assoc()) {
    $api_partners[] = $row;
}

?>

<body>
<section class="body">
    <?php include('include/nav.php'); ?>

    <section role="main" class="content-body">
        <header class="page-header">
            <h2>Availability Search</h2>
        </header>

        <!-- Start: Page Content -->
        <div class="row">
            <div class="col-lg-12">
                <section class="panel">
                    <header class="panel-heading">
                        <h2 class="panel-title">Search Availability</h2>
                    </header>
                    <div class="panel-body">
                        <form id="availabilitySearchForm">
                            <div class="row">
                                
                                <!-- API Partner Dropdown -->
                                <div class="form-group col-4">
                                    <label for="api_partner">API Partner</label>
                                    <select id="api_partner" class="form-control populate">
                                        <option value="">Select API Partner</option>
                                        <?php foreach ($api_partners as $partner): ?>
                                            <option value="<?= $partner['api_partner_id']; ?>" data-key="<?= $partner['api_partner_key']; ?>">
                                                <?= htmlspecialchars($partner['api_partner_name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <!-- Pickup Date & Time -->
                                <div class="form-group col-4">
                                    <label for="pickup_datetime">Pickup Date & Time</label>
                                    <input type="text" id="pickup_datetime" data-plugin-datepicker data-plugin-options='{"format": "dd/mm/yyyy"}' class="form-control">
                                </div>

                                <!-- Drop-off Date & Time -->
                                <div class="form-group col-4">
                                    <label for="dropoff_datetime">Drop-off Date & Time</label>
                                    <input type="text" id="dropoff_datetime" data-plugin-datepicker data-plugin-options='{"format": "dd/mm/yyyy"}' class="form-control">
                                </div>

                                <!-- Pickup Location -->
                                <div class="form-group col-6">
                                    <label for="pickup_location">Pickup Location</label>
                                    <select id="pickup_location" class="form-control populate">
                                        <option value="">Select Pickup Location</option>
                                    </select>
                                </div>

                                <!-- Drop-off Location -->
                                <div class="form-group col-6">
                                    <label for="dropoff_location">Drop-off Location</label>
                                    <select id="dropoff_location" class="form-control populate">
                                        <option value="">Select Drop-off Location</option>
                                    </select>
                                </div>

                            </div>
                            <br>
                            <button type="button" class="btn btn-primary" id="searchAvailability">Search</button>
                        </form>
                    </div>
                </section>
            </div>
        </div>

        <!-- JSON Results -->
        <div class="row">
            <div class="col-lg-12">
                <section class="panel">
                    <header class="panel-heading">
                        <h2 class="panel-title">API Results</h2>
                    </header>
                    <div class="panel-body">
                        <pre style="color:#b3b3b3; max-height:500px;" id="apiResults" class="pre-scrollable">Waiting for search...</pre>
                    </div>
                </section>
            </div>
        </div>
        <!-- End: Page Content -->
    </section>
</section>
    <script src="vendor/jquery/jquery.js"></script>
    <script src="vendor/jquery-browser-mobile/jquery.browser.mobile.js"></script>
    <script src="vendor/popper/umd/popper.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.js"></script>
    <script src="vendor/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
    <script src="vendor/common/common.js"></script>
    <script src="vendor/nanoscroller/nanoscroller.js"></script>
    <script src="vendor/magnific-popup/jquery.magnific-popup.js"></script>
    <script src="vendor/jquery-placeholder/jquery.placeholder.js"></script>
    <!-- Specific Page Vendor -->
    <script src="vendor/select2/js/select2.js"></script>
    <script src="vendor/pnotify/pnotify.custom.js"></script>
    <!--(remove-empty-lines-end)-->
    <!-- Theme Base, Components and Settings -->
    <script src="js/theme.js"></script>
    <!-- Theme Custom -->
    <script src="js/custom.js"></script>
    <!-- Theme Initialization Files -->
    <script src="js/theme.init.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
    <!-- Examples -->
    <script src="js/examples/examples.header.menu.js"></script>
    <script src="js/examples/examples.ecommerce.orders.detail.js"></script>
    <script src="js/examples/examples.modals.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rome/3.0.2/rome.standalone.min.js" integrity="sha512-cJ4aSZY0xBXrcH65MOwCloQAiTNCBm2F8/KlcBTlczgn4txZkT7h3YSXULN06pkUnsySMEg5BU4QCHAr97U7ng==" crossorigin="anonymous"></script>


<!-- Search Functionality -->
<script>
   $(document).ready(function() {

    // Load Locations based on API Partner Selection
    $('#api_partner').change(function() {
        let partnerId = $(this).val();
        if (partnerId) {
            $.getJSON('load_locations.php', { partner_id: partnerId }, function(data) {
                $('#pickup_location, #dropoff_location').empty().append('<option value="">Select Location</option>');
                $.each(data, function(index, item) {
                    $('#pickup_location, #dropoff_location').append('<option value="' + item.place_id + '">' + item.place_name + '</option>');
                });
            });
        }
    });

    // Handle Search Click
    $('#searchAvailability').click(function() {
        let partnerId = $('#api_partner').val();
        let partnerKey = $('#api_partner option:selected').data('key');
        let pickupTime = $('#pickup_datetime').val();
        let dropoffTime = $('#dropoff_datetime').val();
        let pickupLocation = $('#pickup_location').val();
        let dropoffLocation = $('#dropoff_location').val();

        if (!partnerId || !partnerKey || !pickupTime || !dropoffTime || !pickupLocation || !dropoffLocation) {
            alert('Please fill in all required fields.');
            return;
        }

        // Fix: Convert "dd/mm/yyyy" format correctly
        let startTimestamp = moment(pickupTime, "DD/MM/YYYY").unix();
        let endTimestamp = moment(dropoffTime, "DD/MM/YYYY").unix();

        // Debugging: Check if values are correct before sending the request
        console.log("Partner ID:", partnerId);
        console.log("Partner Key:", partnerKey);
        console.log("Pickup Time (Raw):", pickupTime);
        console.log("Dropoff Time (Raw):", dropoffTime);
        console.log("Converted Start Timestamp:", startTimestamp);
        console.log("Converted End Timestamp:", endTimestamp);
        console.log("Pickup Location:", pickupLocation);
        console.log("Dropoff Location:", dropoffLocation);

        let apiUrl = `api-debug2.php`;

        let postData = {
            pid: partnerId,
            key: partnerKey,
            type: 1,
            task: 1,
            start: startTimestamp,
            end: endTimestamp,
            sloc: pickupLocation,
            eloc: dropoffLocation
        };

        console.log("Sending Request:", postData);

        $.ajax({
            url: apiUrl,
            type: "POST",
            data: JSON.stringify(postData),
            contentType: "application/json",
            dataType: "json",
            success: function(response) {
                console.log("API Response:", response);
                if (!response || $.isEmptyObject(response)) {
                    $('#apiResults').text("No data received from API.");
                } else {
                    $('#apiResults').text(JSON.stringify(response, null, 4));
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("AJAX Error:", textStatus, errorThrown);
                console.error("Response Text:", jqXHR.responseText);
                $('#apiResults').text("Error fetching data. Check console.");
            }
        });
    });
});

</script>

</body>
</html>
<?php include('include/footer.php'); ?>
