<?php if (!isset($is_ajax) || $is_ajax == false): ?>
    <div id="queueWrapper">
        <style>
            .singleOrder {
                padding: 20px;
                border-radius: 10px;
            }
        </style>
    <?php endif; ?>

    <div class="dineinQueue">
        <div class="row mb-20">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body d-flex justify-content-between">
                        <div class="left">
                            <h4 class="text-4xl font-bold"><?= __("kitchen_queue"); ?></h4>
                            <p class="text-xl"><?= __("active_orders"); ?>:
                                <?= count(array_filter($order_list, function ($o) {
                                    return in_array($o->status, [0, 1]);
                                })) ?> </p>
                        </div>
                        <div class="right d-flex gap-5 flex-column text-center">
                            <h4 id="current_time" class="text-4xl font-bold text-yellow"><?= date('h:i A'); ?></h4>
                            <span id="current_date"><?= date('l, F j'); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="d-flex gap-20 flex-wrap mb-20 p-10">
                    <?php foreach ($order_list as  $key => $row): ?>
                        <div class="card-body singleOrder">
                            <div class="orderTops d-flex space-between">
                                <div class="left">
                                    <h2>#<?= $row->queue_position; ?></h2>
                                    <p class="fz-16"><?= __("table"); ?> <?= $row->table_no; ?></p>
                                </div>
                                <div class="right d-flex gap-5 flex-column">
                                    <?php if ($row->status == 0 && $row->is_preparing == 0): ?>
                                        <label class="label label-info p-5"><i class="far fa-dot-circle"></i> <?= __("new_order"); ?></label>
                                    <?php elseif ($row->status == 1 && in_array($row->is_preparing, [0, 1])): ?>
                                        <label class="label label-warning p-5"><i class="fa fa-spinner fa-spin"></i> <?= __("preparing"); ?></label>
                                    <?php else: ?>
                                        <label class="label label-success p-5"><i class="fa fa-check"></i> <?= __("completed"); ?></label>
                                    <?php endif; ?>
                                    <h4 class="fz-16"><?= $row->uid; ?></h4>
                                </div>
                            </div>
                            <div class="orderSummary d-flex space-between">
                                <span><?= $row->total_person ?? 1; ?> <?= __("person"); ?></span>

                                <?php if (in_array($row->status, [0, 1]) && in_array($row->is_preparing, [0, 1])): ?>
                                    <div class="text-right">
                                        <?php
                                        $minutes = (float) $row->estimated_time;
                                        $seconds = $minutes * 60;

                                        $baseTime = (!empty($row->accept_time) && $row->accept_time != '0000-00-00 00:00:00') ? $row->accept_time : $row->created_at;
                                        $dtBase = new DateTime($baseTime);

                                        $dtTo = clone $dtBase;
                                        $dtTo->modify("+$seconds seconds");

                                        // Pre-calculate time for initial display to avoid blinking
                                        $dtNow = new DateTime();
                                        $remaining_str = '0 ' . __("ontheways");

                                        if ($dtTo > $dtNow) {
                                            $diff = $dtNow->diff($dtTo);
                                            if ($diff->d > 0) {
                                                $remaining_str = $diff->d . "d " . $diff->h . "h " . $diff->i . "m " . $diff->s . "s";
                                            } elseif ($diff->h > 0) {
                                                $remaining_str = $diff->h . "h " . $diff->i . "m " . $diff->s . "s";
                                            } elseif ($diff->i > 0) {
                                                $remaining_str = $diff->i . "m " . $diff->s . "s";
                                            } elseif ($diff->s > 0) {
                                                $remaining_str = $diff->s . "s";
                                            }
                                        }
                                        ?>
                                        <span class="queueTime" data-id="<?= $row->id; ?>" data-time="<?= $dtTo->format('M d, Y H:i:s'); ?>"></span>
                                        <span class="fw-bold" id="show_time_<?= $row->id; ?>"><?= $remaining_str; ?></span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <?php if (!isset($is_ajax) || $is_ajax == false): ?>
    </div> <!-- End queueWrapper -->

    <script type="text/javascript">
        var countdownIntervals = [];

        function initCountdowns() {
            // Clear existing intervals
            countdownIntervals.forEach(clearInterval);
            countdownIntervals = [];

            $(".queueTime").each(function(i, e) {
                var id = $(this).data('id');
                var time = $(this).data('time');
                var countDownDate = new Date(time).getTime();

                function renderTime() {
                    var now = new Date().getTime();
                    var distance = countDownDate - now;

                    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
                    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

                    if (distance < 0) {
                        $('#show_time_' + id).html('');
                        return;
                    }

                    if (days > 0) {
                        $('#show_time_' + id).html(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
                    } else if (hours > 0) {
                        $('#show_time_' + id).html(hours + "h " + minutes + "m " + seconds + "s ");
                    } else if (minutes > 0) {
                        $('#show_time_' + id).html(minutes + "m " + seconds + "s ");
                    } else {
                        $('#show_time_' + id).html(seconds + "s ");
                    }
                }

                // ⚡ Show initial time immediately (NO FLICKER)
                renderTime();

                // Then update every second
                var x = setInterval(renderTime, 1000);

                countdownIntervals.push(x);
            });

        }

        function updateClock() {
            var now = new Date();
            var timeString = now.toLocaleTimeString('en-US', {
                hour: 'numeric',
                minute: '2-digit',
                hour12: true
            });
            var dateString = now.toLocaleDateString('en-US', {
                weekday: 'long',
                month: 'long',
                day: 'numeric'
            });
            var timeEl = document.getElementById('current_time');
            var dateEl = document.getElementById('current_date');
            if (timeEl) timeEl.innerHTML = timeString;
            if (dateEl) dateEl.innerHTML = dateString;
        }
        setInterval(updateClock, 1000);
        updateClock(); // initial call

        // Initial countdowns
        $(document).ready(function() {
            initCountdowns();
        });

        var shop_id = "<?= restaurant()->username; ?>";

        function loadQueue() {
            $.ajax({
                url: base_url + "dinein-queue/" + shop_id,
                type: "GET",
                dataType: "json",
                success: function(res) {
                    if (res.st === 1) {
                        $("#queueWrapper").html(res.load_data);
                        initCountdowns();
                        updateClock(); // Ensure clock is updated immediately after refresh
                        console.log('Queue updated successfully');
                    }
                }
            });
        }

        // Auto refresh every 5 seconds
        setInterval(loadQueue, 5000);
    </script>
<?php endif; ?>