<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

// Fetch shipment data with statuses
$getShipdata = mysqli_query($conn, "
    SELECT 
        origin,
        destination,
        COUNT(*) AS totalshipment,
        SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS origin_count,
        SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END) AS transit_count,
        SUM(CASE WHEN status = 7 THEN 1 ELSE 0 END) AS destination_count,
        SUM(CASE WHEN status = 9 THEN 1 ELSE 0 END) AS delivered_count
    FROM shipment
") or die(mysqli_error($conn));

$totshipments = mysqli_fetch_assoc($getShipdata);


$getQuerydata = mysqli_query($conn, "
    SELECT 
        origin,
        destination,
        COUNT(*) AS totalshipment,
        SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS origin_count,
        SUM(CASE WHEN status = 5 THEN 1 ELSE 0 END) AS transit_count,
        SUM(CASE WHEN status = 7 THEN 1 ELSE 0 END) AS destination_count,
        SUM(CASE WHEN status = 9 THEN 1 ELSE 0 END) AS delivered_count
    FROM shipment
    GROUP BY origin, destination
    ORDER BY origin, destination
") or die(mysqli_error($conn));

$shipments = [];
while ($fetdata = mysqli_fetch_assoc($getQuerydata)) {
    $shipments[] = $fetdata;
}
?>


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Shipment Dashboard</title>

    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body {
            background: #f8f9fa;
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        }

        .py-5 {
            padding-top: 1rem !important;
            padding-bottom: 3rem !important;
        }

        .stat-card {
            border-radius: 20px;
            padding: 10px;
            text-align: center;
            color: #fff;
            font-size: 15px;
            font-weight: bold;
            box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
        }

        .stat-number {
            font-size: 2rem;
            margin-top: 10px;
        }

        .shipment-carddt {
            border-radius: 15px;
            padding: 12px;
            background: #fff;
            box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s ease-in-out;
            margin-top: -10px !important;
        }

        .shipment-carddt:hover {
            transform: translateY(-5px);
        }

        .badge {
            font-size: 0.9rem;
            padding: 0.5em 0.8em;
            border-radius: 8px;
        }

        .search-box {
            max-width: 300px;
        }

        .pagination {
            justify-content: center;
            margin-top: 5px !important;
        }
    </style>
</head>

<body>
    <div class="container py-5">

        <!-- Shipment Summary -->
        <div class="row g-4 mb-4 justify-content-center text-center">
            <div class="col-md-3">
                <div class="stat-card " style="background-color: #7b2cbf;">
                    <span style="font-size:22px;">Total Shipment</span>
                    <div class="stat-number"><?=  $totshipments['totalshipment'] ?></div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stat-card bg-warning">
                    <span style="font-size:22px;">At Origin</span>
                    <div class="stat-number" onclick="window.open('shipmentlist.php?status=1', '_blank')"> <?=  $totshipments['origin_count'] ?> </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stat-card bg-primary">
                    <span style="font-size:22px;">In Transit</span>
                    <div class="stat-number" onclick="window.open('shipmentlist.php?status=5', '_blank')"><?=  $totshipments['transit_count'] ?></div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stat-card " style="background-color: #a53860;">
                    <span style="font-size:22px;">At Destination</span>
                    <div class="stat-number" onclick="window.open('shipmentlist.php?status=7', '_blank')"><?=  $totshipments['destination_count'] ?></div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="stat-card bg-success">
                    <span style="font-size:22px;">Delivered</span>
                    <div class="stat-number"onclick="window.open('shipmentlist.php?status=9', '_blank')"><?=  $totshipments['delivered_count'] ?></div>
                </div>
            </div>
        </div>


        <div class="d-flex justify-content-between align-items-center mb-4">
            <h4 class="fw-bold text-primary">📦 Shipment Overview</h4>
            <input type="text" id="searchBox" class="form-control search-box" placeholder="Search...">
        </div>

        <div class="row g-4" id="shipmentCards">
            <?php foreach ($shipments as $s): ?>
                <div class="col-md-4 shipment-card-wrapper">
                    <div class="shipment-carddt">
                        <h5 class="mb-2"><?= htmlspecialchars($s['origin']) ?> → <?= htmlspecialchars($s['destination']) ?>
                        </h5>
                        <p class="text-muted mb-3">Total Shipments: <span class="fw-bold"><?= $s['totalshipment'] ?></span>
                        </p>

                        <div class="mb-2">
                            <span class="badge bg-secondary">Origin: <?= $s['origin_count'] ?></span>
                            <span class="badge bg-warning">Transit: <?= $s['transit_count'] ?></span>
                        </div>
                        <div class="mb-2">
                            <span class="badge bg-primary">Destination: <?= $s['destination_count'] ?></span>
                            <span class="badge bg-success">Delivered: <?= $s['delivered_count'] ?></span>
                        </div>

                        <div class="progress mt-3" style="height:8px;">
                            <?php
                            $progress = $s['totalshipment'] > 0
                                ? round(($s['delivered_count'] / $s['totalshipment']) * 100)
                                : 0;
                            ?>
                            <div class="progress-bar bg-primary" role="progressbar" style="width: <?= $progress ?>%;"></div>
                        </div>
                        <small class="text-muted"><?= $progress ?>% Delivered</small>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Pagination Controls -->
        <nav>
            <ul class="pagination mt-4" id="pagination"></ul>
        </nav>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        const cardsPerPage = 6;
        let currentPage = 1;
        let searchTerm = ""; // keep current search globally

        function paginateCards() {
            const allCards = $("#shipmentCards .shipment-card-wrapper");

            // Filter by searchTerm each time (do NOT rely on :visible)
            const filteredCards = allCards.filter(function () {
                return $(this).text().toLowerCase().indexOf(searchTerm) > -1;
            });

            const totalCards = filteredCards.length;
            const totalPages = Math.max(1, Math.ceil(totalCards / cardsPerPage));

            // Clamp page
            if (currentPage > totalPages) currentPage = totalPages;
            if (currentPage < 1) currentPage = 1;

            // Hide all, then show just the slice of filtered cards
            allCards.hide();
            if (totalCards > 0) {
                const start = (currentPage - 1) * cardsPerPage;
                const end = start + cardsPerPage;
                filteredCards.slice(start, end).show();
            }

            // Build pagination
            const pagination = $("#pagination");
            pagination.empty();

            // If no results, leave pagination empty and stop
            if (totalCards === 0) return;

            // Prev
            pagination.append(
                `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
         <a class="page-link" href="#" data-page="${currentPage > 1 ? currentPage - 1 : 1}">Prev</a>
       </li>`
            );

            // Page numbers
            for (let i = 1; i <= totalPages; i++) {
                pagination.append(
                    `<li class="page-item ${i === currentPage ? 'active' : ''}">
           <a class="page-link" href="#" data-page="${i}">${i}</a>
         </li>`
                );
            }

            // Next
            pagination.append(
                `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
         <a class="page-link" href="#" data-page="${currentPage < totalPages ? currentPage + 1 : totalPages}">Next</a>
       </li>`
            );

            // Click handling
            $("#pagination .page-link").off().on("click", function (e) {
                e.preventDefault();
                const page = parseInt($(this).attr("data-page"), 10);
                if (!isNaN(page)) {
                    // Guard within range
                    if (page >= 1 && page <= totalPages) {
                        currentPage = page;
                        paginateCards();
                    }
                }
            });
        }

        // Search handler — only updates searchTerm and reruns paginate
        $("#searchBox").on("input", function () {
            searchTerm = this.value.toLowerCase();
            currentPage = 1;
            paginateCards();
        });

        // Init
        $(document).ready(function () {
            paginateCards();
        });
    </script>



</body>

</html>