<? session_start();
require_once("assets/php/_user_authenticate.php"); ?>
<!-- Login the User -->

<!-- This code generates the base URL for the website by combining the protocol, domain name, and directory path -->
<?php
    $rootFolder = basename($_SERVER['DOCUMENT_ROOT']);
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . str_replace('/pages', '', dirname($_SERVER['SCRIPT_NAME']));
?>
<!-- This code generates the base URL for the website by combining the protocol, domain name, and directory path -->

<!-- This code is useful for internal styles  -->
<?php ob_start(); ?>

        <!-- PRISM CSS -->
    <!--    <link rel="stylesheet" href="<?php //echo $baseUrl; ?>/assets/libs/prismjs/themes/prism-coy.min.css"> -->

<?php $styles = ob_get_clean(); ?>
<!-- This code is useful for internal styles  -->

<!-- This code is useful for content -->
<?php ob_start(); ?>

                <div class="container-fluid">

                    <!-- Page Header -->
                    <div class="d-md-flex d-block align-items-center justify-content-between my-4 page-header-breadcrumb">
                        <h1 class="page-title fw-semibold fs-18 mb-0">Accept Packages</h1>
                        <div class="ms-md-1 ms-0">
                            <nav>
                                <ol class="breadcrumb mb-0">
                                    <li class="breadcrumb-item"><a href="javascript:void(0);">Packages</a></li>
                                    <li class="breadcrumb-item active" aria-current="page">Receive</li>
                                </ol>
                            </nav>
                        </div>
                    </div>
                    <!-- Page Header Close -->

                    <!-- Start:: row-1 -->
                    <div class="row">
                        <div class="col-xl-9">
                            <div class="card custom-card">
                                <div class="card-header justify-content-between">
                                    <div class="card-title">
                                        Accept Packages
                                    </div>
                                    <div class="">
                                        <button class="btn btn-sm btn-primary-light">Clear Fields<i class="ri-code-line ms-2 d-inline-block align-middle"></i></button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label for="form-tracking" class="form-label fs-14 text-dark">Tracking</label>
                                        <input type="text" class="form-control" id="form-tracking" placeholder="tracking">
                                    </div>
                                    <div class="mb-3">
                                        <label for="form-sender" class="form-label fs-14 text-dark">Sender</label>
                                        <input type="form-text" class="form-control" id="form-sender" placeholder="sender">
                                    </div>
                                    <div class="mb-3">
                                        <p class="fw-semibold mb-2">Recipient</p>
                                        <input type="hidden" id="customerKey" name="customerKey" value="">
                                        <input id="receiverSearch" class="form-control input-lg" type="text" placeholder="Loading..." tabindex=3>
                                    </div>
                                    <div class="mb-3">
                                        <p class="fw-semibold mb-2">Package Size</p>
                                        <select class="form-control" data-trigger name="choices-single-groups" id="choices-single-groups">
                                            <option value="">Choose a Package Size</option>
                                            <option value="small">Small</option>
                                            <option value="medium">Medium</option>
                                            <option value="large">Large</option>
                                        </select>
                                    </div>
                                    <button class="btn btn-primary" type="submit">Submit</button>
                                </div>
                                <div class="card-footer d-none border-top-0">

                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3">
                            <div class="card custom-card">
                                <div class="card-header justify-content-between">
                                    <div class="card-title">
                                        Options
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="btn-list">
                                        <div class="d-grid gap-2 mb-4">
                                            <button class="btn btn-secondary btn-wave" type="button">Reprint Last Label</button>
                                            <button class="btn btn-secondary btn-wave" type="button">New Customer</button>
                                            <button class="btn btn-secondary btn-wave" id="updateReceivers" type="button">Refresh Receivers</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer d-none border-top-0">

                            </div>
                        </div>
                    </div>
                    <!-- End:: row-1 -->
                    <!-- Start:: row-2 -->
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card custom-card">
                                <div class="card-header justify-content-between">
                                    <div class="card-title">
                                        Packages
                                    </div>
                                    <div class="prism-toggle">
                                        <button class="btn btn-sm btn-primary-light">Show Code<i class="ri-code-line ms-2 d-inline-block align-middle"></i></button>
                                    </div>
                                </div>
                                <div class="card-body">
                            
                                    <div class="table-responsive">
                                        <table class="table text-nowrap">
                                            <caption>Last 5 Packages</caption>
                                            <thead>
                                                <tr>
                                                    <th scope="col">S.No</th>
                                                    <th scope="col">Country</th>
                                                    <th scope="col">Medals Won</th>
                                                    <th scope="col">No Of Athletes</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <th scope="row">01</th>
                                                    <td>United States</td>
                                                    <td>2012<i class="ri-medal-line mx-2"></i></td>
                                                    <td>1823</td>
                                                </tr>
                                                <tr>
                                                    <th scope="row">02</th>
                                                    <td>United Kingdom</td>
                                                    <td>1012<i class="ri-medal-line mx-2"></i></td>
                                                    <td>992</td>
                                                </tr>
                                                <tr>
                                                    <th scope="row">03</th>
                                                    <td>Germany</td>
                                                    <td>914<i class="ri-medal-line mx-2"></i></td>
                                                    <td>875</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>                            
                                <div class="card-footer d-none border-top-0">
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- End:: row-2 -->
                 
                </div>

<?php $content = ob_get_clean(); ?>
<!-- This code is useful for content -->

<!-- This code is useful for internal scripts  -->
<?php ob_start(); ?>

<!-- JQUERY JS -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">

<script>

$(document).ready(function() {

    // Variable to hold the initial autocomplete data
    let autocompleteData = [];

    // Function to initialize autocomplete with local data source filtering

    function loadAutocompleteData(refreshCache = false) {
        $.ajax({
            url: "assets/php/_get_autocomplete_customers.php",
            dataType: "json",
            data: {
                term: "",
                refresh_cache: refreshCache ? "1" : "0"
            },
            beforeSend: function() {
                console.log(refreshCache ? 'Refreshing autocomplete options...' : 'Loading initial autocomplete options...');
            },
            success: function(autocompleteData) {
                console.log('Autocomplete data loaded:', autocompleteData);

                // Destroy existing autocomplete to avoid duplicates if any
                if ($("#receiverSearch").data("ui-autocomplete")) {
                    $("#receiverSearch").autocomplete("destroy");
                }

                $("#receiverSearch").autocomplete({
                    minLength: 0,
                    source: function(request, response) {
                        const term = request.term.toLowerCase();

                        if (!term) {
                            response(autocompleteData);
                            return;
                        }

                        const filtered = $.grep(autocompleteData, function(item) {
                            return item.label && item.label.toLowerCase().indexOf(term) !== -1;
                        });

                        response(filtered);
                    },
                    select: function(event, ui) {
                        $("#customerKey").val(ui.item.id);
                        $("#receiverSearch").val(ui.item.label || ui.item.value);
                        return false;
                    },
                    focus: function(event, ui) {
                        $("#receiverSearch").val(ui.item.label || ui.item.value);
                        return false;
                    }
                });

                // Set default text only if not refreshing cache
                if (!refreshCache) {
                    $("#receiverSearch").attr("placeholder", "receiver");
                }
            },
            error: function() {
                console.log('Failed to load autocomplete data.');
                $("#receiverSearch").autocomplete({
                    source: []
                });
            }
        });
    }

    // Initial load without refresh
    loadAutocompleteData(false);

    // Setup click handler to refresh cache on button click
    $("#updateReceivers").on("click", function() {
        loadAutocompleteData(true);
    });

/*	$.ajax({
		type: 'POST',
	    dataType: 'json',
		url: 'assets/php/_get_autocomplete_customers.php',
		data: {

		},
		before: function(){

		},
		success: function(response){
		/*		$('#receiverSearch').fadeOut('slow', function() {
							$('#receiverSearch').attr("placeholder", "Please Enter the Recipient's Name");
						});
						$("#receiverSearch").autocomplete({
							source: response,
							minLength: 2,
							select: function(event, ui) {
								$('#customerKey').val(ui.item.id);
								//$('#boxSize').empty();
								//$('#boxSize').multiselect('rebuild');

								var output = [];
									
								$.each(available_package_sizes.package_sizes, function(key, value) {

									if (ui.item.pricegroup == value.price_group) {
										output.push('<option value="' + value.package_size_key + '">' + value.size_name + '</option>');
									}

								});
								//$('#boxSize').html(output.join(''));
								//$('#boxSize').multiselect('rebuild');

							}
						}).fadeIn('slow');
            alert(response);
		},
		error: function(xhr, err){
			alert('Autocomplete Receivers Not Updated');
			alert(xhr.responseText);
			alert(err);
		},
		complete: function(){
			//$('#boxSize').multiselect();
		}
	});*/
});

</script>
<?php $scripts = ob_get_clean(); ?>
<!-- This code is useful for internal scripts  -->

<!-- This code use for render base file -->
<?php include 'layouts/base.php'; ?>
<!-- This code use for render base file -->