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

require 'db_connect.php';

date_default_timezone_set('Africa/Nairobi');

$page_title = "Damages Report | Cashier POS";

$message = "";

/* -----------------------------
   Pagination & Show X Entries
------------------------------*/
$limit_options = [10, 25, 50, 100];
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 10;
if (!in_array($limit, $limit_options, true)) {
    $limit = 10;
}
$page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

// Count total damage records
$countResult = $conn->query("SELECT COUNT(*) AS total FROM damages");
$totalRows   = (int)($countResult->fetch_assoc()['total'] ?? 0);
$totalPages  = $totalRows > 0 ? max(1, (int)ceil($totalRows / $limit)) : 1;
if ($page > $totalPages) $page = $totalPages;

/* -----------------------------
   Handle Add Damage
------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_damage'])) {
    $product_id  = intval($_POST['product_id'] ?? 0);
    $quantity    = intval($_POST['quantity'] ?? 0);
    $description = trim($_POST['description'] ?? '');
    $cashier     = $_SESSION['username'];
    $date        = date('Y-m-d H:i:s');

    if ($product_id <= 0 || $quantity <= 0) {
        $message = "<div class='alert alert-error'>❌ Please select a product and enter a valid quantity.</div>";
    } else {
        $productRes = $conn->query("SELECT * FROM products WHERE id = $product_id");
        $product    = $productRes ? $productRes->fetch_assoc() : null;

        if (!$product) {
            $message = "<div class='alert alert-error'>❌ Product not found.</div>";
        } elseif ($quantity > (int)$product['quantity']) {
            $message = "<div class='alert alert-error'>❌ Not enough stock available.</div>";
        } else {
            $amount_lost = (float)$product['buying_price'] * $quantity;

            $stmt = $conn->prepare("
                INSERT INTO damages (product_name, quantity, amount, description, cashier, damaged_date)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            if ($stmt) {
                $stmt->bind_param(
                    "sidsss",
                    $product['name'],
                    $quantity,
                    $amount_lost,
                    $description,
                    $cashier,
                    $date
                );

                if ($stmt->execute()) {
                    $stmt->close();

                    $new_stock = (int)$product['quantity'] - $quantity;
                    $conn->query("UPDATE products SET quantity = $new_stock WHERE id = $product_id");

                    header("Location: add_damages.php?added=1");
                    exit();
                } else {
                    $message = "<div class='alert alert-error'>❌ Error saving damage record: " . htmlspecialchars($stmt->error) . "</div>";
                    $stmt->close();
                }
            } else {
                $message = "<div class='alert alert-error'>❌ Error preparing statement: " . htmlspecialchars($conn->error) . "</div>";
            }
        }
    }
}

/* -----------------------------
   Handle Delete
------------------------------*/
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    if ($id > 0) {
        $conn->query("DELETE FROM damages WHERE id = $id");
    }
    header("Location: add_damages.php?deleted=1");
    exit();
}

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

/* -----------------------------
   Fetch products for dropdown
------------------------------*/
$product_list = $conn->query("
    SELECT id, name, quantity
    FROM products
    ORDER BY name ASC
");

/* -----------------------------
   Calculate Grand Total
------------------------------*/
$grandTotalResult = $conn->query("SELECT SUM(amount) AS grand_total FROM damages");
$grandTotalRow    = $grandTotalResult->fetch_assoc();
$grandTotal       = (float)($grandTotalRow['grand_total'] ?? 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        /* ====== Layout + sticky footer ====== */
        html, body {
            height: 100%;
        }
        body {
            min-height: 100vh;
            margin: 0;
            display: flex;
            flex-direction: column;
        }
        .cashier-shell {
            flex: 1;
            display: flex;
            min-height: 0;
        }
        .cashier-main {
            flex: 1;
            min-width: 0;
            padding: 24px 30px 34px;
        }
        footer {
            position: relative !important;
            bottom: auto !important;
            width: 100%;
            margin-top: auto;
        }

        /* ====== HERO TOP BAR (like screenshot) ====== */
        .cashier-hero-bar {
            background: linear-gradient(90deg, #e0f7ff 0%, #f7fbff 35%, #e6f5ff 100%);
            border-radius: 14px;
            padding: 14px 22px;
            margin-bottom: 18px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 20px;
            border: 1px solid rgba(148,163,184,0.35);
        }
        .hero-left h1 {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
            color: #020617;
        }
        .hero-left p {
            margin: 2px 0 0;
            font-size: 13px;
            color: #64748b;
        }
        .hero-nav {
            display: flex;
            align-items: center;
            gap: 16px;
            flex-wrap: wrap;
        }
        .hero-tabs {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }
        .hero-tab {
            font-size: 13px;
            padding: 7px 14px;
            border-radius: 999px;
            text-decoration: none;
            color: #0f172a;
            background: transparent;
        }
        .hero-tab:hover {
            background: rgba(148,163,184,0.18);
        }
        .hero-tab.active {
            background: #06b6d4;
            color: #f9fafb;
            font-weight: 600;
        }
        .hero-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .hero-menu-btn {
            width: 36px;
            height: 36px;
            border-radius: 999px;
            border: none;
            background: #06b6d4;
            color: #f9fafb;
            font-size: 18px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        .hero-menu-btn:focus {
            outline: none;
        }

        /* ====== Page cards / table – dark default ====== */
        .pos-card,
        .pos-table-card {
            background: linear-gradient(135deg, #064ab8 0%, #022a6b 55%, #021d53 100%);
            border-radius: 18px;
            padding: 18px 22px 22px;
            box-shadow: 0 20px 45px rgba(0,0,0,0.55);
            color: #E9F5FF;
            border: 1px solid rgba(130,238,253,0.5);
            margin-bottom: 22px;
        }

        .pos-card-header h2 {
            font-size: 19px;
            font-weight: 600;
        }

        .pos-card-header p {
            font-size: 13px;
            color: #c3d8ff;
            margin-top: 4px;
        }

        .damage-form {
            margin-top: 14px;
            max-width: 520px;
        }

        .damage-form label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 4px;
            color: #E9F5FF;
        }

        .damage-form input,
        .damage-form select {
            width: 100%;
            padding: 9px 11px;
            border-radius: 10px;
            border: 1px solid rgba(130,238,253,0.5);
            background: #0a3d87;
            color: #E9F5FF;
            font-size: 13px;
            margin-bottom: 10px;
        }

        .damage-form input::placeholder {
            color: rgba(226,232,240,0.7);
        }

        .damage-form input:focus,
        .damage-form select:focus {
            outline: none;
            border-color: #00FFE5;
            box-shadow: 0 0 0 1px rgba(0,255,229,0.35);
        }

        .btn-primary {
            padding: 10px 18px;
            border-radius: 999px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            background: var(--cash-accent-turquoise);
            color: #011b35;
            margin-top: 4px;
        }

        .btn-primary:hover {
            filter: brightness(1.08);
        }

        .alert {
            margin-bottom: 10px;
            padding: 8px 10px;
            border-radius: 10px;
            font-size: 13px;
            border-left-width: 4px;
            border-left-style: solid;
        }

        .alert-success {
            background: rgba(34,197,94,0.12);
            border-left-color: rgba(34,197,94,0.9);
            color: #bbf7d0;
        }

        .alert-error {
            background: rgba(239,68,68,0.14);
            border-left-color: rgba(248,113,113,0.95);
            color: #fecaca;
        }

        .pos-table-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 14px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }

        .pos-table-header h3 {
            font-size: 17px;
            font-weight: 600;
        }

        .pos-table-header p {
            font-size: 12px;
            color: #c3d8ff;
            margin-top: 2px;
        }

        .pos-controls {
            display: flex;
            flex-direction: column;
            gap: 10px;
            align-items: flex-end;
        }

        .entries-form {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
        }

        .entries-form label {
            color: #c3d8ff;
        }

        .entries-form select {
            padding: 7px 11px;
            border-radius: 999px;
            border: 1px solid rgba(130,238,253,0.6);
            background: #063d8c;
            color: #E9F5FF;
            font-size: 13px;
        }

        .badge-muted {
            font-size: 11px;
            padding: 4px 9px;
            border-radius: 999px;
            background: rgba(15,23,42,0.86);
            color: #c3d8ff;
        }

        .pos-table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 6px;
        }

        table.pos-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
            min-width: 850px;
        }

        .pos-table th,
        .pos-table td {
            padding: 9px 8px;
            text-align: center;
            border-bottom: 1px solid rgba(148,163,184,0.25);
            color: #F9FAFF;
        }

        .pos-table th {
            background: #012a73;
            position: sticky;
            top: 0;
            z-index: 1;
            font-weight: 600;
        }

        .pos-table tbody tr:nth-child(even) { background: rgba(2,35,98,0.82); }
        .pos-table tbody tr:nth-child(odd)  { background: rgba(1,26,80,0.82); }

        .pos-table tbody tr:hover { background: rgba(130,238,253,0.16); }

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

        .empty-row {
            padding: 18px;
            color: #c3d8ff;
            text-align: center;
        }

        .delete-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 5px 10px;
            font-size: 12px;
            border-radius: 999px;
            text-decoration: none;
            border: 1px solid rgba(239,68,68,0.8);
            background: rgba(239,68,68,0.16);
            color: #fecaca;
        }

        .delete-btn:hover {
            background: rgba(239,68,68,0.3);
        }

        .totals-row {
            background: rgba(3,4,94,0.98);
            font-weight: 600;
        }

        .pagination {
            margin-top: 14px;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            justify-content: center;
        }

        .page-btn {
            padding: 7px 12px;
            border-radius: 999px;
            border: 1px solid rgba(130,238,253,0.7);
            background: rgba(0,26,80,0.4);
            color: #E9F5FF;
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
        }

        .page-btn:hover {
            background: rgba(15,23,42,0.96);
        }

        .page-btn.active {
            background: var(--cash-accent-turquoise);
            border-color: var(--cash-accent-turquoise);
            color: #011b35;
            font-weight: 700;
        }

        .back-link {
            text-decoration: none;
            font-size: 13px;
            color: #82EEFD;
        }

        .back-link:hover {
            text-decoration: underline;
        }

        @media (max-width: 960px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
            .pos-controls {
                align-items: flex-start;
            }
            .cashier-hero-bar {
                flex-direction: column;
                align-items: flex-start;
            }
            .hero-nav {
                width: 100%;
                justify-content: space-between;
            }
        }

        /* ====== LIGHT THEME OVERRIDES ====== */
        html[data-theme="light"] .cashier-hero-bar,
        body[data-theme="light"] .cashier-hero-bar,
        body.light-theme .cashier-hero-bar {
            background: linear-gradient(90deg, #f1fbff 0%, #ffffff 35%, #f5fbff 100%);
            border-color: rgba(148,163,184,0.4);
        }

        html[data-theme="light"] .pos-card,
        html[data-theme="light"] .pos-table-card,
        body[data-theme="light"] .pos-card,
        body[data-theme="light"] .pos-table-card,
        body.light-theme .pos-card,
        body.light-theme .pos-table-card {
            background: #ffffff !important;
            color: #0f172a !important;
            border-color: rgba(148,163,184,0.6) !important;
            box-shadow: 0 8px 22px rgba(15,23,42,0.12);
        }

        html[data-theme="light"] .pos-card-header p,
        body[data-theme="light"] .pos-card-header p,
        body.light-theme .pos-card-header p {
            color: #64748b !important;
        }

        html[data-theme="light"] .damage-form label,
        body[data-theme="light"] .damage-form label,
        body.light-theme .damage-form label {
            color: #0f172a !important;
        }

        html[data-theme="light"] .damage-form input,
        html[data-theme="light"] .damage-form select,
        body[data-theme="light"] .damage-form input,
        body[data-theme="light"] .damage-form select,
        body.light-theme .damage-form input,
        body.light-theme .damage-form select {
            background: #e5f2ff !important;
            color: #0f172a !important;
            border-color: rgba(148,163,184,0.9) !important;
        }

        html[data-theme="light"] .pos-table th,
        html[data-theme="light"] .pos-table td,
        body[data-theme="light"] .pos-table th,
        body[data-theme="light"] .pos-table td,
        body.light-theme .pos-table th,
        body.light-theme .pos-table td {
            color: #0f172a !important;
            border-bottom-color: rgba(148,163,184,0.35) !important;
        }

        html[data-theme="light"] .pos-table th,
        body[data-theme="light"] .pos-table th,
        body.light-theme .pos-table th {
            background: #e5f3ff !important;
        }

        html[data-theme="light"] .pos-table tbody tr:nth-child(even),
        html[data-theme="light"] .pos-table tbody tr:nth-child(odd),
        body[data-theme="light"] .pos-table tbody tr:nth-child(even),
        body[data-theme="light"] .pos-table tbody tr:nth-child(odd),
        body.light-theme .pos-table tbody tr:nth-child(even),
        body.light-theme .pos-table tbody tr:nth-child(odd) {
            background: #ffffff !important;
        }

        html[data-theme="light"] .pos-table tbody tr:hover,
        body[data-theme="light"] .pos-table tbody tr:hover,
        body.light-theme .pos-table tbody tr:hover {
            background: #e2f3ff !important;
        }

        html[data-theme="light"] .totals-row,
        body[data-theme="light"] .totals-row,
        body.light-theme .totals-row {
            background: #f1f5f9 !important;
        }

        html[data-theme="light"] .page-btn,
        body[data-theme="light"] .page-btn,
        body.light-theme .page-btn {
            background: #e5f2ff !important;
            color: #0f172a !important;
            border-color: rgba(148,163,184,0.8) !important;
        }

        html[data-theme="light"] .page-btn:hover,
        body[data-theme="light"] .page-btn:hover,
        body.light-theme .page-btn:hover {
            background: #dbeafe !important;
        }

        html[data-theme="light"] .badge-muted,
        body[data-theme="light"] .badge-muted,
        body.light-theme .badge-muted {
            background: #e2e8f0 !important;
            color: #0f172a !important;
        }

        html[data-theme="light"] .delete-btn,
        body[data-theme="light"] .delete-btn,
        body.light-theme .delete-btn {
            background: #fee2e2 !important;
            color: #b91c1c !important;
            border-color: #fecaca !important;
        }
    </style>
</head>
<body>

<div class="cashier-shell">
    <?php include "cashier_sidebar.php"; ?>

    <main class="cashier-main">

        <!-- HERO TOP BAR (like your screenshot) -->
        <header class="cashier-hero-bar">
            <div class="hero-left">
                <h1>Damaged Products | Cashier POS</h1>
                <p>Record stock that is broken, expired, or otherwise lost.</p>
            </div>

            <div class="hero-nav">
                <nav class="hero-tabs">
                    <a href="cashier_dashboard.php" class="hero-tab">Dashboard</a>
                    <a href="record_sale.php" class="hero-tab">Sales</a>
                    <a href="view_today_sales.php" class="hero-tab">Today’s Sales</a>
                    <a href="cashier_transactions.php" class="hero-tab">Transactions</a>
                    <a href="customers.php" class="hero-tab">Customers</a>
                    <a href="add_expense.php" class="hero-tab">Expenses</a>
                    <a href="customer_debts.php" class="hero-tab">Debts</a>
                    <a href="add_damages.php" class="hero-tab active">Damaged</a>
                </nav>

                <div class="hero-actions">
                    <!-- If you already have a theme toggle component, you can replace this with it -->
                    <!-- Placeholder mini-pill for "Theme" so it visually matches screenshot -->
                    <div class="badge-muted" style="border-radius:999px;padding:5px 12px;font-size:12px;">
                        Theme
                    </div>
                    <button class="hero-menu-btn" type="button" onclick="toggleCashierSidebar()">
                        ☰
                    </button>
                </div>
            </div>
        </header>

        <!-- Add damage form -->
        <section class="pos-card">
            <div class="pos-card-header">
                <h2>Record damage</h2>
                <p>Select a product and quantity. The system will calculate the loss at buying price and reduce stock.</p>
            </div>

            <?php if (isset($_GET['added'])): ?>
                <div class="alert alert-success">✔ Damage recorded successfully.</div>
            <?php endif; ?>

            <?php if (isset($_GET['deleted'])): ?>
                <div class="alert alert-success">✔ Damage deleted successfully.</div>
            <?php endif; ?>

            <?php if ($message): ?>
                <?= $message ?>
            <?php endif; ?>

            <form method="POST" class="damage-form">
                <label for="product_id">Select product</label>
                <select id="product_id" name="product_id" required>
                    <option value="">-- choose product --</option>
                    <?php if ($product_list && $product_list->num_rows > 0): ?>
                        <?php while ($p = $product_list->fetch_assoc()): ?>
                            <option value="<?= (int)$p['id'] ?>">
                                <?= htmlspecialchars($p['name']) ?> (Stock: <?= (int)$p['quantity'] ?>)
                            </option>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </select>

                <label for="quantity">Quantity damaged</label>
                <input type="number" id="quantity" name="quantity" min="1" required>

                <label for="description">Description</label>
                <input
                    type="text"
                    id="description"
                    name="description"
                    placeholder="e.g. broken, expired"
                >

                <button type="submit" name="add_damage" class="btn-primary">Add damage</button>
            </form>
        </section>

        <!-- Damages table -->
        <section class="pos-table-card">
            <div class="pos-table-header">
                <div>
                    <h3>Damages report</h3>
                    <p>
                        <?= $totalRows ? "Showing page $page of $totalPages" : "No damage records yet." ?>
                    </p>
                </div>

                <div class="pos-controls">
                    <span class="badge-muted">
                        Grand total loss: KES <?= number_format($grandTotal, 2) ?>
                    </span>

                    <form method="GET" class="entries-form">
                        <label>Show</label>
                        <select name="limit" onchange="this.form.submit()">
                            <?php foreach ($limit_options as $opt): ?>
                                <option value="<?= $opt ?>" <?= ($limit === $opt) ? 'selected' : '' ?>>
                                    <?= $opt ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <span style="color:var(--cash-text-muted);">entries</span>
                    </form>
                </div>
            </div>

            <div class="pos-table-wrapper">
                <table class="pos-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Product</th>
                            <th>Quantity</th>
                            <th>Loss (KES)</th>
                            <th>Description</th>
                            <th>Cashier</th>
                            <th>Date</th>
                            <th>Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $page_total = 0;
                        if ($damages && $damages->num_rows > 0):
                            while ($row = $damages->fetch_assoc()):
                                $page_total += (float)$row['amount'];
                        ?>
                            <tr>
                                <td><?= (int)$row['id'] ?></td>
                                <td class="cell-left"><?= htmlspecialchars($row['product_name']) ?></td>
                                <td><?= (int)$row['quantity'] ?></td>
                                <td><?= number_format((float)$row['amount'], 2) ?></td>
                                <td class="cell-left"><?= htmlspecialchars($row['description']) ?></td>
                                <td><?= htmlspecialchars($row['cashier']) ?></td>
                                <td><?= htmlspecialchars($row['damaged_date']) ?></td>
                                <td>
                                    <a href="add_damages.php?delete=<?= (int)$row['id'] ?>"
                                       class="delete-btn"
                                       onclick="return confirm('Delete this damage record?');">
                                        Delete
                                    </a>
                                </td>
                            </tr>
                        <?php
                            endwhile;
                        ?>

                            <tr class="totals-row">
                                <td colspan="3" style="text-align:right;">Page total loss</td>
                                <td>KES <?= number_format($page_total, 2) ?></td>
                                <td colspan="4"></td>
                            </tr>

                            <tr class="totals-row">
                                <td colspan="3" style="text-align:right;">Grand total loss</td>
                                <td>KES <?= number_format($grandTotal, 2) ?></td>
                                <td colspan="4"></td>
                            </tr>

                        <?php else: ?>
                            <tr>
                                <td colspan="8" class="empty-row">No damage records found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

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

            <div style="margin-top: 14px;">
                <a href="cashier_dashboard.php" class="back-link">← Back to dashboard</a>
            </div>
        </section>

    </main>
</div>


</body>
</html>
