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

require 'db_connect.php';

$page_title = "Payments History | Cashier POS";
$active     = 'payments';

$cashier = $_SESSION['username'] ?? 'unknown';

// ----- DATE FILTER -----
$today         = date('Y-m-d');
$selected_date = isset($_GET['date']) && $_GET['date'] !== '' ? $_GET['date'] : $today;

// Get list of distinct payment dates (last 30 days for example)
$dates_result = mysqli_query(
    $conn,
    "SELECT DISTINCT DATE(created_at) AS pay_date
     FROM payments
     ORDER BY pay_date DESC
     LIMIT 30"
);

$available_dates = [];
if ($dates_result) {
    while ($row = mysqli_fetch_assoc($dates_result)) {
        $available_dates[] = $row['pay_date'];
    }
}

/*
 |---------------------------------------------------------
 | Get payments for selected date
 | - Joins to customer_debts + products to show product
 |   for credit payments (especially partial ones).
 |---------------------------------------------------------
*/
$stmt = $conn->prepare("
    SELECT
        p.id,
        p.receipt_id,
        p.debt_id,
        p.payment_method,
        p.amount_due,
        p.paid_at,
        p.change_amount,
        p.mpesa_code,
        p.bank_ref,
        p.created_at,
        p.cashier,
        p.print_requested,
        p.is_debt_payment,
        d.product_id,
        pr.name AS product_name
    FROM payments p
    LEFT JOIN customer_debts d ON d.id = p.debt_id
    LEFT JOIN products pr       ON pr.id = d.product_id
    WHERE DATE(p.created_at) = ?
    ORDER BY p.created_at DESC
");
$stmt->bind_param("s", $selected_date);
$stmt->execute();
$payments_result = $stmt->get_result();

/*
 |---------------------------------------------------------
 | Calculate totals for that date (all payments)
 |---------------------------------------------------------
*/
$totals_stmt = $conn->prepare("
    SELECT
        SUM(amount_due)    AS total_due,
        SUM(paid_at)       AS total_paid,
        SUM(change_amount) AS total_change
    FROM payments
    WHERE DATE(created_at) = ?
");
$totals_stmt->bind_param("s", $selected_date);
$totals_stmt->execute();
$totals_row = $totals_stmt->get_result()->fetch_assoc();

$total_due    = $totals_row['total_due']    ?? 0;
$total_paid   = $totals_row['total_paid']   ?? 0;
$total_change = $totals_row['total_change'] ?? 0;

$stmt->close();
$totals_stmt->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'cashier_head.php'; ?>
    <style>
        :root {
            --cash-accent-main: var(--cash-accent-main, #22d3ee);
            --cash-accent-soft: var(--cash-accent-soft, #7dd3fc);
        }

        .cashier-main {
            padding: 24px 30px 34px;
            min-width: 0;
        }

        @media (max-width: 900px) {
            .cashier-main {
                padding: 18px 16px 26px;
            }
        }

        .pos-wrapper {
            max-width: 1280px;
            margin: 0 auto;
            width: 100%;
        }

        .pos-card {
            background:
                radial-gradient(circle at top left, rgba(34,211,238,0.10), transparent 55%),
                var(--cash-bg-card);
            border-radius: 18px;
            padding: 18px 22px 20px;
            box-shadow: 0 20px 45px rgba(0,0,0,0.55);
            color: var(--cash-text-main);
            border: 1px solid var(--cash-border-soft);
            margin-bottom: 22px;
        }

        html[data-theme="light"] .pos-card {
            background:
                radial-gradient(circle at top left, rgba(56,189,248,0.10), transparent 55%),
                #ffffff;
            box-shadow: 0 10px 22px rgba(15,23,42,0.12);
            border-color: #dbeafe;
            color: #0f172a;
        }

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

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

        .pos-header p {
            font-size: 13px;
            color: var(--cash-text-muted);
            margin-top: 3px;
        }

        html[data-theme="light"] .pos-header p {
            color: #475569;
        }

        /* DATE FILTER STRIP */

        .date-filter-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
            margin-bottom: 10px;
            font-size: 13px;
        }

        .date-pills {
            display: flex;
            flex-wrap: wrap;
            gap: 6px;
        }

        .date-pill {
            padding: 6px 10px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.55);
            background: rgba(0,22,60,0.75);
            color: #E9F5FF;
            text-decoration: none;
            font-size: 12px;
        }

        .date-pill.active {
            border-color: #22d3ee;
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            color: #011b35;
            font-weight: 600;
        }

        html[data-theme="light"] .date-pill {
            background: #eff6ff;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        .date-filter-form {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-left: auto;
        }

        .date-filter-form input[type="date"] {
            padding: 6px 10px;
            border-radius: 999px;
            border: 1px solid rgba(148,163,184,0.55);
            background: #001B3A;
            color: #E5E7EB;
            font-size: 12px;
        }

        html[data-theme="light"] .date-filter-form input[type="date"] {
            background: #ffffff;
            color: #0f172a;
            border-color: #cbd5f5;
        }

        .date-filter-form button {
            padding: 6px 10px;
            border-radius: 999px;
            border: none;
            font-size: 12px;
            cursor: pointer;
            background: linear-gradient(to right, #22d3ee, #0ea5e9);
            color: #011b35;
            font-weight: 600;
        }

        /* TABLE */

        .pos-table-wrapper {
            margin-top: 12px;
            overflow-x: auto;
        }

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

        .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;
            font-weight: 600;
        }

        html[data-theme="light"] .pos-table th {
            background: #eff6ff;
            color: #0f172a;
        }

        html[data-theme="light"] .pos-table td {
            color: #0f172a;
        }

        .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);
        }

        html[data-theme="light"] .pos-table tbody tr:nth-child(even) {
            background: #f9fafb;
        }

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

        html[data-theme="light"] .pos-table tbody tr:hover {
            background: #e0f2fe;
        }

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

        html[data-theme="light"] .totals-row {
            background: #e0f2fe;
        }

        .badge-method {
            padding: 3px 8px;
            border-radius: 999px;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.06em;
        }

        .badge-method.mpesa {
            background: rgba(16,185,129,0.2);
            color: #6ee7b7;
        }

        .badge-method.cash {
            background: rgba(59,130,246,0.18);
            color: #bfdbfe;
        }

        .badge-method.bank {
            background: rgba(234,179,8,0.18);
            color: #facc15;
        }

        html[data-theme="light"] .badge-method.mpesa {
            background: #dcfce7;
            color: #166534;
        }
        html[data-theme="light"] .badge-method.cash {
            background: #dbeafe;
            color: #1d4ed8;
        }
        html[data-theme="light"] .badge-method.bank {
            background: #fef9c3;
            color: #854d0e;
        }

        /* NEW: badge for type (normal vs credit) */
        .badge-type {
            padding: 3px 8px;
            border-radius: 999px;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.06em;
        }
        .badge-type.credit-partial {
            background: rgba(234,179,8,0.20);
            color: #facc15;
        }
        .badge-type.credit-settled {
            background: rgba(34,197,94,0.20);
            color: #bbf7d0;
        }
        .badge-type.normal {
            background: rgba(148,163,184,0.25);
            color: #e5e7eb;
        }

        html[data-theme="light"] .badge-type.credit-partial {
            background: #fef3c7;
            color: #92400e;
        }
        html[data-theme="light"] .badge-type.credit-settled {
            background: #dcfce7;
            color: #166534;
        }
        html[data-theme="light"] .badge-type.normal {
            background: #e5e7eb;
            color: #374151;
        }

        .no-data {
            padding: 14px 10px;
            text-align: center;
            font-size: 13px;
            color: #e5e7eb;
        }

        html[data-theme="light"] .no-data {
            color: #4b5563;
        }
    </style>
</head>
<body>

<div class="cashier-shell">

    <?php include 'cashier_sidebar.php'; ?>

    <main class="cashier-main" id="cashierMain">
        <div class="pos-wrapper">

            <!-- TOP BAR -->
            <div class="cashier-topbar">
                <div class="cashier-topbar-left">
                    <h1><?= htmlspecialchars($page_title); ?></h1>
                    <small>View all payments (normal & credit) and filter by date.</small>
                </div>
                <div class="cashier-topbar-right">
                    <nav class="cashier-topnav">
                        <a href="cashier_dashboard.php" class="<?= ($active === 'dashboard') ? 'active' : '' ?>">Dashboard</a>
                        <a href="record_sales.php" class="<?= ($active === 'sales') ? 'active' : '' ?>">Sales</a>
                        <a href="cashier_view_daily_sales.php" class="<?= ($active === 'daily_sales') ? 'active' : '' ?>">Today’s Sales</a>
                        <a href="customer_debts.php" class="<?= ($active === 'debts') ? 'active' : '' ?>">Credit Sales</a>
                        <a href="cashier_payments_history.php" class="<?= ($active === 'payments') ? 'active' : '' ?>">Payments</a>
                    </nav>

                    <button type="button" class="cashier-theme-toggle" onclick="toggleCashierTheme()">
                        <span class="icon">🌓</span>
                        <span class="label">Theme</span>
                    </button>

                    <button class="cashier-toggle" type="button" onclick="toggleCashierSidebar()">☰</button>
                </div>
            </div>

            <!-- PAYMENTS CARD -->
            <section class="pos-card">
                <div class="pos-header">
                    <div>
                        <h2>Payments by date</h2>
                        <p>Click a date below or choose a date to see all payments for that day.</p>
                    </div>
                </div>

                <!-- DATE FILTER -->
                <div class="date-filter-bar">
                    <div class="date-pills">
                        <?php if (!empty($available_dates)): ?>
                            <?php foreach ($available_dates as $d): ?>
                                <a
                                    href="?date=<?= htmlspecialchars($d); ?>"
                                    class="date-pill <?= ($d === $selected_date) ? 'active' : ''; ?>"
                                >
                                    <?= htmlspecialchars($d); ?>
                                </a>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span class="no-data">No payments recorded yet.</span>
                        <?php endif; ?>
                    </div>

                    <form method="get" class="date-filter-form">
                        <input type="date" name="date" value="<?= htmlspecialchars($selected_date); ?>">
                        <button type="submit">Go</button>
                    </form>
                </div>

                <!-- TABLE -->
                <div class="pos-table-wrapper">
                    <?php if ($payments_result->num_rows === 0): ?>
                        <div class="no-data">
                            No payments done on <strong><?= htmlspecialchars($selected_date); ?></strong>.
                        </div>
                    <?php else: ?>
                        <table class="pos-table">
                            <thead>
                                <tr>
                                    <th>Time</th>
                                    <th>Receipt</th>
                                    <th>Cashier</th>
                                    <th>Type</th>
                                    <th>Credit Ref / Product</th>
                                    <th>Method</th>
                                    <th>Amount due</th>
                                    <th>Amount paid</th>
                                    <th>Change</th>
                                    <th>M-Pesa code</th>
                                    <th>Bank ref</th>
                                    <th>Print</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($pay = mysqli_fetch_assoc($payments_result)): ?>
                                    <?php
                                        $isDebtPayment = !empty($pay['is_debt_payment']) && (int)$pay['is_debt_payment'] === 1;

                                        // Decide type label + badge class
                                        if ($isDebtPayment) {
                                            // If debt_id still exists in customer_debts join, it's partial (debt still open)
                                            $isPartial = !empty($pay['product_id']); // we joined to customer_debts
                                            if ($isPartial) {
                                                $typeLabel = "Credit (partial)";
                                                $typeClass = "badge-type credit-partial";
                                            } else {
                                                $typeLabel = "Credit (settled)";
                                                $typeClass = "badge-type credit-settled";
                                            }
                                        } else {
                                            $typeLabel = "Normal sale";
                                            $typeClass = "badge-type normal";
                                        }

                                        // Credit reference / product info
                                        if ($isDebtPayment) {
                                            $refParts = [];
                                            if (!empty($pay['debt_id'])) {
                                                $refParts[] = "Debt #".$pay['debt_id'];
                                            }
                                            if (!empty($pay['product_name'])) {
                                                $refParts[] = $pay['product_name'];
                                            }
                                            $creditRef = !empty($refParts) ? implode(" — ", $refParts) : "Credit payment";
                                        } else {
                                            $creditRef = "—";
                                        }

                                        $method = strtolower($pay['payment_method']);
                                        $badgeClassMethod = 'badge-method '.$method;
                                    ?>
                                    <tr>
                                        <td><?= date('H:i:s', strtotime($pay['created_at'])); ?></td>
                                        <td><?= htmlspecialchars($pay['receipt_id']); ?></td>
                                        <td><?= htmlspecialchars($pay['cashier']); ?></td>
                                        <td>
                                            <span class="<?= $typeClass; ?>">
                                                <?= htmlspecialchars($typeLabel); ?>
                                            </span>
                                        </td>
                                        <td><?= htmlspecialchars($creditRef); ?></td>
                                        <td>
                                            <span class="<?= $badgeClassMethod; ?>">
                                                <?= strtoupper(htmlspecialchars($pay['payment_method'])); ?>
                                            </span>
                                        </td>
                                        <td><?= number_format($pay['amount_due'], 2); ?></td>
                                        <td><?= number_format($pay['paid_at'], 2); ?></td>
                                        <td><?= number_format($pay['change_amount'], 2); ?></td>
                                        <td><?= htmlspecialchars($pay['mpesa_code']); ?></td>
                                        <td><?= htmlspecialchars($pay['bank_ref']); ?></td>
                                        <td>
                                            <?php if ($isDebtPayment): ?>
                                                <!-- Credit payments: do NOT show "Yes" here -->
                                                —
                                            <?php else: ?>
                                                <?= !empty($pay['print_requested']) ? 'Yes' : 'No'; ?>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>

                                <tr class="totals-row">
                                    <td colspan="6" style="text-align:right;">Totals for <?= htmlspecialchars($selected_date); ?>:</td>
                                    <td><?= number_format($total_due,    2); ?></td>
                                    <td><?= number_format($total_paid,   2); ?></td>
                                    <td><?= number_format($total_change, 2); ?></td>
                                    <td colspan="3"></td>
                                </tr>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </section>

        </div>
    </main>
</div>

<?php include 'footer.php'; ?>
</body>
</html>
