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

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

/* ── Partners ── */
$stmt = $pdo->query("
    SELECT *
    FROM partner_shops
    ORDER BY id DESC
");
$partners = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ── Filter ── */
$filterPartner = $_GET["partner_id"] ?? "";
$filterType    = $_GET["type"]       ?? "";
$filterFrom    = $_GET["from"]       ?? "";
$filterTo      = $_GET["to"]         ?? "";

/* ── Transactions query ── */
$where  = [];
$params = [];

if ($filterPartner !== "") {
    $where[]  = "t.partner_id = ?";
    $params[] = (int)$filterPartner;
}
if ($filterType !== "") {
    $where[]  = "t.type = ?";
    $params[] = $filterType;
}
if ($filterFrom !== "") {
    $where[]  = "DATE(t.created_at) >= ?";
    $params[] = $filterFrom;
}
if ($filterTo !== "") {
    $where[]  = "DATE(t.created_at) <= ?";
    $params[] = $filterTo;
}

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

try {
    $txStmt = $pdo->prepare("
        SELECT
            t.*,
            p.shop_name,
            p.shop_code
        FROM partner_transactions t
        LEFT JOIN partner_shops p ON t.partner_id = p.id
        {$whereSQL}
        ORDER BY t.created_at DESC
        LIMIT 500
    ");
    $txStmt->execute($params);
    $transactions = $txStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    /* Table may not exist yet */
    $transactions = [];
}

/* ── Summary totals for filtered result ── */
$totalCredit = 0;
$totalDebit  = 0;
foreach ($transactions as $tx) {
    $type = strtolower($tx["type"] ?? "");
    if (in_array($type, ["credit", "top_up", "topup", "deposit", "add"])) {
        $totalCredit += (float)($tx["amount"] ?? 0);
    } else {
        $totalDebit += (float)($tx["amount"] ?? 0);
    }
}

/* Build partner lookup for filter label */
$partnerMap = [];
foreach ($partners as $p) {
    $partnerMap[$p["id"]] = $p;
}

/* Distinct transaction types for filter dropdown */
$txTypes = [];
try {
    $typeStmt = $pdo->query("SELECT DISTINCT type FROM partner_transactions ORDER BY type");
    $txTypes  = $typeStmt->fetchAll(PDO::FETCH_COLUMN);
} catch (Throwable $e) {}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Partner Shops</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: 1500px;
            margin: auto;
            display: flex;
            flex-direction: column;
            gap: 24px;
        }

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

        h1, h2 { margin-top: 0; color: #111827; }
        h2 { font-size: 20px; margin-bottom: 16px; }

        .top-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }

        /* ── 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-primary { background: #2563eb; color: white; }
        .btn-edit    { background: #16a34a; color: white; }
        .btn-gray    { background: #6b7280; color: white; }
        .btn-reset   { background: #f59e0b; color: white; margin-left: 4px; }
        .btn-reset:hover { background: #d97706; }
        .btn-filter  { background: #1f4e79; color: white; }
        .btn-clear   { background: #e5e7eb; color: #374151; }

        /* ── 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;
        }

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

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

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

        .summary-box .label {
            font-size: 12px;
            color: #64748b;
            font-weight: 600;
            margin-bottom: 4px;
        }

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

        .summary-box.green  { background: #f0fdf4; border-color: #86efac; }
        .summary-box.green .value { color: #16a34a; }
        .summary-box.red    { background: #fff1f2; border-color: #fca5a5; }
        .summary-box.red .value   { color: #dc2626; }

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

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

        th {
            background: #0f172a;
            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; }

        .credit-val  { color: #16a34a; font-weight: 700; }
        .debit-val   { color: #dc2626; font-weight: 700; }
        .status-active   { color: #16a34a; font-weight: 700; }
        .status-inactive { color: #dc2626; font-weight: 700; }

        .badge {
            display: inline-block;
            padding: 3px 9px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 700;
        }
        .badge-credit  { background: #dcfce7; color: #166534; }
        .badge-debit   { background: #fee2e2; color: #991b1b; }
        .badge-neutral { background: #e0e7ff; color: #3730a3; }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #94a3b8;
            font-style: italic;
        }

        .footer { margin-top: 4px; }

        /* Active filter notice */
        .filter-active-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;
        }

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

<div class="container">

    <!-- ══════════════════════════════
         CARD 1: Partner Shops List
    ══════════════════════════════ -->
    <div class="card">

        <div class="top-bar">
            <h1>Partner Shops</h1>
            <a class="btn btn-primary" href="partner_create.php">+ Create Partner Shop</a>
        </div>

        <?php if (isset($_GET['password_reset'])): ?>
            <div style="background:#dcfce7;color:#166534;padding:14px 18px;border-radius:10px;
                        margin-bottom:20px;border:1px solid #86efac;font-weight:600;">
                ✅ Password reset successfully. New password: <strong>123456</strong>
            </div>
        <?php endif; ?>

        <div class="table-wrapper">
            <table>
                <tr>
                    <th>ID</th>
                    <th>Shop Code</th>
                    <th>Shop Name</th>
                    <th>Owner</th>
                    <th>Phone</th>
                    <th>Email</th>
                    <th>Credit Balance</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>

                <?php foreach ($partners as $partner): ?>
                    <?php $pid = (int)$partner["id"]; ?>
                    <tr>
                        <td><?= $pid ?></td>
                        <td><?= htmlspecialchars($partner["shop_code"]) ?></td>
                        <td>
                            <!-- Clicking shop name scrolls to transactions filtered by this partner -->
                            <a href="?partner_id=<?= $pid ?>#transactions"
                               style="color:#2563eb;font-weight:600;text-decoration:none;">
                                <?= htmlspecialchars($partner["shop_name"]) ?>
                            </a>
                        </td>
                        <td><?= htmlspecialchars($partner["owner_name"] ?? "") ?></td>
                        <td><?= htmlspecialchars($partner["phone"]      ?? "") ?></td>
                        <td><?= htmlspecialchars($partner["email"]      ?? "") ?></td>
                        <td class="credit-val"><?= number_format((float)$partner["credit_balance"], 2) ?></td>
                        <td>
                            <span class="status-<?= htmlspecialchars($partner["status"]) ?>">
                                <?= ucfirst(htmlspecialchars($partner["status"])) ?>
                            </span>
                        </td>
                        <td>
                            <a class="btn btn-edit"
                               href="edit_partner.php?id=<?= $pid ?>">Edit</a>

                            <a class="btn btn-reset"
                               href="reset_partner_password.php?id=<?= $pid ?>"
                               onclick="return confirm('Reset password for <?= htmlspecialchars(addslashes($partner['shop_name'])) ?>?\n\nNew password will be: 123456');">
                                Reset Password
                            </a>

                            <!-- Quick link to view only this partner's transactions -->
                            <a class="btn btn-primary"
                               href="?partner_id=<?= $pid ?>#transactions"
                               style="margin-left:4px;font-size:12px;">
                                Transactions
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </table>
        </div>

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

    </div><!-- /card 1 -->


    <!-- ══════════════════════════════
         CARD 2: Transactions
    ══════════════════════════════ -->
    <div class="card" id="transactions">

        <h2>📋 Partner Transactions</h2>

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

                <div class="filter-group">
                    <label>Partner Shop</label>
                    <select name="partner_id">
                        <option value="">— All Partners —</option>
                        <?php foreach ($partners as $p): ?>
                            <option value="<?= (int)$p["id"] ?>"
                                <?= ($filterPartner == $p["id"]) ? "selected" : "" ?>>
                                <?= htmlspecialchars($p["shop_name"]) ?>
                                (<?= htmlspecialchars($p["shop_code"]) ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="filter-group">
                    <label>Transaction Type</label>
                    <select name="type">
                        <option value="">— All Types —</option>
                        <?php foreach ($txTypes as $t): ?>
                            <option value="<?= htmlspecialchars($t) ?>"
                                <?= ($filterType === $t) ? "selected" : "" ?>>
                                <?= htmlspecialchars(ucfirst($t)) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </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">Clear</a>
                </div>

            </div>
        </form>

        <!-- Active filter notice -->
        <?php if ($filterPartner || $filterType || $filterFrom || $filterTo): ?>
            <div class="filter-active-notice">
                🔎 Filtered:
                <?php if ($filterPartner && isset($partnerMap[$filterPartner])): ?>
                    <strong><?= htmlspecialchars($partnerMap[$filterPartner]["shop_name"]) ?></strong>
                <?php endif; ?>
                <?php if ($filterType): ?>
                    | Type: <strong><?= htmlspecialchars(ucfirst($filterType)) ?></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" 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 green">
                <div class="label">Total Credit / Top-up</div>
                <div class="value"><?= number_format($totalCredit, 2) ?></div>
            </div>
            <div class="summary-box red">
                <div class="label">Total Debit / Spend</div>
                <div class="value"><?= number_format($totalDebit, 2) ?></div>
            </div>
            <div class="summary-box">
                <div class="label">Net</div>
                <div class="value"><?= number_format($totalCredit - $totalDebit, 2) ?></div>
            </div>
        </div>

        <!-- Transactions table -->
        <div class="table-wrapper">
            <table>
                <tr>
                    <th>ID</th>
                    <th>Date / Time</th>
                    <th>Shop</th>
                    <th>Type</th>
                    <th>Amount</th>
                    <th>Balance After</th>
                    <th>Reference</th>
                    <th>Note</th>
                </tr>

                <?php if (empty($transactions)): ?>
                    <tr>
                        <td colspan="8" class="no-data">
                            No transactions found<?= ($filterPartner || $filterType || $filterFrom || $filterTo) ? " for the selected filter" : "" ?>.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($transactions as $tx): ?>
                        <?php
                        $type      = strtolower($tx["type"] ?? "");
                        $isCredit  = in_array($type, ["credit","top_up","topup","deposit","add"]);
                        $badgeClass = $isCredit ? "badge-credit" : (in_array($type, ["debit","spend","use","payment","charge"]) ? "badge-debit" : "badge-neutral");
                        ?>
                        <tr>
                            <td><?= (int)$tx["id"] ?></td>
                            <td style="white-space:nowrap;">
                                <?= htmlspecialchars($tx["created_at"] ?? "") ?>
                            </td>
                            <td>
                                <strong><?= htmlspecialchars($tx["shop_name"] ?? "") ?></strong><br>
                                <small style="color:#64748b;"><?= htmlspecialchars($tx["shop_code"] ?? "") ?></small>
                            </td>
                            <td>
                                <span class="badge <?= $badgeClass ?>">
                                    <?= htmlspecialchars(ucfirst($tx["type"] ?? "")) ?>
                                </span>
                            </td>
                            <td class="<?= $isCredit ? 'credit-val' : 'debit-val' ?>">
                                <?= $isCredit ? "+" : "-" ?>
                                <?= number_format((float)($tx["amount"] ?? 0), 2) ?>
                            </td>
                            <td><?= number_format((float)($tx["balance_after"] ?? 0), 2) ?></td>
                            <td style="font-size:12px;color:#475569;">
                                <?= htmlspecialchars($tx["reference"] ?? $tx["ref"] ?? $tx["transaction_ref"] ?? "—") ?>
                            </td>
                            <td style="font-size:12px;color:#475569;max-width:200px;word-break:break-word;">
                                <?= htmlspecialchars($tx["note"] ?? $tx["remark"] ?? $tx["description"] ?? "") ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </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 results.
            </p>
        <?php endif; ?>

    </div><!-- /card 2 -->

</div><!-- /container -->

<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) {
            /* When from-date changes, set minDate on to-date */
            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>