<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

include 'layouts/dbconn.php';

$role        = $_SESSION['role_name'];
$business_id = (int)$_SESSION['business_id'];
$user_id     = (int)$_SESSION['user_id'];
$today       = date('Y-m-d');
$is_admin    = in_array($role, ['super_admin', 'manager']);
$is_agent    = ($role === 'agent');
$is_auditor  = ($role === 'auditor');

/* ═══════════════════════════════════════════════════════════════════
   SHARED: unresolved alerts
══════════════════════════════════════════════════════════════════════ */
$alerts_sql = "SELECT a.*, l.location_name
               FROM   alerts a
               LEFT   JOIN locations l ON l.id = a.location_id
               WHERE  a.business_id = ? AND a.is_resolved = 0
               ORDER  BY FIELD(a.severity,'critical','high','medium','low'), a.created_at DESC
               LIMIT  10";
$al_s = $conn->prepare($alerts_sql); $al_s->bind_param("i", $business_id);
$al_s->execute(); $alerts_list = $al_s->get_result()->fetch_all(MYSQLI_ASSOC);
$alert_count = count($alerts_list);

/* ═══════════════════════════════════════════════════════════════════
   ADMIN / MANAGER METRICS
══════════════════════════════════════════════════════════════════════ */
if ($is_admin) {

    /* KPI 1 – Active locations */
    $r = $conn->query("SELECT COUNT(*) c FROM locations WHERE business_id=$business_id AND is_active=1");
    $total_locations = (int)$r->fetch_assoc()['c'];

    /* KPI 2 – Sessions today */
    $r = $conn->query("SELECT
            COUNT(*) total,
            SUM(status='open') open_count,
            SUM(status='closed') closed_count,
            SUM(status='approved') approved_count
        FROM daily_sessions ds
        JOIN locations l ON l.id=ds.location_id
        WHERE l.business_id=$business_id AND ds.business_date='$today'");
    $sessions = $r->fetch_assoc() ?: ['total'=>0,'open_count'=>0,'closed_count'=>0,'approved_count'=>0];

    /* KPI 3 – Total float across all accounts */
    $r = $conn->query("SELECT
            SUM(fa.current_balance) total_float,
            SUM(CASE WHEN fa.account_type='MPESA'  THEN fa.current_balance ELSE 0 END) mpesa,
            SUM(CASE WHEN fa.account_type='EQUITY' THEN fa.current_balance ELSE 0 END) equity,
            SUM(CASE WHEN fa.account_type='KCB'    THEN fa.current_balance ELSE 0 END) kcb,
            SUM(CASE WHEN fa.account_type='COOP'   THEN fa.current_balance ELSE 0 END) coop,
            SUM(CASE WHEN fa.account_type='NCBA'   THEN fa.current_balance ELSE 0 END) ncba,
            SUM(CASE WHEN fa.account_type='ABSA'   THEN fa.current_balance ELSE 0 END) absa,
            SUM(CASE WHEN fa.account_type='DIM'    THEN fa.current_balance ELSE 0 END) dim
        FROM float_accounts fa
        JOIN locations l ON l.id=fa.location_id
        WHERE l.business_id=$business_id AND fa.is_active=1");
    $float_totals = $r->fetch_assoc() ?: [];

    /* KPI 4 – Today's volume & commission */
    $r = $conn->query("SELECT
            COUNT(*) txn_count,
            COALESCE(SUM(CASE WHEN mt.direction='cash_in'  THEN mt.amount ELSE 0 END),0) cash_in,
            COALESCE(SUM(CASE WHEN mt.direction='cash_out' THEN mt.amount ELSE 0 END),0) cash_out,
            COALESCE(SUM(mt.commission),0) commission
        FROM mpesa_transactions mt
        JOIN daily_sessions ds ON ds.id=mt.session_id
        JOIN locations l ON l.id=ds.location_id
        WHERE l.business_id=$business_id AND ds.business_date='$today' AND mt.is_voided=0");
    $today_mpesa = $r->fetch_assoc() ?: ['txn_count'=>0,'cash_in'=>0,'cash_out'=>0,'commission'=>0];

    $r = $conn->query("SELECT
            COALESCE(SUM(abt.amount),0) ab_volume,
            COALESCE(SUM(abt.commission),0) ab_commission
        FROM agency_banking_transactions abt
        JOIN daily_sessions ds ON ds.id=abt.session_id
        JOIN locations l ON l.id=ds.location_id
        WHERE l.business_id=$business_id AND ds.business_date='$today' AND abt.is_voided=0");
    $today_agency = $r->fetch_assoc() ?: ['ab_volume'=>0,'ab_commission'=>0];

    $today_commission = $today_mpesa['commission'] + $today_agency['ab_commission'];

    /* KPI 5 – Short / excess today */
    $r = $conn->query("SELECT
            COALESCE(SUM(dr.short_amount),0) total_short,
            COALESCE(SUM(dr.excess_amount),0) total_excess,
            SUM(dr.status='pending') pending_recon
        FROM daily_reconciliation dr
        JOIN locations l ON l.id=dr.location_id
        WHERE l.business_id=$business_id AND dr.business_date='$today'");
    $recon_today = $r->fetch_assoc() ?: ['total_short'=>0,'total_excess'=>0,'pending_recon'=>0];

    /* Float snapshot per location */
    $float_snap_sql = "SELECT l.location_name, fa.account_type, fa.current_balance, fa.alert_threshold,
            CASE
                WHEN fa.current_balance <= 0 THEN 'CRITICAL'
                WHEN fa.alert_threshold IS NOT NULL AND fa.current_balance < fa.alert_threshold THEN 'LOW'
                WHEN fa.alert_threshold IS NOT NULL AND fa.current_balance < fa.alert_threshold*1.5 THEN 'WATCH'
                ELSE 'OK'
            END status
        FROM float_accounts fa
        JOIN locations l ON l.id=fa.location_id
        WHERE l.business_id=$business_id AND fa.is_active=1
        ORDER BY l.location_name, fa.account_type";
    $float_snap = $conn->query($float_snap_sql)->fetch_all(MYSQLI_ASSOC);

    /* Recent reconciliations */
    $recon_sql = "SELECT dr.business_date, l.location_name, u.full_name reconciled_by,
            dr.expected_balance, dr.actual_balance, dr.short_amount, dr.excess_amount, dr.status
        FROM daily_reconciliation dr
        JOIN locations l ON l.id=dr.location_id
        JOIN users u ON u.id=dr.reconciled_by
        WHERE l.business_id=$business_id
        ORDER BY dr.business_date DESC, dr.created_at DESC
        LIMIT 8";
    $recent_recon = $conn->query($recon_sql)->fetch_all(MYSQLI_ASSOC);

    /* Branch commission last 7 days */
    $branch_comm_sql = "SELECT l.location_name,
            COALESCE(SUM(c.commission_amt),0) total_comm
        FROM commissions c
        JOIN daily_sessions ds ON ds.id=c.session_id
        JOIN locations l ON l.id=ds.location_id
        WHERE l.business_id=$business_id AND ds.business_date >= DATE_SUB('$today', INTERVAL 7 DAY)
        GROUP BY l.id, l.location_name
        ORDER BY total_comm DESC";
    $branch_comms = $conn->query($branch_comm_sql)->fetch_all(MYSQLI_ASSOC);
}

/* ═══════════════════════════════════════════════════════════════════
   AGENT METRICS
══════════════════════════════════════════════════════════════════════ */
if ($is_agent) {
    $location_id = (int)$_SESSION['primary_location_id'];

    /* Today's session */
    $sess_sql = "SELECT * FROM daily_sessions WHERE location_id=? AND business_date=? LIMIT 1";
    $s = $conn->prepare($sess_sql); $s->bind_param("is", $location_id, $today);
    $s->execute(); $my_session = $s->get_result()->fetch_assoc();

    /* Float balances at this location */
    $float_sql = "SELECT account_type, current_balance, alert_threshold,
            CASE
                WHEN current_balance <= 0 THEN 'CRITICAL'
                WHEN alert_threshold IS NOT NULL AND current_balance < alert_threshold THEN 'LOW'
                WHEN alert_threshold IS NOT NULL AND current_balance < alert_threshold*1.5 THEN 'WATCH'
                ELSE 'OK'
            END status
        FROM float_accounts WHERE location_id=? AND is_active=1 ORDER BY account_type";
    $fs = $conn->prepare($float_sql); $fs->bind_param("i", $location_id);
    $fs->execute(); $my_floats = $fs->get_result()->fetch_all(MYSQLI_ASSOC);

    if ($my_session) {
        $sid = (int)$my_session['id'];

        /* Today's transactions */
        $txn_sql = "SELECT
                COUNT(*) txn_count,
                COALESCE(SUM(CASE WHEN direction='cash_in'  THEN amount ELSE 0 END),0) cash_in,
                COALESCE(SUM(CASE WHEN direction='cash_out' THEN amount ELSE 0 END),0) cash_out,
                COALESCE(SUM(commission),0) commission
            FROM mpesa_transactions WHERE session_id=$sid AND is_voided=0";
        $my_txns = $conn->query($txn_sql)->fetch_assoc();

        /* Recent 10 transactions */
        $recent_txn_sql = "SELECT mt.txn_time, mt.particulars, mt.direction,
                mt.amount, mt.commission, tt.type_name
            FROM mpesa_transactions mt
            JOIN transaction_types tt ON tt.id=mt.type_id
            WHERE mt.session_id=$sid AND mt.is_voided=0
            ORDER BY mt.txn_time DESC LIMIT 10";
        $recent_txns = $conn->query($recent_txn_sql)->fetch_all(MYSQLI_ASSOC);

        /* Airtime sold today */
        $air_sql = "SELECT COALESCE(SUM(amount),0) sold FROM airtime_sales WHERE session_id=$sid";
        $airtime_sold = (float)$conn->query($air_sql)->fetch_assoc()['sold'];
    } else {
        $my_txns = ['txn_count'=>0,'cash_in'=>0,'cash_out'=>0,'commission'=>0];
        $recent_txns = [];
        $airtime_sold = 0;
    }
}

/* ═══════════════════════════════════════════════════════════════════
   AUDITOR METRICS (read-only summary)
══════════════════════════════════════════════════════════════════════ */
if ($is_auditor) {
    $r = $conn->query("SELECT l.location_name, ds.business_date, ds.status session_status,
            dr.expected_balance, dr.actual_balance, dr.short_amount, dr.excess_amount, dr.status recon_status
        FROM daily_sessions ds
        JOIN locations l ON l.id=ds.location_id
        LEFT JOIN daily_reconciliation dr ON dr.session_id=ds.id
        WHERE l.business_id=$business_id
        ORDER BY ds.business_date DESC, l.location_name
        LIMIT 20");
    $audit_view = $r->fetch_all(MYSQLI_ASSOC);
}

/* ── DO NOT close $conn here — layouts/topbar.php still needs it ──
   $conn will be closed naturally when the script finishes.          */

/* ─── helpers ───────────────────────────────────────────────────── */
function kes(float $v): string { return 'KES '.number_format($v, 2); }
function statusBadge(string $s): string {
    return match($s) {
        'CRITICAL' => 'badge bg-danger',
        'LOW'      => 'badge bg-warning text-dark',
        'WATCH'    => 'badge bg-info text-dark',
        default    => 'badge bg-success',
    };
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php',
        ['title' => 'Dashboard — Christmond M-Pesa System']); ?>
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
    <style>
        :root {
            --mpesa-green:       #00a651;
            --mpesa-green-dark:  #007a3d;
            --mpesa-green-light: #34c470;
            --light-green:       #e8f8ef;
        }
        .stat-card { border: none; border-radius: 14px; overflow: hidden; box-shadow: 0 2px 12px rgba(0,0,0,.07); transition: transform .2s; }
        .stat-card:hover { transform: translateY(-3px); }
        .stat-card .icon-wrap { width: 52px; height: 52px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; }
        .stat-card .stat-label { font-size: .72rem; text-transform: uppercase; letter-spacing: .06em; color: var(--bs-secondary); }
        .stat-card .stat-value { font-size: 1.55rem; font-weight: 700; color: #1a1a2e; line-height: 1.1; }
        .stat-card .stat-sub   { font-size: .78rem; color: var(--bs-secondary); margin-top: 3px; }

        .float-pill { padding: 6px 14px; border-radius: 20px; font-size: .8rem; font-weight: 600; margin: 3px; display: inline-block; }
        .float-pill.mpesa  { background: #e8f8ef; color: #007a3d; }
        .float-pill.equity { background: #fff3cd; color: #7a5000; }
        .float-pill.kcb    { background: #e3f2fd; color: #1565c0; }
        .float-pill.coop   { background: #fce4ec; color: #880e4f; }
        .float-pill.ncba   { background: #ede7f6; color: #4527a0; }
        .float-pill.absa   { background: #ffebee; color: #b71c1c; }
        .float-pill.dim    { background: #e8eaf6; color: #283593; }

        .session-banner { border-radius: 14px; padding: 18px 22px; }
        .session-open   { background: linear-gradient(120deg, #e8f8ef, #d0f0e0); border-left: 5px solid var(--mpesa-green); }
        .session-none   { background: linear-gradient(120deg, #fff3cd, #ffeaa7); border-left: 5px solid #ffc107; }
        .session-closed { background: linear-gradient(120deg, #e3f2fd, #bbdefb); border-left: 5px solid #1976d2; }

        .alert-item { border-left: 4px solid; border-radius: 8px; padding: 10px 14px; margin-bottom: 8px; font-size: .85rem; }
        .alert-item.critical { border-color: #dc3545; background: #fff5f5; }
        .alert-item.high     { border-color: #fd7e14; background: #fff8f0; }
        .alert-item.medium   { border-color: #ffc107; background: #fffdf0; }
        .alert-item.low      { border-color: #28a745; background: #f0fff4; }

        .table-sm td, .table-sm th { font-size: .83rem; vertical-align: middle; }
        .badge-session-open     { background: #d0f0e0; color: #007a3d; }
        .badge-session-closed   { background: #bbdefb; color: #1565c0; }
        .badge-session-approved { background: #c8e6c9; color: #2e7d32; }
        .badge-session-disputed { background: #ffcdd2; color: #b71c1c; }

        .section-title { font-size: .95rem; font-weight: 700; color: #1a1a2e; border-bottom: 2px solid var(--mpesa-green); padding-bottom: 6px; margin-bottom: 16px; }

        .btn-mpesa { background: linear-gradient(135deg, var(--mpesa-green), var(--mpesa-green-light)); border: none; color: #fff; border-radius: 8px; }
        .btn-mpesa:hover { background: linear-gradient(135deg, var(--mpesa-green-dark), var(--mpesa-green)); color: #fff; }
    </style>
    <style>
.main-content { margin-left: 280px; }
@media (max-width: 768px) { .main-content { margin-left: 0 !important; } }
</style>
</head>

<body>
<?php include 'layouts/menu.php'; ?>

<div class="main-content">
<div class="page-content">
<div class="container-fluid">

<!-- ── Page header ─────────────────────────────────────────────── -->
<div class="row mb-3">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
                <h5 class="mb-0 fw-bold">
                    <i class="ri-dashboard-line text-success me-2"></i>
                    <?php if($is_admin): ?>
                        Business Overview
                    <?php elseif($is_agent): ?>
                        <?= htmlspecialchars($_SESSION['primary_location_name'] ?? 'My Branch') ?> — Daily View
                    <?php else: ?>
                        Audit Overview
                    <?php endif; ?>
                </h5>
                <small class="text-muted">
                    <?= date('l, d F Y') ?> &bull;
                    <?= htmlspecialchars($_SESSION['full_name']) ?>
                    <span class="badge ms-1" style="background:var(--mpesa-green);font-size:.7rem;">
                        <?= ucfirst(str_replace('_',' ', $role)) ?>
                    </span>
                </small>
            </div>
            <div class="d-flex gap-2">
                <?php if($is_admin): ?>
                    <a href="reports.php" class="btn btn-sm btn-outline-success">
                        <i class="ri-file-chart-line me-1"></i>Reports
                    </a>
                    <a href="locations.php" class="btn btn-sm btn-outline-secondary">
                        <i class="ri-store-2-line me-1"></i>Branches
                    </a>
                <?php endif; ?>
                <?php if($is_agent && !$my_session): ?>
                    <a href="open_session.php" class="btn btn-sm btn-mpesa">
                        <i class="ri-play-circle-line me-1"></i>Open Today's Session
                    </a>
                <?php elseif($is_agent && $my_session && $my_session['status']==='open'): ?>
                    <a href="transactions.php" class="btn btn-sm btn-mpesa">
                        <i class="ri-add-circle-line me-1"></i>Record Transaction
                    </a>
                    <a href="close_session.php?id=<?= $my_session['id'] ?>" class="btn btn-sm btn-outline-danger">
                        <i class="ri-stop-circle-line me-1"></i>Close Session
                    </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php /* ══════════════════════════════════════════════════════════════
         ADMIN / MANAGER VIEW
       ══════════════════════════════════════════════════════════════ */
if ($is_admin): ?>

<!-- KPI cards -->
<div class="row g-3 mb-4">

    <!-- Total Float -->
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="icon-wrap" style="background:#e8f8ef;">
                    <i class="ri-money-dollar-circle-line" style="color:var(--mpesa-green);"></i>
                </div>
                <div>
                    <div class="stat-label">Total Float</div>
                    <div class="stat-value"><?= kes((float)($float_totals['total_float']??0)) ?></div>
                    <div class="stat-sub">Across all branches &amp; banks</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Today's Commission -->
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="icon-wrap" style="background:#fff8e1;">
                    <i class="ri-award-line" style="color:#f59e0b;"></i>
                </div>
                <div>
                    <div class="stat-label">Commission Today</div>
                    <div class="stat-value"><?= kes($today_commission) ?></div>
                    <div class="stat-sub"><?= number_format($today_mpesa['txn_count']) ?> M-Pesa transactions</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Active Sessions -->
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="icon-wrap" style="background:#e3f2fd;">
                    <i class="ri-store-2-line" style="color:#1976d2;"></i>
                </div>
                <div>
                    <div class="stat-label">Sessions Today</div>
                    <div class="stat-value"><?= (int)$sessions['total'] ?> / <?= $total_locations ?></div>
                    <div class="stat-sub">
                        <?= (int)$sessions['open_count'] ?> open &bull;
                        <?= (int)$sessions['closed_count'] ?> closed &bull;
                        <?= (int)$sessions['approved_count'] ?> approved
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Short / Alerts -->
    <div class="col-xl-3 col-md-6">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="icon-wrap" style="background:<?= $recon_today['total_short']>0 ? '#ffebee' : '#e8f8ef' ?>;">
                    <i class="ri-alarm-warning-line" style="color:<?= $recon_today['total_short']>0 ? '#c0392b' : '#00a651' ?>;"></i>
                </div>
                <div>
                    <div class="stat-label">Recon Issues</div>
                    <div class="stat-value"><?= kes((float)$recon_today['total_short']) ?></div>
                    <div class="stat-sub">
                        Short today &bull;
                        <?= (int)$recon_today['pending_recon'] ?> pending &bull;
                        <?= $alert_count ?> alerts
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Today's volume strip -->
<div class="row g-3 mb-4">
    <div class="col-md-8">
        <div class="card stat-card">
            <div class="card-body">
                <div class="section-title">Today's Float Breakdown</div>
                <?php
                $types = ['mpesa'=>'M-Pesa','equity'=>'Equity','kcb'=>'KCB','coop'=>'Co-op','ncba'=>'NCBA','absa'=>'ABSA','dim'=>'DIM'];
                foreach ($types as $key => $label):
                    $val = (float)($float_totals[$key] ?? 0);
                ?>
                    <span class="float-pill <?= $key ?>">
                        <?= $label ?>: <strong><?= kes($val) ?></strong>
                    </span>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card stat-card">
            <div class="card-body text-center">
                <div class="section-title">Cash Flow Today</div>
                <div class="d-flex justify-content-around">
                    <div>
                        <div class="text-success fw-bold fs-5"><?= kes((float)$today_mpesa['cash_in']) ?></div>
                        <small class="text-muted">Cash In</small>
                    </div>
                    <div>
                        <div class="text-danger fw-bold fs-5"><?= kes((float)$today_mpesa['cash_out']) ?></div>
                        <small class="text-muted">Cash Out</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">

    <!-- Float snapshot table -->
    <div class="col-xl-8">
        <div class="card stat-card">
            <div class="card-body">
                <div class="section-title">Branch Float Snapshot</div>
                <div class="table-responsive">
                    <table class="table table-sm table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Branch</th>
                                <th>Account</th>
                                <th class="text-end">Balance (KES)</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($float_snap as $row): ?>
                            <tr>
                                <td><?= htmlspecialchars($row['location_name']) ?></td>
                                <td><span class="float-pill <?= strtolower($row['account_type']) ?>"><?= $row['account_type'] ?></span></td>
                                <td class="text-end fw-semibold"><?= kes((float)$row['current_balance']) ?></td>
                                <td><span class="<?= statusBadge($row['status']) ?>"><?= $row['status'] ?></span></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($float_snap)): ?>
                            <tr><td colspan="4" class="text-center text-muted py-3">No float accounts found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Alerts -->
    <div class="col-xl-4">
        <div class="card stat-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="section-title mb-0">Active Alerts</div>
                    <?php if($alert_count): ?>
                        <span class="badge bg-danger"><?= $alert_count ?></span>
                    <?php endif; ?>
                </div>
                <?php if (empty($alerts_list)): ?>
                    <div class="text-center text-muted py-3">
                        <i class="ri-checkbox-circle-line text-success fs-3 d-block mb-1"></i>
                        All clear — no active alerts
                    </div>
                <?php else: ?>
                    <?php foreach ($alerts_list as $al): ?>
                        <div class="alert-item <?= $al['severity'] ?>">
                            <div class="fw-semibold"><?= htmlspecialchars($al['alert_type']) ?></div>
                            <div><?= htmlspecialchars($al['location_name'] ?? '') ?></div>
                            <div class="text-muted" style="font-size:.75rem;">
                                <?= htmlspecialchars(substr($al['message'],0,80)) ?>…
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <a href="alerts.php" class="btn btn-sm btn-outline-danger w-100 mt-1">View All Alerts</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Branch commission + recent reconciliation -->
<div class="row g-3">
    <div class="col-xl-4">
        <div class="card stat-card">
            <div class="card-body">
                <div class="section-title">Commission (Last 7 Days)</div>
                <?php foreach ($branch_comms as $bc): ?>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small"><?= htmlspecialchars($bc['location_name']) ?></span>
                        <span class="badge" style="background:var(--mpesa-green);font-size:.78rem;">
                            <?= kes((float)$bc['total_comm']) ?>
                        </span>
                    </div>
                <?php endforeach; ?>
                <?php if (empty($branch_comms)): ?>
                    <p class="text-muted small">No commission data in last 7 days.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card stat-card">
            <div class="card-body">
                <div class="section-title">Recent Reconciliations</div>
                <div class="table-responsive">
                    <table class="table table-sm table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Date</th><th>Branch</th><th>By</th>
                                <th class="text-end">Expected</th>
                                <th class="text-end">Actual</th>
                                <th class="text-end">Short</th>
                                <th class="text-end">Excess</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($recent_recon as $rr): ?>
                            <tr>
                                <td><?= $rr['business_date'] ?></td>
                                <td><?= htmlspecialchars($rr['location_name']) ?></td>
                                <td><?= htmlspecialchars($rr['reconciled_by']) ?></td>
                                <td class="text-end"><?= number_format((float)$rr['expected_balance']) ?></td>
                                <td class="text-end"><?= number_format((float)$rr['actual_balance']) ?></td>
                                <td class="text-end <?= $rr['short_amount']>0 ? 'text-danger fw-bold' : '' ?>">
                                    <?= $rr['short_amount']>0 ? number_format((float)$rr['short_amount']) : '—' ?>
                                </td>
                                <td class="text-end <?= $rr['excess_amount']>0 ? 'text-success fw-bold' : '' ?>">
                                    <?= $rr['excess_amount']>0 ? number_format((float)$rr['excess_amount']) : '—' ?>
                                </td>
                                <td>
                                    <span class="badge <?= match($rr['status']) {
                                        'approved' => 'bg-success',
                                        'pending'  => 'bg-warning text-dark',
                                        'disputed' => 'bg-danger',
                                        default    => 'bg-secondary'
                                    } ?>">
                                        <?= ucfirst($rr['status']) ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($recent_recon)): ?>
                            <tr><td colspan="8" class="text-center text-muted py-3">No reconciliations found.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php /* ══════════════════════════════════════════════════════════════
         AGENT VIEW
       ══════════════════════════════════════════════════════════════ */
elseif ($is_agent): ?>

<!-- Session status banner -->
<div class="row mb-4">
    <div class="col-12">
        <?php if (!$my_session): ?>
            <div class="session-banner session-none d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="fw-bold mb-1"><i class="ri-time-line me-2"></i>No session open today</h6>
                    <small class="text-muted">Start your day by opening today's session to begin recording transactions.</small>
                </div>
                <a href="open_session.php" class="btn btn-sm btn-mpesa">
                    <i class="ri-play-circle-line me-1"></i>Open Session
                </a>
            </div>
        <?php elseif($my_session['status']==='open'): ?>
            <div class="session-banner session-open d-flex justify-content-between align-items-center flex-wrap gap-2">
                <div>
                    <h6 class="fw-bold mb-1" style="color:var(--mpesa-green-dark);">
                        <i class="ri-radio-button-line me-2"></i>Session Open — <?= date('D d M Y') ?>
                    </h6>
                    <small class="text-muted">
                        Opened at <?= date('H:i', strtotime($my_session['opened_at'])) ?> &bull;
                        Session #<?= $my_session['id'] ?>
                    </small>
                </div>
                <div class="d-flex gap-2">
                    <a href="transactions.php?session=<?= $my_session['id'] ?>" class="btn btn-sm btn-mpesa">
                        <i class="ri-add-line me-1"></i>New Transaction
                    </a>
                    <a href="close_session.php?id=<?= $my_session['id'] ?>" class="btn btn-sm btn-outline-danger">
                        <i class="ri-stop-line me-1"></i>Close Session
                    </a>
                </div>
            </div>
        <?php else: ?>
            <div class="session-banner session-closed d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="fw-bold mb-1 text-primary">
                        <i class="ri-check-double-line me-2"></i>Session Closed
                    </h6>
                    <small class="text-muted">Closed at <?= date('H:i', strtotime($my_session['closed_at'])) ?> &bull; Status: <?= ucfirst($my_session['status']) ?></small>
                </div>
                <a href="session_detail.php?id=<?= $my_session['id'] ?>" class="btn btn-sm btn-outline-primary">
                    <i class="ri-eye-line me-1"></i>View Details
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- KPI cards (agent) -->
<div class="row g-3 mb-4">
    <div class="col-sm-6 col-xl-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="icon-wrap" style="background:#e8f8ef;">
                    <i class="ri-arrow-down-circle-line" style="color:var(--mpesa-green);"></i>
                </div>
                <div>
                    <div class="stat-label">Cash In Today</div>
                    <div class="stat-value"><?= kes((float)$my_txns['cash_in']) ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="icon-wrap" style="background:#ffebee;">
                    <i class="ri-arrow-up-circle-line" style="color:#c0392b;"></i>
                </div>
                <div>
                    <div class="stat-label">Cash Out Today</div>
                    <div class="stat-value"><?= kes((float)$my_txns['cash_out']) ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="icon-wrap" style="background:#fff8e1;">
                    <i class="ri-award-line" style="color:#f59e0b;"></i>
                </div>
                <div>
                    <div class="stat-label">Commission</div>
                    <div class="stat-value"><?= kes((float)$my_txns['commission']) ?></div>
                    <div class="stat-sub"><?= $my_txns['txn_count'] ?> transactions</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-sm-6 col-xl-3">
        <div class="card stat-card h-100">
            <div class="card-body d-flex align-items-center gap-3">
                <div class="icon-wrap" style="background:#e3f2fd;">
                    <i class="ri-sim-card-line" style="color:#1976d2;"></i>
                </div>
                <div>
                    <div class="stat-label">Airtime Sold</div>
                    <div class="stat-value"><?= kes($airtime_sold) ?></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <!-- Float balances -->
    <div class="col-xl-4">
        <div class="card stat-card">
            <div class="card-body">
                <div class="section-title">My Float Balances</div>
                <?php foreach ($my_floats as $f): ?>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <span class="float-pill <?= strtolower($f['account_type']) ?>">
                                <?= $f['account_type'] ?>
                            </span>
                        </div>
                        <div class="text-end">
                            <div class="fw-bold"><?= kes((float)$f['current_balance']) ?></div>
                            <span class="<?= statusBadge($f['status']) ?>" style="font-size:.7rem;"><?= $f['status'] ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
                <?php if (empty($my_floats)): ?>
                    <p class="text-muted small">No float accounts assigned.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Recent transactions -->
    <div class="col-xl-8">
        <div class="card stat-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div class="section-title mb-0">Today's Transactions</div>
                    <?php if($my_session): ?>
                        <a href="transactions.php?session=<?= $my_session['id'] ?>" class="btn btn-sm btn-outline-success">
                            View All
                        </a>
                    <?php endif; ?>
                </div>
                <?php if (empty($recent_txns)): ?>
                    <div class="text-center text-muted py-4">
                        <i class="ri-inbox-line fs-2 d-block mb-1"></i>
                        No transactions recorded yet today.
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Time</th><th>Particulars</th><th>Type</th>
                                    <th class="text-end">Amount</th>
                                    <th class="text-end">Comm.</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($recent_txns as $t): ?>
                                <tr>
                                    <td class="text-muted"><?= date('H:i', strtotime($t['txn_time'])) ?></td>
                                    <td><?= htmlspecialchars($t['particulars']) ?></td>
                                    <td>
                                        <span class="badge <?= $t['direction']==='cash_in' ? 'bg-success' : 'bg-danger' ?>" style="font-size:.7rem;">
                                            <?= $t['type_name'] ?>
                                        </span>
                                    </td>
                                    <td class="text-end fw-semibold <?= $t['direction']==='cash_in' ? 'text-success' : 'text-danger' ?>">
                                        <?= ($t['direction']==='cash_in' ? '+' : '-') ?>
                                        <?= number_format((float)$t['amount']) ?>
                                    </td>
                                    <td class="text-end text-muted"><?= $t['commission']>0 ? number_format((float)$t['commission'],2) : '—' ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php /* ══════════════════════════════════════════════════════════════
         AUDITOR VIEW
       ══════════════════════════════════════════════════════════════ */
elseif ($is_auditor): ?>

<div class="row">
    <div class="col-12">
        <div class="card stat-card">
            <div class="card-body">
                <div class="section-title">Reconciliation Audit Log (Last 20 sessions)</div>
                <div class="table-responsive">
                    <table class="table table-sm table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Date</th><th>Branch</th><th>Session</th>
                                <th class="text-end">Expected</th><th class="text-end">Actual</th>
                                <th class="text-end">Short</th><th class="text-end">Excess</th>
                                <th>Recon Status</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($audit_view as $av): ?>
                            <tr>
                                <td><?= $av['business_date'] ?></td>
                                <td><?= htmlspecialchars($av['location_name']) ?></td>
                                <td>
                                    <span class="badge badge-session-<?= $av['session_status'] ?>">
                                        <?= ucfirst($av['session_status']) ?>
                                    </span>
                                </td>
                                <td class="text-end"><?= number_format((float)$av['expected_balance']) ?></td>
                                <td class="text-end"><?= number_format((float)$av['actual_balance']) ?></td>
                                <td class="text-end <?= $av['short_amount']>0 ? 'text-danger fw-bold' : '' ?>">
                                    <?= $av['short_amount']>0 ? number_format((float)$av['short_amount']) : '—' ?>
                                </td>
                                <td class="text-end <?= $av['excess_amount']>0 ? 'text-success fw-bold' : '' ?>">
                                    <?= $av['excess_amount']>0 ? number_format((float)$av['excess_amount']) : '—' ?>
                                </td>
                                <td>
                                    <?php if($av['recon_status']): ?>
                                        <span class="badge <?= match($av['recon_status']) {
                                            'approved' => 'bg-success',
                                            'pending'  => 'bg-warning text-dark',
                                            'disputed' => 'bg-danger',
                                            default    => 'bg-secondary'
                                        } ?>">
                                            <?= ucfirst($av['recon_status']) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted small">—</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php endif; ?>

</div><!-- /container-fluid -->
</div><!-- /page-content -->
</div><!-- /main-content -->

<?php include 'layouts/vendor-scripts.php'; ?>
<script>
// Auto-refresh alert badge every 2 min
setInterval(() => {
    fetch('api/alert_count.php')
        .then(r => r.json())
        .then(d => {
            const el = document.getElementById('alert-badge');
            if (el && d.count > 0) { el.textContent = d.count; el.style.display = ''; }
        }).catch(() => {});
}, 120000);
</script>
</body>
</html>