<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Track My Order</title>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/alpinejs@3.10.3" defer></script>

    <style>
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes slideUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .fade-in {
            animation: fadeIn .7s ease forwards;
        }

        .timeline-item {
            opacity: 0;
            animation: slideUp .7s ease forwards;
        }
    </style>

</head>

<body class="bg-[#f4f6f9] min-h-screen">

<!-- ================= HEADER ================= -->
<header class="bg-white shadow sticky top-0 z-50">
    <div class="max-w-6xl mx-auto px-4 flex items-center justify-between h-20">

        <div class="flex items-center space-x-3">
            <img src="<?= base_url('uploads/MSFFLogo.png') ?>" class="h-14 w-auto">
            <div>
                <h3 class="text-2xl font-extrabold text-green-700">Multiplex Farms</h3>
                <p class="text-sm text-gray-600 italic">Safe Farms and Fresh Store</p>
            </div>
        </div>

        <?php if(session()->get('isLoggedIn')): ?>
        <div x-data="{ open:false }" class="relative">
            <button @click="open=!open"
                class="flex items-center bg-gray-100 px-4 py-2 rounded-lg hover:bg-gray-200 transition">
                <span class="text-sm font-semibold text-gray-700"><?= session()->get('phone') ?></span>
                <svg class="w-4 h-4 ml-2" fill="none" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M19 9l-7 7-7-7"/>
                </svg>
            </button>

            <div x-show="open" @click.away="open=false"
                 class="absolute right-0 mt-2 w-48 bg-white shadow-md rounded-lg py-2">
                <a href="<?= base_url('order-tracking') ?>" class="px-4 py-2 block hover:bg-gray-100">📦 My Orders</a>
                <hr>
                <a href="<?= base_url('auth/logout') ?>" class="px-4 py-2 block text-red-600">🔐 Logout</a>
            </div>
        </div>
        <?php endif; ?>

    </div>
</header>

<!-- ================= MAIN ================= -->
<div class="max-w-4xl mx-auto mt-10">

    <!-- Greeting -->
    <div class="bg-white shadow-md rounded-xl p-6 mb-8 fade-in">
        <h2 class="text-3xl font-bold text-gray-800">Hello, <?= esc($customer_name) ?> 👋</h2>
        <p class="text-gray-500 mt-2">
            Tracking orders for <strong><?= esc(session()->get('phone')) ?></strong>
        </p>
    </div>

    <!-- Select Order -->
    <div class="bg-white shadow-md rounded-xl p-6 fade-in">
        <h3 class="text-xl font-semibold text-gray-800 mb-4">Select Your Order</h3>

        <div class="flex gap-3">
            <select id="orderId"
                class="flex-1 p-3 border rounded-lg bg-gray-50 focus:ring-2 focus:ring-green-600">
                <option value="">-- Select Order --</option>

                <?php foreach($userOrders as $order): ?>
                <option value="<?= $order['id'] ?>">Order #<?= $order['id'] ?> — ₹<?= $order['total_amount'] ?></option>
                <?php endforeach; ?>

            </select>

            <button id="trackBtn"
                class="px-6 py-3 bg-green-600 text-white rounded-lg shadow hover:bg-green-700">
                Track
            </button>
        </div>
    </div>

    <!-- Order Summary -->
    <div id="orderSummary" class="hidden bg-white shadow-md rounded-xl p-6 mt-6"></div>

    <!-- Progress Bar -->
    <div id="progressBarContainer" class="hidden bg-white shadow-md rounded-xl p-8 mt-6">
        <h3 class="text-xl font-bold text-gray-800 mb-6">Delivery Status</h3>

        <div class="relative">
            <div class="absolute top-5 left-0 right-0 h-1 bg-gray-300"></div>
            <div id="progressFill" class="absolute top-5 left-0 h-1 bg-green-600 rounded-full transition-all" style="width:0%"></div>

            <div class="flex justify-between text-center mt-6">
                <?php
                $icons = ["📦","📃","🚚","📍","✅"];
                $labels = ["Order Placed","Packed","Shipped","Out for Delivery","Delivered"];
                foreach($labels as $i => $label):
                ?>
                <div class="step">
                    <div class="stepIcon w-10 h-10 mx-auto rounded-full bg-gray-200 flex items-center justify-center text-xl">
                        <?= $icons[$i] ?>
                    </div>
                    <p class="text-gray-700 mt-2 text-sm"><?= $label ?></p>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Timeline -->
    <div id="trackingResult" class="hidden bg-white shadow-md rounded-xl p-6 mt-6 space-y-8 border-l-4 border-green-600"></div>

</div>


<!-- ================= CANCEL POPUP ================= -->
<div x-data="{ openCancel:false, orderId:null }"
     x-show="openCancel"
     x-cloak
     class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-[9999]">

    <div class="bg-white w-96 p-6 rounded-xl shadow-xl animate__animated animate__zoomIn">

        <img src="https://cdn-icons-png.flaticon.com/512/463/463612.png" class="w-16 mx-auto mb-3">

        <h2 class="text-xl font-bold text-gray-800">Cancel Order?</h2>
        <p class="text-gray-600 mt-2">
            Once cancelled, the order cannot be restored.
        </p>

        <div class="mt-6 flex justify-center gap-4">
            <button @click="openCancel=false"
                class="px-5 py-2 bg-gray-200 rounded-lg text-gray-700 hover:bg-gray-300">
                No, Keep Order
            </button>

            <button id="confirmCancelBtn"
                class="px-5 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
                Yes, Cancel
            </button>
        </div>

    </div>

</div>


<!-- ================= JAVASCRIPT ================= -->
<script>

function openCancelPopup(id){
    document.querySelector('[x-data]').__x.$data.openCancel = true;
    Alpine.store("cancelId", id);

    $("#confirmCancelBtn").off("click").on("click", function(){

        $.post("<?= base_url('order-tracking/cancelOrder/') ?>" + id, function(res){

            document.querySelector('[x-data]').__x.$data.openCancel = false;

            alert("Order Cancelled Successfully!");
            fetchTracking(id);

        }).fail(function(){
            alert("Error cancelling order!");
        });
    });
}



$(function(){

    function fetchTracking(orderId){

        $.get("<?= base_url('order-tracking/getStatus/') ?>" + orderId, function(res){

            $("#orderSummary, #progressBarContainer, #trackingResult")
                .removeClass("hidden").addClass("fade-in");

            $("#trackingResult").html("");

            if(res.success){

                // Progress
                let completed = res.data.length;
                let percent = (completed / 5) * 100;
                $("#progressFill").css("width", percent + "%");

                $(".stepIcon").each(function(i){
                    if(i < completed){
                        $(this).removeClass("bg-gray-200")
                               .addClass("bg-green-600 text-white");
                    }
                });

                // Timeline
                let delay = 0;
                res.data.forEach(function(step){
                    delay += 100;
                    $("#trackingResult").append(`
                        <div class="relative pb-8 timeline-item" style="animation-delay:${delay}ms">
                            <span class="absolute -left-6 top-2 w-4 h-4 bg-green-600 border-white border-2 rounded-full"></span>

                            <div class="bg-green-50 border border-green-100 p-4 rounded-lg">
                                <div class="text-lg font-bold text-green-700">${step.status}</div>
                                <div class="text-gray-600 mt-1">${step.remarks ?? ''}</div>
                                <div class="text-gray-400 text-xs mt-2">📅 ${step.updated_at}</div>
                            </div>
                        </div>
                    `);
                });

                // Summary + Action Buttons
                $("#orderSummary").html(`
                    <h3 class="text-xl font-semibold text-gray-800 mb-4">Order Summary</h3>

                    <div class="grid grid-cols-2 gap-4 mb-5">
                        <p><strong>Order ID:</strong> ${orderId}</p>
                        <p><strong>Total:</strong> ₹${res.data[0].total_amount}</p>
                        <p><strong>Last Update:</strong> ${res.data[0].updated_at}</p>
                        <p><strong>Status:</strong> ${res.data[0].order_status}</p>
                    </div>

                    <div class="flex gap-4">
                        <button 
                            class="px-6 py-2 bg-red-600 text-white rounded-lg shadow hover:bg-red-700"
                            onclick="openCancelPopup(${orderId})">
                            ❌ Cancel Order
                        </button>

                        <button class="px-6 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700">
                            🔄 Reorder
                        </button>

                        <button class="px-6 py-2 bg-yellow-500 text-white rounded-lg shadow hover:bg-yellow-600">
                            💸 Refund
                        </button>
                    </div>
                `);

            }
            else{
                $("#trackingResult").html(
                    "<div class='text-red-600 p-4'>" + res.message + "</div>"
                );
            }

        });
    }


    // Auto-select latest order
    let latest = $("#orderId option:nth-child(2)").val();
    if(latest){
        $("#orderId").val(latest);
        fetchTracking(latest);
    }

    // Manual Track Button
    $("#trackBtn").click(function(){
        let id = $("#orderId").val();
        if(!id){ alert("Please select an order!"); return; }
        fetchTracking(id);
    });

});
</script>

</body>
</html>
