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

require_once '../config/database.php';

$companyId   = (int)$_SESSION["company_id"];
$companyName = $_SESSION["company_name"] ?? "";

/* ── Company credit balance ── */
$co = $pdo->prepare("SELECT credit_balance, created_at FROM companies WHERE id=?");
$co->execute([$companyId]);
$co = $co->fetch(PDO::FETCH_ASSOC);
$balance = (float)($co["credit_balance"] ?? 0);

/* ── Transfer history from Seven Digital ── */
$transfers = $pdo->prepare("
    SELECT t.*, u.name AS transferred_by_name
    FROM company_credit_transfers t
    JOIN users u ON u.id = t.transferred_by
    WHERE t.company_id = ?
    ORDER BY t.created_at DESC
    LIMIT 100
");
$transfers->execute([$companyId]);
$transfers = $transfers->fetchAll(PDO::FETCH_ASSOC);

/* ── Monthly totals for chart data ── */
$monthly = $pdo->prepare("
    SELECT
        DATE_FORMAT(created_at, '%Y-%m') AS ym,
        DATE_FORMAT(created_at, '%b %Y') AS label,
        SUM(amount) AS total
    FROM company_credit_transfers
    WHERE company_id = ?
    GROUP BY ym, label
    ORDER BY ym DESC
    LIMIT 12
");
$monthly->execute([$companyId]);
$monthly = array_reverse($monthly->fetchAll(PDO::FETCH_ASSOC));

/* ── Stats ── */
$totalReceived = array_sum(array_column($transfers, "amount"));
$thisMonth     = 0;
$currentYM     = date("Y-m");
foreach ($transfers as $t) {
    if (str_starts_with($t["created_at"], date("Y-m"))) {
        $thisMonth += (float)$t["amount"];
    }
}
$totalTransfers = count($transfers);
?>
<!DOCTYPE html>
<html lang="lo">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Credit Balance — <?= htmlspecialchars($companyName) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
    --p:#0f766e;--s:#fff;--bg:#f0f4f8;--b:#e2e8f0;--t:#0f172a;--m:#64748b;
    --g:#16a34a;--gl:#dcfce7;--r:#dc2626;--rl:#fee2e2;--a:#d97706;--al:#fef3c7;
    --bl:#2563eb;--bll:#dbeafe;--rad:14px;--sh:0 2px 14px rgba(15,23,42,.09)
}
body{font-family:"Noto Sans Lao","Inter",Arial,sans-serif;background:var(--bg);color:var(--t);min-height:100vh}

/* top bar */
.top-bar{background:var(--s);border-bottom:1px solid var(--b);padding:12px 32px;display:flex;align-items:center;gap:14px;position:sticky;top:0;z-index:100;box-shadow:0 1px 6px rgba(15,23,42,.06)}
.back{display:inline-flex;align-items:center;gap:6px;color:var(--m);text-decoration:none;font-size:13px;font-weight:600;padding:6px 12px;border-radius:8px;border:1.5px solid var(--b);transition:all .15s}
.back:hover{border-color:var(--p);color:var(--p)}
h1{font-size:17px;font-weight:800;flex:1}

.pb{padding:24px 32px;max-width:1100px;margin:auto}

/* balance hero */
.balance-hero{background:linear-gradient(135deg,#042f2e 0%,#084740 50%,#0f766e 100%);border-radius:20px;padding:32px 36px;color:#fff;margin-bottom:24px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:20px;box-shadow:0 8px 32px rgba(4,47,46,.22);position:relative;overflow:hidden}
.balance-hero::before{content:"";position:absolute;width:300px;height:300px;right:-60px;top:-80px;border-radius:50%;background:rgba(255,255,255,.06)}
.balance-hero::after{content:"";position:absolute;width:180px;height:180px;right:140px;bottom:-70px;border-radius:50%;background:rgba(255,255,255,.05)}
.bh-left h2{font-size:14px;font-weight:700;opacity:.75;text-transform:uppercase;letter-spacing:.6px;margin-bottom:8px}
.bh-left .amount{font-size:42px;font-weight:800;line-height:1;letter-spacing:-1px}
.bh-left .sub{font-size:13px;opacity:.7;margin-top:8px}
.bh-right{position:relative;z-index:1;display:flex;flex-direction:column;gap:10px;align-items:flex-end}
.bh-badge{background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);border-radius:12px;padding:12px 18px;text-align:center;min-width:130px}
.bh-badge .bv{font-size:20px;font-weight:800;display:block}
.bh-badge .bl{font-size:11px;opacity:.75;margin-top:2px}

/* stat row */
.stat-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:14px;margin-bottom:24px}
.stat-card{background:var(--s);border-radius:var(--rad);padding:18px 20px;box-shadow:var(--sh);border:1px solid var(--b);display:flex;align-items:center;gap:14px}
.si{width:46px;height:46px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0}
.si-g{background:var(--gl)} .si-b{background:var(--bll)} .si-a{background:var(--al)} .si-t{background:#ccfbf1}
.stat-val{font-size:22px;font-weight:800;color:var(--t);line-height:1}
.stat-lbl{font-size:11px;color:var(--m);font-weight:600;margin-top:3px;text-transform:uppercase;letter-spacing:.4px}

/* chart */
.chart-card{background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);border:1px solid var(--b);padding:20px 24px;margin-bottom:24px}
.chart-title{font-size:14px;font-weight:800;margin-bottom:16px;color:var(--t)}
.bar-chart{display:flex;align-items:flex-end;gap:8px;height:120px;padding-bottom:24px;position:relative;border-bottom:1.5px solid var(--b)}
.bar-wrap{flex:1;display:flex;flex-direction:column;align-items:center;gap:4px;min-width:0}
.bar{width:100%;border-radius:6px 6px 0 0;background:linear-gradient(180deg,#0f766e,#084740);min-height:4px;transition:opacity .15s;position:relative}
.bar:hover{opacity:.8}
.bar-tip{position:absolute;bottom:calc(100% + 4px);left:50%;transform:translateX(-50%);background:#0f172a;color:#fff;font-size:10px;font-weight:700;padding:3px 7px;border-radius:5px;white-space:nowrap;opacity:0;pointer-events:none;transition:opacity .15s}
.bar:hover .bar-tip{opacity:1}
.bar-lbl{font-size:9px;color:var(--m);text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;width:100%}
.no-chart{text-align:center;padding:40px;color:var(--m);font-size:13px}

/* search */
.toolbar{display:flex;align-items:center;gap:10px;margin-bottom:16px;flex-wrap:wrap}
.search-wrap{position:relative;flex:1;min-width:200px}
.search-wrap input{width:100%;padding:9px 13px 9px 36px;border:1.5px solid var(--b);border-radius:9px;font-size:13px;font-family:inherit;outline:none;background:var(--s);transition:border-color .15s}
.search-wrap input:focus{border-color:var(--p)}
.search-wrap .si-icon{position:absolute;left:11px;top:50%;transform:translateY(-50%);font-size:14px}
.btn{display:inline-flex;align-items:center;gap:6px;padding:9px 18px;border-radius:9px;font-size:13px;font-weight:700;font-family:inherit;cursor:pointer;border:none;transition:all .15s}
.btn-p{background:linear-gradient(135deg,#084740,#0f766e);color:#fff}.btn-p:hover{opacity:.9}

/* table */
.tc{background:var(--s);border-radius:var(--rad);box-shadow:var(--sh);border:1px solid var(--b);overflow:hidden}
.ch{padding:14px 20px;border-bottom:1px solid var(--b);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px}
.ch h2{font-size:15px;font-weight:800}
table{width:100%;border-collapse:collapse}
thead th{background:#f8fafc;padding:10px 16px;text-align:left;font-size:11px;font-weight:700;color:var(--m);text-transform:uppercase;letter-spacing:.5px;border-bottom:1px solid var(--b);white-space:nowrap}
tbody tr{border-bottom:1px solid var(--b);transition:background .1s}
tbody tr:last-child{border-bottom:none}
tbody tr:hover{background:#f8fafc}
td{padding:12px 16px;font-size:13px;vertical-align:middle}
.amount-cell{font-weight:800;color:var(--g);font-size:15px}
.note-cell{color:var(--m);font-size:12px;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.tx-id{font-size:11px;color:var(--m);margin-top:2px}

/* running balance column */
.run-bal{font-size:12px;color:var(--p);font-weight:700}

.empty{text-align:center;padding:60px;color:var(--m)}
.empty .icon{font-size:44px;margin-bottom:12px}
.empty p{font-size:13px}

/* pagination */
.pager{display:flex;align-items:center;justify-content:space-between;padding:14px 20px;border-top:1px solid var(--b);font-size:13px;color:var(--m)}
.pager-btns{display:flex;gap:6px}
.pbtn{padding:6px 14px;border-radius:7px;border:1.5px solid var(--b);background:var(--s);color:var(--m);font-size:12px;font-weight:700;cursor:pointer;font-family:inherit;text-decoration:none;transition:all .15s}
.pbtn:hover{border-color:var(--p);color:var(--p)}
.pbtn.active{background:var(--p);border-color:var(--p);color:#fff}

@media(max-width:700px){.pb{padding:16px}.top-bar{padding:10px 16px}.bh-left .amount{font-size:30px}.bar-lbl{font-size:8px}}
</style>
</head>
<body>

<div class="top-bar">
    <a class="back" href="dashboard.php">← Dashboard</a>
    <h1>💰 Credit Balance</h1>
</div>

<div class="pb">

    <!-- Balance hero -->
    <div class="balance-hero">
        <div class="bh-left">
            <h2>Available Credit Balance</h2>
            <div class="amount">₭ <?= number_format($balance, 0) ?></div>
            <div class="sub">
                <?= htmlspecialchars($companyName) ?> · Funded by Seven Digital Admin
            </div>
        </div>
        <div class="bh-right">
            <div class="bh-badge">
                <span class="bv"><?= $totalTransfers ?></span>
                <span class="bl">Total transfers</span>
            </div>
            <div class="bh-badge">
                <span class="bv">₭ <?= number_format($thisMonth, 0) ?></span>
                <span class="bl">This month</span>
            </div>
        </div>
    </div>

    <!-- Stats -->
    <div class="stat-row">
        <div class="stat-card">
            <div class="si si-g">💰</div>
            <div>
                <div class="stat-val">₭ <?= number_format($balance, 0) ?></div>
                <div class="stat-lbl">Current Balance</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="si si-b">📥</div>
            <div>
                <div class="stat-val">₭ <?= number_format($totalReceived, 0) ?></div>
                <div class="stat-lbl">Total Received</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="si si-a">📅</div>
            <div>
                <div class="stat-val">₭ <?= number_format($thisMonth, 0) ?></div>
                <div class="stat-lbl"><?= date("M Y") ?></div>
            </div>
        </div>
        <div class="stat-card">
            <div class="si si-t">🔢</div>
            <div>
                <div class="stat-val"><?= $totalTransfers ?></div>
                <div class="stat-lbl">Transfers</div>
            </div>
        </div>
    </div>

    <!-- Bar chart -->
    <?php if (!empty($monthly)): ?>
    <div class="chart-card">
        <div class="chart-title">📈 Monthly Credit Received (last <?= count($monthly) ?> months)</div>
        <?php
        $maxVal = max(array_column($monthly, "total")) ?: 1;
        ?>
        <div class="bar-chart">
            <?php foreach ($monthly as $m): ?>
            <?php $pct = max(4, round(((float)$m["total"] / $maxVal) * 100)); ?>
            <div class="bar-wrap">
                <div class="bar" style="height:<?= $pct ?>%">
                    <div class="bar-tip">₭ <?= number_format((float)$m["total"], 0) ?></div>
                </div>
                <div class="bar-lbl"><?= htmlspecialchars($m["label"]) ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Transfer history -->
    <div class="tc">
        <div class="ch">
            <h2>📋 Transfer History</h2>
            <span style="font-size:12px;color:var(--m)"><?= $totalTransfers ?> record<?= $totalTransfers !== 1 ? "s" : "" ?></span>
        </div>

        <?php if (empty($transfers)): ?>
        <div class="empty">
            <div class="icon">📭</div>
            <p>No credit transfers yet.<br>Contact Seven Digital admin to fund your account.</p>
        </div>
        <?php else: ?>

        <!-- Search client-side -->
        <div style="padding:14px 16px;border-bottom:1px solid var(--b)">
            <div class="search-wrap" style="max-width:360px">
                <span class="si-icon">🔍</span>
                <input type="text" id="searchInput" placeholder="Search by amount, note, or admin name…" oninput="filterTable()">
            </div>
        </div>

        <table id="txTable">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Date & Time</th>
                    <th>Amount</th>
                    <th>Transferred By</th>
                    <th>Note</th>
                    <th>Running Balance</th>
                </tr>
            </thead>
            <tbody>
            <?php
            /* Calculate running balance from oldest to newest */
            $sorted = array_reverse($transfers);
            $running = 0;
            $runningMap = [];
            foreach ($sorted as $t) {
                $running += (float)$t["amount"];
                $runningMap[$t["id"]] = $running;
            }
            $num = count($transfers);
            foreach ($transfers as $i => $t):
            ?>
            <tr class="tx-row">
                <td style="color:var(--m);font-size:12px"><?= $num - $i ?></td>
                <td>
                    <div style="font-weight:600"><?= date("d M Y", strtotime($t["created_at"])) ?></div>
                    <div class="tx-id"><?= date("H:i", strtotime($t["created_at"])) ?></div>
                </td>
                <td>
                    <div class="amount-cell">+ ₭ <?= number_format((float)$t["amount"], 0) ?></div>
                </td>
                <td style="font-weight:600"><?= htmlspecialchars($t["transferred_by_name"]) ?></td>
                <td class="note-cell" title="<?= htmlspecialchars($t["note"] ?? "") ?>">
                    <?= htmlspecialchars($t["note"] ?: "—") ?>
                </td>
                <td>
                    <div class="run-bal">₭ <?= number_format($runningMap[$t["id"]], 0) ?></div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <div class="pager" id="pagerInfo">
            <span id="showingText"></span>
            <div class="pager-btns" id="pagerBtns"></div>
        </div>

        <?php endif; ?>
    </div>

</div>

<script>
/* ── Client-side search + pagination ── */
const rows      = Array.from(document.querySelectorAll('.tx-row'));
const perPage   = 20;
let filtered    = rows;
let currentPage = 1;

function filterTable() {
    const q = document.getElementById('searchInput').value.toLowerCase();
    filtered = rows.filter(r => r.textContent.toLowerCase().includes(q));
    currentPage = 1;
    render();
}

function render() {
    const total = filtered.length;
    const pages = Math.ceil(total / perPage) || 1;
    const start = (currentPage - 1) * perPage;
    const end   = Math.min(start + perPage, total);

    rows.forEach(r => r.style.display = 'none');
    filtered.slice(start, end).forEach(r => r.style.display = '');

    document.getElementById('showingText').textContent =
        total === 0 ? 'No results' :
        `Showing ${start + 1}–${end} of ${total}`;

    const btns = document.getElementById('pagerBtns');
    btns.innerHTML = '';
    for (let p = 1; p <= pages; p++) {
        const a = document.createElement('a');
        a.href = '#';
        a.className = 'pbtn' + (p === currentPage ? ' active' : '');
        a.textContent = p;
        a.addEventListener('click', e => { e.preventDefault(); currentPage = p; render(); });
        btns.appendChild(a);
    }
}

render();
</script>

</body>
</html>