<?php
session_start();
require_once '../config/database.php';

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

/* ── Filters ── */
$filterType = $_GET["type"] ?? "";
$filterFrom = $_GET["from"] ?? "";
$filterTo   = $_GET["to"]   ?? "";
$filterCode = trim($_GET["code"] ?? "");

$where  = [];
$params = [];

if ($filterType !== "") {
    $where[]  = "transaction_type = ?";
    $params[] = $filterType;
}
if ($filterFrom !== "") {
    $where[]  = "DATE(created_at) >= ?";
    $params[] = $filterFrom;
}
if ($filterTo !== "") {
    $where[]  = "DATE(created_at) <= ?";
    $params[] = $filterTo;
}
if ($filterCode !== "") {
    $where[]  = "transaction_code LIKE ?";
    $params[] = "%" . $filterCode . "%";
}

$whereSQL = $where ? "WHERE " . implode(" AND ", $where) : "";

$transactions = $pdo->prepare("
    SELECT *
    FROM transactions
    {$whereSQL}
    ORDER BY id DESC
    LIMIT 500
");
$transactions->execute($params);
$transactions = $transactions->fetchAll(PDO::FETCH_ASSOC);

/* ── Summary ── */
$totalAmount   = 0;
$countByType   = [];
$amountByType  = [];
foreach ($transactions as $tx) {
    $t = $tx["transaction_type"] ?? "other";
    $totalAmount        += (float)$tx["amount"];
    $countByType[$t]     = ($countByType[$t]  ?? 0) + 1;
    $amountByType[$t]    = ($amountByType[$t] ?? 0) + (float)$tx["amount"];
}

/* All distinct types for the dropdown */
$allTypes = $pdo->query("SELECT DISTINCT transaction_type FROM transactions ORDER BY transaction_type")
               ->fetchAll(PDO::FETCH_COLUMN);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Transaction History</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        * { box-sizing: border-box; }

        body {
            font-family: Arial, sans-serif;
            background: #f4f6f8;
            margin: 0;
            padding: 24px;
        }

        .container { max-width: 1400px; margin: auto; }

        .card {
            background: white;
            border-radius: 14px;
            padding: 24px;
            box-shadow: 0 4px 14px rgba(0,0,0,0.08);
        }

        h1 { margin-top: 0; color: #111827; }

        .subtitle { color: #6b7280; margin-bottom: 20px; font-size: 14px; }

        /* ── Filter bar ── */
        .filter-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: flex-end;
            background: #f8faff;
            border: 1px solid #dbe3ea;
            border-radius: 10px;
            padding: 14px 18px;
            margin-bottom: 18px;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 4px;
            min-width: 160px;
        }

        .filter-group label {
            font-size: 12px;
            font-weight: 600;
            color: #475569;
        }

        .filter-group select,
        .filter-group input {
            padding: 8px 10px;
            border: 1px solid #cbd5e1;
            border-radius: 7px;
            font-size: 13px;
            background: #fff;
            font-family: inherit;
        }

        .filter-actions {
            display: flex;
            gap: 8px;
            align-items: flex-end;
            padding-bottom: 1px;
        }

        /* ── Summary ── */
        .summary-row {
            display: flex;
            gap: 12px;
            margin-bottom: 18px;
            flex-wrap: wrap;
        }

        .summary-box {
            flex: 1;
            min-width: 150px;
            background: #f0f5ff;
            border: 1px solid #c7d9f5;
            border-radius: 10px;
            padding: 12px 16px;
            text-align: center;
        }

        .summary-box .label {
            font-size: 11px;
            color: #64748b;
            font-weight: 700;
            margin-bottom: 4px;
            text-transform: uppercase;
            letter-spacing: .4px;
        }

        .summary-box .value {
            font-size: 20px;
            font-weight: 800;
            color: #1f4e79;
        }

        .summary-box.blue  { background: #dbeafe; border-color: #93c5fd; }
        .summary-box.blue .value  { color: #1d4ed8; }
        .summary-box.green { background: #dcfce7; border-color: #86efac; }
        .summary-box.green .value { color: #166534; }
        .summary-box.red   { background: #fee2e2; border-color: #fca5a5; }
        .summary-box.red .value   { color: #991b1b; }

        /* ── Active filter notice ── */
        .filter-notice {
            background: #fffbeb;
            border: 1px solid #fcd34d;
            border-radius: 8px;
            padding: 8px 14px;
            font-size: 13px;
            color: #78350f;
            margin-bottom: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        /* ── Table ── */
        .table-wrapper {
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        table {
            width: 100%;
            min-width: 700px;
            border-collapse: collapse;
        }

        th {
            background: #111827;
            color: white;
            text-align: left;
            padding: 12px 14px;
            font-size: 13px;
            white-space: nowrap;
        }

        td {
            padding: 12px 14px;
            border-bottom: 1px solid #e5e7eb;
            font-size: 13px;
            vertical-align: middle;
        }

        tr:hover td { background: #f9fafb; }

        .amount { color: #2563eb; font-weight: 700; }

        /* Type badges — auto-colour from class name */
        .type-badge {
            padding: 5px 11px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: 700;
            display: inline-block;
            white-space: nowrap;
        }

        .credit_transfer { background: #dbeafe; color: #1d4ed8; }
        .cash_to_credit  { background: #dcfce7; color: #166534; }
        .credit_to_cash  { background: #fee2e2; color: #991b1b; }

        /* Fallback for unknown types */
        .type-default    { background: #e0e7ff; color: #3730a3; }

        /* ── Buttons ── */
        .btn {
            padding: 9px 15px;
            border-radius: 8px;
            text-decoration: none;
            display: inline-block;
            font-size: 13px;
            border: none;
            cursor: pointer;
            font-family: inherit;
        }
        .btn-gray   { background: #6b7280; color: white; }
        .btn-filter { background: #1f4e79; color: white; }
        .btn-clear  { background: #e5e7eb; color: #374151; }

        .footer { margin-top: 20px; }

        .empty {
            background: #f9fafb;
            padding: 30px;
            border-radius: 10px;
            color: #6b7280;
            text-align: center;
            font-style: italic;
        }

        @media (max-width: 700px) {
            .filter-bar { flex-direction: column; }
            .summary-row { flex-direction: column; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="card">

        <h1>Transaction History</h1>
        <p class="subtitle">Seven Digital internal credit movement history — cash↔credit transfers.</p>

        <!-- ── Filter bar ── -->
        <form method="GET" action="">
            <div class="filter-bar">

                <div class="filter-group">
                    <label>Transaction Type</label>
                    <select name="type">
                        <option value="">— All Types —</option>
                        <?php foreach ($allTypes as $t): ?>
                            <option value="<?= htmlspecialchars($t) ?>"
                                <?= ($filterType === $t) ? "selected" : "" ?>>
                                <?= htmlspecialchars(ucwords(str_replace("_", " ", $t))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-group">
                    <label>Transaction Code</label>
                    <input type="text" name="code"
                           placeholder="Search code…"
                           value="<?= htmlspecialchars($filterCode) ?>">
                </div>

                <div class="filter-group">
                    <label>From Date</label>
                    <input type="text" name="from" id="from-date"
                           placeholder="Select date…"
                           value="<?= htmlspecialchars($filterFrom) ?>" readonly>
                </div>

                <div class="filter-group">
                    <label>To Date</label>
                    <input type="text" name="to" id="to-date"
                           placeholder="Select date…"
                           value="<?= htmlspecialchars($filterTo) ?>" readonly>
                </div>

                <div class="filter-actions">
                    <button class="btn btn-filter" type="submit">🔍 Filter</button>
                    <a class="btn btn-clear" href="transactions.php">Clear</a>
                </div>

            </div>
        </form>

        <!-- Active filter notice -->
        <?php if ($filterType || $filterFrom || $filterTo || $filterCode): ?>
            <div class="filter-notice">
                🔎 Filtered:
                <?php if ($filterType): ?>
                    Type: <strong><?= htmlspecialchars(ucwords(str_replace("_"," ",$filterType))) ?></strong>
                <?php endif; ?>
                <?php if ($filterCode): ?>
                    | Code: <strong><?= htmlspecialchars($filterCode) ?></strong>
                <?php endif; ?>
                <?php if ($filterFrom || $filterTo): ?>
                    | Date: <strong><?= htmlspecialchars($filterFrom ?: "—") ?></strong>
                    to <strong><?= htmlspecialchars($filterTo ?: "—") ?></strong>
                <?php endif; ?>
                &nbsp;·&nbsp; <?= count($transactions) ?> records
                <a href="transactions.php"
                   style="margin-left:auto;color:#92400e;font-weight:700;text-decoration:none;">
                    ✕ Clear
                </a>
            </div>
        <?php endif; ?>

        <!-- ── Summary boxes ── -->
        <div class="summary-row">
            <div class="summary-box">
                <div class="label">Total Records</div>
                <div class="value"><?= number_format(count($transactions)) ?></div>
            </div>
            <div class="summary-box blue">
                <div class="label">Credit Transfer</div>
                <div class="value"><?= number_format($amountByType["credit_transfer"] ?? 0, 2) ?></div>
            </div>
            <div class="summary-box green">
                <div class="label">Cash → Credit</div>
                <div class="value"><?= number_format($amountByType["cash_to_credit"] ?? 0, 2) ?></div>
            </div>
            <div class="summary-box red">
                <div class="label">Credit → Cash</div>
                <div class="value"><?= number_format($amountByType["credit_to_cash"] ?? 0, 2) ?></div>
            </div>
            <div class="summary-box">
                <div class="label">Total Amount</div>
                <div class="value"><?= number_format($totalAmount, 2) ?></div>
            </div>
        </div>

        <!-- ── Table ── -->
        <?php if (empty($transactions)): ?>
            <div class="empty">No transactions found for the selected filter.</div>
        <?php else: ?>
            <div class="table-wrapper">
                <table>
                    <tr>
                        <th>#</th>
                        <th>Transaction Code</th>
                        <th>Type</th>
                        <th>Amount</th>
                        <th>Date / Time</th>
                    </tr>

                    <?php foreach ($transactions as $i => $row): ?>
                        <?php
                        $typeClass = preg_match('/^[a-z_]+$/', $row["transaction_type"] ?? "")
                                   ? htmlspecialchars($row["transaction_type"])
                                   : "type-default";
                        ?>
                        <tr>
                            <td style="color:#94a3b8;font-size:12px;"><?= $i + 1 ?></td>
                            <td style="font-family:monospace;font-size:13px;">
                                <?= htmlspecialchars($row["transaction_code"]) ?>
                            </td>
                            <td>
                                <span class="type-badge <?= $typeClass ?>">
                                    <?= htmlspecialchars(ucwords(str_replace("_", " ", $row["transaction_type"]))) ?>
                                </span>
                            </td>
                            <td class="amount">
                                <?= number_format((float)$row["amount"], 2) ?>
                            </td>
                            <td style="white-space:nowrap;color:#475569;">
                                <?= htmlspecialchars($row["created_at"]) ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>

            <?php if (count($transactions) >= 500): ?>
                <p style="color:#f59e0b;font-size:13px;margin-top:10px;">
                    ⚠️ Showing first 500 records. Use filters to narrow your results.
                </p>
            <?php endif; ?>
        <?php endif; ?>

        <div class="footer">
            <a class="btn btn-gray" href="dashboard.php">Back to Dashboard</a>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
    const fromPicker = flatpickr("#from-date", {
        dateFormat: "Y-m-d",
        allowInput: false,
        onChange: function(selectedDates, dateStr) {
            toPicker.set("minDate", dateStr);
        }
    });

    const toPicker = flatpickr("#to-date", {
        dateFormat: "Y-m-d",
        allowInput: false,
        onChange: function(selectedDates, dateStr) {
            fromPicker.set("maxDate", dateStr);
        }
    });
</script>
</body>
</html>