<?php
session_start();

if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.php");
    exit();
}

require 'db_connect.php';

// Pagination settings
$limit  = 10;
$page   = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page   = max(1, $page);
$offset = ($page - 1) * $limit;

// Count total records
$totalRow = $conn->query("SELECT COUNT(*) AS total FROM damages")->fetch_assoc();
$total       = (int)($totalRow['total'] ?? 0);
$total_pages = $total > 0 ? (int)ceil($total / $limit) : 1;

// Fetch page data
$res = $conn->query("
    SELECT *
    FROM damages
    ORDER BY damaged_date DESC
    LIMIT $limit OFFSET $offset
");

$rows      = [];
$page_qty  = 0;
$page_loss = 0;

while ($r = $res->fetch_assoc()) {
    $rows[]     = $r;
    $page_qty  += (int)$r['quantity'];
    $page_loss += (float)$r['amount'];
}

// Grand totals
$grand = $conn->query("
    SELECT 
        COALESCE(SUM(quantity), 0) AS qty, 
        COALESCE(SUM(amount), 0)   AS lost
    FROM damages
")->fetch_assoc();

$page_title = "Damaged Goods Report";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include("head.php"); ?>

    <style>
        body {
            font-family: 'Poppins', Arial, sans-serif;
            background: var(--bg-main, #001f3f);
            margin: 0;
            color: var(--text-main);
        }

        /* ============= LAYOUT + TOPBAR (SAME AS EXPENSES PAGE) ============= */
        .content-wrapper {
            margin-left: 260px; /* space for admin sidebar */
            padding: 24px 26px 32px;
            min-height: 100vh;
            box-sizing: border-box;
            background:
                radial-gradient(circle at top left, rgba(0,255,239,0.08), transparent 55%),
                var(--bg-main, #001f3f);
            transition: margin-left 0.3s ease, background 0.3s ease;
        }

        .content-wrapper.fullwidth {
            margin-left: 0;
        }

        .content-inner {
            max-width: 1600px;
            margin: 0 auto;
        }

        .topbar {
            background: var(--bg-sidebar);
            padding: 14px 18px;
            margin-bottom: 20px;
            border-radius: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border: 1px solid #B8860B;
            box-shadow: 0 6px 18px rgba(0,0,0,0.5);
            color: brown;
        }

        .topbar-left {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 13px;
        }

        .topbar-title {
            font-weight: 600;
            font-size: 15px;
            letter-spacing: 0.03em;
        }

        .menu-btn {
            font-size: 22px;
            cursor: pointer;
            color: var(--accent-gold, #f4b400);
            transition: 0.3s;
            line-height: 1;
        }

        .menu-btn:hover {
            color: #e6c34b;
        }

        .theme-toggle {
            border-radius: 999px;
            border: 1px solid rgba(184,134,11,0.7);
            padding: 6px 12px;
            background: rgba(0,0,0,0.4);
            color: #f9f9f9;
            font-size: 12px;
            cursor: pointer;
        }

        .theme-toggle:hover {
            background: rgba(0,0,0,0.65);
        }

        .topbar-user strong {
            font-weight: 600;
        }

        /* Sidebar hide on toggle (same logic as expenses page) */
        #sidebar.hidden {
            transform: translateX(-260px);
        }

        @media (max-width: 900px) {
            .content-wrapper {
                margin-left: 0;
                padding: 18px 16px 24px;
            }
        }

        @media (max-width: 768px){
            .content-wrapper {
                padding: 18px 14px 24px;
            }
        }

        /* ============= PAGE CONTENT STYLES (DAMAGED REPORT) ============= */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 18px;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            color: var(--text-heading);
        }

        .page-subtitle {
            font-size: 13px;
            color: var(--accent-gold);
            margin-top: 4px;
        }

        /* Card box */
        .card-box {
            width: 100%;
            max-width: 1600px;
            margin: 0 auto;
            background: var(--bg-card);
            padding: 20px 22px;
            border-radius: 14px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.35);
            border: 1px solid #0a4a85;
            color: var(--text-main);
        }

        body[data-theme="light"] .card-box {
            border-color: rgba(148,163,184,0.55);
            box-shadow: 0 10px 24px rgba(15,23,42,0.10);
        }

        h2 {
            text-align: center;
            font-size: 22px;
            color: var(--text-heading);
            font-weight: 600;
            margin-bottom: 10px;
        }

        /* Table wrapper */
        .table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 8px;
        }

        /* Table style */
        table {
            width: 100%;
            min-width: 1150px;
            margin-top: 10px;
            border-collapse: collapse;
            background: var(--bg-card);
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0,0,0,0.35);
            color: var(--text-main);
        }

        thead tr {
            background: var(--bg-table-head);
        }

        th {
            color: var(--text-heading);
            padding: 10px 12px;
            font-size: 13px;
            font-weight: 600;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.15);
            white-space: nowrap;
        }

        body[data-theme="light"] th {
            border-bottom-color: rgba(0,0,0,0.08);
        }

        td {
            padding: 9px 12px;
            text-align: center;
            background: var(--bg-table-row);
            border-bottom: 1px solid rgba(255,255,255,0.12);
            color: var(--text-main);
            font-size: 13px;
            white-space: nowrap;
        }

        body[data-theme="light"] td {
            border-bottom-color: rgba(0,0,0,0.06);
        }

        td.product-cell {
            text-align: left;
        }

        tbody tr:nth-child(even) {
            background: var(--bg-table-row);
            opacity: 0.96;
        }

        tbody tr:hover {
            background: var(--bg-table-hover);
        }

        .numeric {
            text-align: right;
        }

        /* Totals row */
        .totals-row {
            background: var(--bg-main);
            font-weight: 700;
        }

        .totals-row td {
            border-top: 1px solid rgba(255,255,255,0.25);
        }

        body[data-theme="light"] .totals-row td {
            border-top-color: rgba(0,0,0,0.10);
        }

        /* Pagination */
        .pagination {
            text-align: center;
            margin-top: 18px;
        }

        .pagination a {
            padding: 7px 12px;
            background: var(--bg-card);
            color: var(--text-main);
            border-radius: 5px;
            margin: 3px;
            text-decoration: none;
            border: 1px solid #0a4a85;
            font-size: 13px;
        }

        body[data-theme="light"] .pagination a {
            border-color: rgba(148,163,184,0.55);
        }

        .pagination a.active {
            background: #5a47f5;
            font-weight: 700;
            border-color: #5a47f5;
            color: #ffffff;
        }

        .pagination a:hover {
            background: var(--bg-table-hover);
            border-color: #014b94;
        }

        /* Grand totals box */
        .summary-box {
            width: 100%;
            max-width: 520px;
            margin: 22px auto 10px auto;
            background: var(--bg-card);
            padding: 14px 16px;
            border-radius: 10px;
            border-left: 8px solid var(--accent-gold);
            font-size: 15px;
            font-weight: 600;
            color: var(--text-main);
            text-align: center;
            box-shadow: 0 4px 10px rgba(0,0,0,0.3);
        }

        .summary-box span.label {
            color: var(--text-main);
        }

        .summary-box span.value {
            color: var(--accent-gold);
        }

        footer {
            background: transparent;
            margin-top: 24px;
        }
    </style>
</head>

<body>

<?php include("sidebar.php"); ?>

<div class="content-wrapper" id="content-wrapper">

    <!-- TOP BAR (SAME LOGIC AS EXPENSES PAGE) -->
    <div class="topbar">
        <div class="topbar-left">
            <span class="menu-btn" onclick="toggleAdminSidebar()">☰</span>
            <span class="topbar-title">Admin Panel</span>
        </div>
        <div class="topbar-right">
            <button class="theme-toggle" type="button" onclick="toggleAdminTheme()">
                🌓 Theme
            </button>
            <span class="topbar-user">
                Logged in as
                <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></strong>
            </span>
        </div>
    </div>

    <div class="content-inner">

        <div class="page-header">
            <div>
                <div class="page-title">Damaged Goods Report</div>
                <div class="page-subtitle">
                    Page <?= $page ?> of <?= $total_pages ?> (<?= $limit ?> per page)
                </div>
            </div>
        </div>

        <div class="card-box">

            <h2>Damaged Goods Report</h2>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Product</th>
                            <th>Qty Damaged</th>
                            <th>Total Loss (KES)</th>
                            <th>Description</th>
                            <th>Cashier</th>
                            <th>Date Reported</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!empty($rows)): ?>
                        <?php foreach($rows as $row): ?>
                        <tr>
                            <td><?= (int)$row['id'] ?></td>
                            <td class="product-cell"><?= htmlspecialchars($row['product_name']) ?></td>
                            <td class="numeric"><?= number_format((int)$row['quantity']) ?></td>
                            <td class="numeric"><?= number_format((float)$row['amount'], 2) ?></td>
                            <td><?= htmlspecialchars($row['description']) ?></td>
                            <td><?= htmlspecialchars($row['cashier']) ?></td>
                            <td><?= htmlspecialchars($row['damaged_date']) ?></td>
                        </tr>
                        <?php endforeach; ?>

                        <tr class="totals-row">
                            <td colspan="2">Page Totals</td>
                            <td class="numeric"><?= number_format($page_qty) ?></td>
                            <td class="numeric">KES <?= number_format($page_loss, 2) ?></td>
                            <td colspan="3"></td>
                        </tr>

                    <?php else: ?>
                        <tr>
                            <td colspan="7">No damage records found.</td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <div class="pagination">
                <?php for($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="?page=<?= $i ?>" class="<?= ($i == $page ? 'active' : '') ?>">
                        <?= $i ?>
                    </a>
                <?php endfor; ?>
            </div>

            <!-- Grand totals -->
            <div class="summary-box">
                <div>
                    <span class="label">Grand Total Damaged Quantity:</span>
                    <span class="value"><?= number_format((float)($grand['qty'] ?? 0)) ?></span>
                </div>
                <div>
                    <span class="label">Grand Total Loss:</span>
                    <span class="value">KES <?= number_format((float)($grand['lost'] ?? 0), 2) ?></span>
                </div>
            </div>

        </div> <!-- /card-box -->

        <?php include("footer.php"); ?>

    </div> <!-- /content-inner -->
</div> <!-- /content-wrapper -->

<script>
function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const wrapper = document.getElementById('content-wrapper');
    if (!sidebar || !wrapper) return;

    const isHidden = sidebar.classList.toggle('hidden');
    if (isHidden) {
        wrapper.classList.add('fullwidth');
    } else {
        wrapper.classList.remove('fullwidth');
    }
}
</script>

</body>
</html>
