<?php

// ─── Session setup ────────────────────────────────────────────────────────────
session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
    mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();

error_reporting(0);

// ─── Auth guard ───────────────────────────────────────────────────────────────
if (!isset($_SESSION['sid']) || strlen($_SESSION['sid']) == 0) {
    header('location:logout.php');
    exit();
}
if (!isset($_SESSION['permission']) || $_SESSION['permission'] !== 'Super User') {
    header('location:logout.php');
    exit();
}

// ─── Dependencies ─────────────────────────────────────────────────────────────
require_once 'vendor/autoload.php';
require_once 'helpers/ReconciliationHelper.php';
include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName = $stResult['term_name'];

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

// ─── Date validation ──────────────────────────────────────────────────────────
$rawDate      = $_GET['date'] ?? date('Y-m-d');
$selectedDate = validateReconciliationDate($rawDate);
$dateInvalid  = ($selectedDate !== $rawDate && $rawDate !== '');

// ─── Summary queries ──────────────────────────────────────────────────────────

// Paystack Total — sourced live from Paystack API (see JS autoFetchPaystack on page load)
// Local DB queries kept only for variance reference in the AJAX endpoint.
// We still need local count/total for the PDF export fallback.
$stmt = $con->prepare("SELECT COUNT(*), COALESCE(SUM(amount),0) FROM payments WHERE DATE(payment_date)=? AND LOWER(payment_method) IN ('paystack','bank transfer')");
$stmt->bind_param('s', $selectedDate);
$stmt->execute();
$stmt->bind_result($paystackCount, $paystackTotal);
$stmt->fetch();
$stmt->close();

// Paystack Card sub-total (local DB fallback)
$stmt = $con->prepare("SELECT COUNT(*), COALESCE(SUM(amount),0) FROM payments WHERE DATE(payment_date)=? AND LOWER(payment_method)='paystack'");
$stmt->bind_param('s', $selectedDate);
$stmt->execute();
$stmt->bind_result($cardCount, $cardTotal);
$stmt->fetch();
$stmt->close();

// Bank Transfer sub-total (local DB fallback)
$stmt = $con->prepare("SELECT COUNT(*), COALESCE(SUM(amount),0) FROM payments WHERE DATE(payment_date)=? AND LOWER(payment_method)='bank transfer'");
$stmt->bind_param('s', $selectedDate);
$stmt->execute();
$stmt->bind_result($bankCount, $bankTotal);
$stmt->fetch();
$stmt->close();

// Approved Total (payment table — all methods)
$stmt = $con->prepare("SELECT COUNT(*), COALESCE(SUM(amount),0) FROM payment WHERE DATE(payment_date)=?");
$stmt->bind_param('s', $selectedDate);
$stmt->execute();
$stmt->bind_result($approvedCount, $approvedTotal);
$stmt->fetch();
$stmt->close();

// Wallet Total
$stmt = $con->prepare("SELECT COUNT(*), COALESCE(SUM(amount),0) FROM payment WHERE DATE(payment_date)=? AND method='Wallet'");
$stmt->bind_param('s', $selectedDate);
$stmt->execute();
$stmt->bind_result($walletCount, $walletTotal);
$stmt->fetch();
$stmt->close();

// Wallet — same-day funded: students who paid via wallet today AND had a deposit today
// These represent Paystack inflows that already entered today (same-day round-trip)
$stmt = $con->prepare(
    "SELECT COUNT(*), COALESCE(SUM(p.amount),0)
     FROM payment p
     WHERE DATE(p.payment_date) = ?
       AND p.method = 'Wallet'
       AND EXISTS (
           SELECT 1 FROM wallet_transactions wt
           WHERE wt.student_id = p.studentno
              OR wt.student_id = (SELECT id FROM students WHERE studentno = p.studentno LIMIT 1)
           AND wt.type = 'deposit'
           AND DATE(wt.created_at) = ?
           AND wt.status = 'success'
       )"
);
$stmt->bind_param('ss', $selectedDate, $selectedDate);
$stmt->execute();
$stmt->bind_result($walletSameDayCount, $walletSameDayTotal);
$stmt->fetch();
$stmt->close();

// Wallet — pre-funded: wallet payments today where the deposit was on a PRIOR day
$walletPreFundedCount = max(0, (int)$walletCount - (int)$walletSameDayCount);
$walletPreFundedTotal = max(0.0, (float)$walletTotal - (float)$walletSameDayTotal);

// Other Total — anything that isn't Wallet or Paystack in the payment table
$stmt = $con->prepare("SELECT COUNT(*), COALESCE(SUM(amount),0) FROM payment WHERE DATE(payment_date)=? AND LOWER(method) NOT IN ('wallet','paystack')");
$stmt->bind_param('s', $selectedDate);
$stmt->execute();
$stmt->bind_result($otherCount, $otherTotal);
$stmt->fetch();
$stmt->close();

// Pending (message table)
$stmt = $con->prepare("SELECT COUNT(*), COALESCE(SUM(amount),0) FROM message WHERE DATE(timestamp)=? AND status=0");
$stmt->bind_param('s', $selectedDate);
$stmt->execute();
$stmt->bind_result($pendingCount, $pendingTotal);
$stmt->fetch();
$stmt->close();

// Approved Paystack-method (for variance calculation)
// In the payment table, card payments use method='Paystack' only — no 'Bank Transfer' here
$stmt = $con->prepare("SELECT COALESCE(SUM(amount),0) FROM payment WHERE DATE(payment_date)=? AND LOWER(method)='paystack'");
$stmt->bind_param('s', $selectedDate);
$stmt->execute();
$stmt->bind_result($approvedPaystackAmount);
$stmt->fetch();
$stmt->close();

// ─── Derived values ───────────────────────────────────────────────────────────
$grandTotal = computeGrandTotal([$approvedTotal]);
$variance   = computeVariance((float)$paystackTotal, (float)$approvedPaystackAmount);

// ─── Transaction log — method filter & pagination ─────────────────────────────
$methodFilter = $_GET['method'] ?? 'All';
$page         = max(1, (int)($_GET['page'] ?? 1));
$perPage      = 25;
$offset       = ($page - 1) * $perPage;

// Build WHERE clauses based on method filter
$paymentWhere   = "DATE(p.payment_date) = ?";
$paymentsWhere  = "DATE(py.payment_date) = ?";
$includePayments = true; // whether to include the payments table half

if ($methodFilter === 'Wallet') {
    $paymentWhere   .= " AND p.method = 'Wallet'";
    $includePayments = false;
} elseif ($methodFilter === 'Other') {
    $paymentWhere   .= " AND LOWER(p.method) NOT IN ('wallet','paystack')";
    $includePayments = false;
} elseif ($methodFilter === 'Paystack') {
    $paymentWhere  .= " AND LOWER(p.method) = 'paystack'";
    $paymentsWhere .= " AND LOWER(py.payment_method) = 'paystack'";
} elseif ($methodFilter === 'Bank Transfer') {
    $paymentWhere  .= " AND LOWER(p.method) = 'bank transfer'";
    $paymentsWhere .= " AND LOWER(py.payment_method) = 'bank transfer'";
}

// Count query (no LIMIT)
if ($includePayments) {
    $countSql = "SELECT COUNT(*) FROM (
        SELECT p.id FROM payment p WHERE {$paymentWhere}
        UNION ALL
        SELECT py.id FROM payments py WHERE {$paymentsWhere}
    ) AS combined";
    $countStmt = $con->prepare($countSql);
    $countStmt->bind_param('ss', $selectedDate, $selectedDate);
} else {
    $countSql  = "SELECT COUNT(*) FROM payment p WHERE {$paymentWhere}";
    $countStmt = $con->prepare($countSql);
    $countStmt->bind_param('s', $selectedDate);
}
$countStmt->execute();
$countStmt->bind_result($totalRows);
$countStmt->fetch();
$countStmt->close();
$totalPages = max(1, (int)ceil($totalRows / $perPage));

// Data query (with LIMIT/OFFSET)
if ($includePayments) {
    $dataSql = "SELECT p.studentName, p.studentno, p.pay_for AS purpose, p.amount,
                       p.method AS channel, p.Term AS term, p.session, p.payment_date,
                       'payment' AS source_table
                FROM payment p WHERE {$paymentWhere}
                UNION ALL
                SELECT py.studentName, py.studentno, py.fee_type AS purpose, py.amount,
                       py.payment_method AS channel, '' AS term, '' AS session, py.payment_date,
                       'payments' AS source_table
                FROM payments py WHERE {$paymentsWhere}
                ORDER BY payment_date DESC LIMIT ? OFFSET ?";
    $dataStmt = $con->prepare($dataSql);
    $dataStmt->bind_param('ssii', $selectedDate, $selectedDate, $perPage, $offset);
} else {
    $dataSql = "SELECT p.studentName, p.studentno, p.pay_for AS purpose, p.amount,
                       p.method AS channel, p.Term AS term, p.session, p.payment_date,
                       'payment' AS source_table
                FROM payment p WHERE {$paymentWhere}
                ORDER BY p.payment_date DESC LIMIT ? OFFSET ?";
    $dataStmt = $con->prepare($dataSql);
    $dataStmt->bind_param('sii', $selectedDate, $perPage, $offset);
}
$dataStmt->execute();
$result       = $dataStmt->get_result();
$transactions = [];
while ($row = $result->fetch_assoc()) {
    $transactions[] = $row;
}
$dataStmt->close();

?>
<!DOCTYPE html>
<html lang="en">
<?php @include("includes/head.php"); ?>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

  <?php @include("includes/header.php"); ?>
  <?php @include("includes/sidebar.php"); ?>

  <!-- Content Wrapper -->
  <div class="content-wrapper">
            <section class="content-header premium-header">
                <div class="container-fluid">
                    <div class="header-glass-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="title-section">
                                    <div class="icon-box bg-primary-gradient shadow-sm">
                                        <i class="fas fa-credit-card"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Payment Management
                                            <span class="premium-subtitle text-secondary">Daily Transaction Reconciliation for <?= date('d M Y', strtotime($selectedDate)) ?></span>
                                        </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb premium-breadcrumb">
                                        <li class="breadcrumb-item"><a href="dashboard.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Daily Reconciliation</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
    <!-- Page Header -->

    <!-- Main content -->
    <section class="content">
      <div class="container-fluid">

        <?php if ($dateInvalid): ?>
        <div class="alert alert-warning alert-dismissible">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <i class="fas fa-exclamation-triangle"></i>
          Invalid date provided. Showing results for today.
        </div>
        <?php endif; ?>

        <?php if (isset($_GET['pdf_error'])): ?>
        <div class="alert alert-danger alert-dismissible">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <i class="fas fa-times-circle"></i>
          PDF generation failed. Please try again.
        </div>
        <?php endif; ?>

        <!-- Date picker form -->
        <div class="card card-default mb-3">
                      <div class="card-header text-white">
            <h5 class="card-title">
              <i class="fas fa-search"></i> Search 
            </h5>
            <div class="card-tools">
            </div>
          </div>
          <div class="card-body">
            <form method="GET">
              <div class="form-row align-items-end">
                <div class="col-md-4 col-sm-6 mb-2">
                  <label class="font-weight-bold"><i class="fas fa-calendar-alt mr-1"></i> Select Date</label>
                  <input type="date" name="date" class="form-control"
                         value="<?= htmlspecialchars($selectedDate) ?>">
                </div>
                <div class="col-auto mb-2">
                  <button type="submit" class="btn btn-primary">
                    <i class="fas fa-search mr-1"></i> View
                  </button>
                </div>
                <div class="col-auto mb-2">
                  <a href="generate_reconciliation_pdf.php?date=<?= urlencode($selectedDate) ?>"
                     class="btn btn-danger">
                    <i class="fas fa-file-pdf mr-1"></i> Export PDF
                  </a>
                </div>
              </div>
            </form>
          </div>
        </div>

        <!-- ── Summary Bento Cards ── -->
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-4 gap-4 mb-6">

          <!-- Paystack Inflows — live from Paystack API -->
          <div class="bento-card group" id="paystackInflowCard">
            <div class="flex justify-between items-start mb-3">
              <div class="w-10 h-10 bg-blue-50 text-blue-600 rounded-xl flex items-center justify-center text-base transition-transform group-hover:scale-110">
                <i class="fas fa-credit-card"></i>
              </div>
              <span class="text-[11px] font-bold text-slate-400 uppercase tracking-tight">Paystack Inflows</span>
            </div>
            <h2 class="text-xl font-black text-slate-800 tracking-tight" id="paystackInflowTotal">
              <i class="fas fa-spinner fa-spin text-blue-400"></i>
            </h2>
            <p class="text-[12px] font-bold text-slate-500 uppercase tracking-tight mt-1" id="paystackInflowCount">Loading…</p>
            <p class="text-[11px] text-slate-400 mt-1" id="paystackInflowBreakdown"></p>
            <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">
              <div class="h-full bg-blue-600 opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000"></div>
            </div>
          </div>

          <!-- Approved Payments -->
          <div class="bento-card group">
            <div class="flex justify-between items-start mb-3">
              <div class="w-10 h-10 bg-emerald-50 text-emerald-600 rounded-xl flex items-center justify-center text-base transition-transform group-hover:scale-110">
                <i class="fas fa-check-circle"></i>
              </div>
              <span class="text-[11px] font-bold text-slate-400 uppercase tracking-tight">Approved</span>
            </div>
            <h2 class="text-xl font-black text-slate-800 tracking-tight"><?= formatNaira((float)$approvedTotal) ?></h2>
            <p class="text-[12px] font-bold text-slate-500 uppercase tracking-tight mt-1"><?= (int)$approvedCount ?> payments</p>
            <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">
              <div class="h-full bg-emerald-600 opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000"></div>
            </div>
          </div>

          <!-- Wallet Payments -->
          <div class="bento-card group">
            <div class="flex justify-between items-start mb-3">
              <div class="w-10 h-10 bg-cyan-50 text-cyan-600 rounded-xl flex items-center justify-center text-base transition-transform group-hover:scale-110">
                <i class="fas fa-wallet"></i>
              </div>
              <span class="text-[11px] font-bold text-slate-400 uppercase tracking-tight">Wallet</span>
            </div>
            <h2 class="text-xl font-black text-slate-800 tracking-tight"><?= formatNaira((float)$walletTotal) ?></h2>
            <p class="text-[12px] font-bold text-slate-500 uppercase tracking-tight mt-1"><?= (int)$walletCount ?> payments</p>
            <p class="text-[11px] text-slate-400 mt-1">
              Same-day funded: <?= formatNaira((float)$walletSameDayTotal) ?> (<?= (int)$walletSameDayCount ?>)<br>
              <span class="text-amber-500">Pre-funded (prior day): <?= formatNaira((float)$walletPreFundedTotal) ?> (<?= (int)$walletPreFundedCount ?>)</span>
            </p>
            <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">
              <div class="h-full bg-cyan-600 opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000"></div>
            </div>
          </div>

          <!-- Other Payments -->
          <div class="bento-card group">
            <div class="flex justify-between items-start mb-3">
              <div class="w-10 h-10 bg-slate-50 text-slate-600 rounded-xl flex items-center justify-center text-base transition-transform group-hover:scale-110">
                <i class="fas fa-ellipsis-h"></i>
              </div>
              <span class="text-[11px] font-bold text-slate-400 uppercase tracking-tight">Other</span>
            </div>
            <h2 class="text-xl font-black text-slate-800 tracking-tight"><?= formatNaira((float)$otherTotal) ?></h2>
            <p class="text-[12px] font-bold text-slate-500 uppercase tracking-tight mt-1"><?= (int)$otherCount ?> payments</p>
            <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">
              <div class="h-full bg-slate-600 opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000"></div>
            </div>
          </div>

          <!-- Pending Payments -->
          <div class="bento-card group">
            <div class="flex justify-between items-start mb-3">
              <div class="w-10 h-10 bg-orange-50 text-orange-600 rounded-xl flex items-center justify-center text-base transition-transform group-hover:scale-110">
                <i class="fas fa-hourglass-half"></i>
              </div>
              <a href="request.php" class="text-[12px] font-black text-slate-400 group-hover:text-slate-900 transition-colors tracking-tighter">
                <i class="fas fa-arrow-right"></i> REVIEW
              </a>
            </div>
            <h2 class="text-xl font-black text-slate-800 tracking-tight"><?= formatNaira((float)$pendingTotal) ?></h2>
            <p class="text-[12px] font-bold text-slate-500 uppercase tracking-tight mt-1"><?= (int)$pendingCount ?> pending</p>
            <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">
              <div class="h-full bg-orange-600 opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000"></div>
            </div>
          </div>

          <!-- Grand Total -->
          <div class="bento-card group">
            <div class="flex justify-between items-start mb-3">
              <div class="w-10 h-10 bg-slate-100 text-slate-700 rounded-xl flex items-center justify-center text-base transition-transform group-hover:scale-110">
                <i class="fas fa-calculator"></i>
              </div>
              <span class="text-[11px] font-bold text-slate-400 uppercase tracking-tight">Grand Total</span>
            </div>
            <h2 class="text-xl font-black text-slate-800 tracking-tight"><?= formatNaira((float)$grandTotal) ?></h2>
            <p class="text-[12px] font-bold text-slate-500 uppercase tracking-tight mt-1">All approved methods</p>
            <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">
              <div class="h-full bg-slate-700 opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000"></div>
            </div>
          </div>

          <!-- Reconciliation Variance -->
          <?php
            $varBg      = ($variance == 0) ? 'bg-emerald-50'  : 'bg-rose-50';
            $varText    = ($variance == 0) ? 'text-emerald-600': 'text-rose-600';
            $varBar     = ($variance == 0) ? 'bg-emerald-600'  : 'bg-rose-600';
            $varIcon    = ($variance == 0) ? 'fa-check-circle' : 'fa-exclamation-triangle';
            $varLabel   = ($variance == 0) ? 'Balanced'
                          : formatNaira(abs($variance)) . ' ' . ($variance > 0 ? 'surplus' : 'deficit');
          ?>
          <div class="bento-card group col-span-2 md:col-span-1">
            <div class="flex justify-between items-start mb-3">
              <div class="w-10 h-10 <?= $varBg ?> <?= $varText ?> rounded-xl flex items-center justify-center text-base transition-transform group-hover:scale-110">
                <i class="fas <?= $varIcon ?>"></i>
              </div>
              <span class="text-[11px] font-bold text-slate-400 uppercase tracking-tight">Variance</span>
            </div>
            <h2 class="text-xl font-black <?= $varText ?> tracking-tight" id="varianceCardValue"><?= $varLabel ?></h2>
            <p class="text-[11px] text-slate-400 mt-1" id="varianceCardNote">
              Paystack inflows (<code>payments</code>) vs<br>
              Paystack-method approved (<code>payment</code>)
            </p>
            <div class="mt-4 w-full h-1 bg-slate-200/50 rounded-full overflow-hidden">
              <div class="h-full <?= $varBar ?> opacity-40 w-full transform -translate-x-1/2 group-hover:translate-x-0 transition-transform duration-1000"></div>
            </div>
          </div>

        </div><!-- /.bento grid -->


        <!-- ── Paystack API Records Section ── -->
        <div class="card" id="paystackApiSection">
          <div class="card-header text-white">
            <h5 class="card-title">
              <i class="fas fa-cloud-download-alt"></i> Paystack API Records
            </h5>
            <div class="card-tools">
              <button type="button" class="btn btn-sm btn-primary"
                      id="fetchPaystackBtn" onclick="fetchPaystackData()">
                <i class="fas fa-sync-alt"></i> Refresh from Paystack
              </button>
            </div>
          </div>
          <div class="card-body" id="paystackApiBody">
            <p class="text-muted">
              Click "Fetch from Paystack" to load live transaction data from the
              Paystack API for <?= date('d M Y', strtotime($selectedDate)) ?>.
            </p>
          </div>
        </div><!-- /.card paystack api -->

        <!-- ── Transaction Log ── -->
        <div class="card">
          <div class="card-header text-white">
            <h5 class="card-title"><i class="fas fa-list-alt"></i> Transaction Log</h5>
            <div class="card-tools">
              <?php
              $methods = ['All', 'Paystack', 'Bank Transfer', 'Wallet', 'Other'];
              foreach ($methods as $m):
                $active = ($methodFilter === $m) ? 'btn-primary' : 'btn-outline-primary';
              ?>
              <a href="?date=<?= urlencode($selectedDate) ?>&method=<?= urlencode($m) ?>"
                 class="btn btn-sm <?= $active ?>"><?= htmlspecialchars($m) ?></a>
              <?php endforeach; ?>
            </div>
          </div>
          <div class="card-body table-responsive p-0">
            <?php if ($totalRows === 0): ?>
              <div class="p-4 text-center text-muted">
                <i class="fas fa-inbox fa-2x mb-2"></i><br>
                No transactions found for this date.
              </div>
            <?php else: ?>
            <table class="table table-hover table-striped mb-0">
              <thead class="thead-light">
                <tr>
                  <th>#</th>
                  <th>Student Name</th>
                  <th>ADM No.</th>
                  <th>Fee Type / Purpose</th>
                  <th>Amount (₦)</th>
                  <th>Method / Channel</th>
                  <th>Term</th>
                  <th>Session</th>
                  <th>Date &amp; Time</th>
                </tr>
              </thead>
              <tbody>
                <?php $rowNum = $offset + 1; foreach ($transactions as $tx): ?>
                <tr>
                  <td><?= $rowNum++ ?></td>
                  <td><?= htmlspecialchars($tx['studentName']) ?></td>
                  <td><?= htmlspecialchars($tx['studentno']) ?></td>
                  <td><?= htmlspecialchars($tx['purpose']) ?></td>
                  <td><?= formatNaira((float)$tx['amount']) ?></td>
                  <td><?= htmlspecialchars($tx['channel']) ?></td>
                  <td><?= htmlspecialchars($tx['term']) ?></td>
                  <td><?= htmlspecialchars($tx['session']) ?></td>
                  <td><?= date('d M Y H:i', strtotime($tx['payment_date'])) ?></td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>

            <?php if ($totalPages > 1): ?>
            <div class="p-3">
              <nav aria-label="Transaction log pagination">
                <ul class="pagination pagination-sm mb-0">
                  <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                  <li class="page-item <?= ($p === $page) ? 'active' : '' ?>">
                    <a class="page-link"
                       href="?date=<?= urlencode($selectedDate) ?>&method=<?= urlencode($methodFilter) ?>&page=<?= $p ?>">
                      <?= $p ?>
                    </a>
                  </li>
                  <?php endfor; ?>
                </ul>
              </nav>
            </div>
            <?php endif; ?>

            <?php endif; ?>
          </div>
        </div><!-- /.card transaction log -->

      </div><!-- /.container-fluid -->
    </section><!-- /.content -->
  </div><!-- /.content-wrapper -->

  <?php @include("includes/footer.php"); ?>

</div><!-- /.wrapper -->

<?php @include("includes/foot.php"); ?>


<script>
const selectedDate       = <?= json_encode($selectedDate) ?>;
const localPaystackTotal = <?= json_encode((float)$paystackTotal) ?>;

// ── Helpers ──────────────────────────────────────────────────────────────────
function naira(amount) {
    return '₦' + parseFloat(amount).toLocaleString('en-NG', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}

// ── Auto-fetch Paystack inflows on page load ──────────────────────────────────
document.addEventListener('DOMContentLoaded', function () {
    autoFetchPaystackInflows();
});

function autoFetchPaystackInflows() {
    fetch('api/fetch_paystack_transactions.php', {
        method:  'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body:    'date=' + encodeURIComponent(selectedDate)
    })
    .then(r => r.json())
    .then(data => {
        if (!data.success) {
            document.getElementById('paystackInflowTotal').innerHTML =
                '<span class="text-rose-500 text-sm"><i class="fas fa-exclamation-circle"></i> API Error</span>';
            document.getElementById('paystackInflowCount').textContent = 'Could not load';
            document.getElementById('paystackInflowBreakdown').textContent = data.message || '';
            return;
        }

        // Populate the Paystack Inflows bento card with live API data
        document.getElementById('paystackInflowTotal').textContent = naira(data.api_total_amount_naira);
        document.getElementById('paystackInflowCount').textContent = data.api_total_count + ' transactions (live)';

        let breakdown = '';
        for (const [ch, info] of Object.entries(data.by_channel || {})) {
            const label = ch.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
            breakdown += label + ': ' + naira(info.amount) + ' (' + info.count + ')\n';
        }
        document.getElementById('paystackInflowBreakdown').textContent = breakdown.trim();

        // Update the variance card live
        updateVarianceCard(data.api_total_amount_naira, data.local_paystack_total);

        // Also render the full Paystack API section below
        renderPaystackData(data);
    })
    .catch(() => {
        document.getElementById('paystackInflowTotal').innerHTML =
            '<span class="text-rose-500 text-sm"><i class="fas fa-exclamation-circle"></i> Unavailable</span>';
        document.getElementById('paystackInflowCount').textContent = 'Could not reach Paystack';
    });
}

// ── Update variance card based on live API total ──────────────────────────────
function updateVarianceCard(apiTotal, localTotal) {
    const variance     = apiTotal - localTotal;
    const varianceCard = document.getElementById('varianceCardValue');
    const varianceNote = document.getElementById('varianceCardNote');
    if (!varianceCard) return;

    if (Math.abs(variance) < 0.01) {
        varianceCard.className = 'text-xl font-black text-emerald-600 tracking-tight';
        varianceCard.textContent = 'Balanced';
        if (varianceNote) varianceNote.textContent = 'API total matches local records';
    } else {
        const label = variance > 0 ? 'surplus' : 'deficit';
        varianceCard.className = 'text-xl font-black text-rose-600 tracking-tight';
        varianceCard.textContent = naira(Math.abs(variance)) + ' ' + label;
        if (varianceNote) varianceNote.textContent = 'Paystack API vs local approved (Paystack method)';
    }
}

// ── Manual re-fetch button ────────────────────────────────────────────────────
function fetchPaystackData() {
    const btn  = document.getElementById('fetchPaystackBtn');
    const body = document.getElementById('paystackApiBody');

    btn.disabled    = true;
    btn.innerHTML   = '<i class="fas fa-spinner fa-spin"></i> Fetching...';
    body.innerHTML  = '<p class="text-muted"><i class="fas fa-spinner fa-spin"></i> Loading Paystack records...</p>';

    // Reset inflow card to loading state
    document.getElementById('paystackInflowTotal').innerHTML = '<i class="fas fa-spinner fa-spin text-blue-400"></i>';
    document.getElementById('paystackInflowCount').textContent = 'Loading…';
    document.getElementById('paystackInflowBreakdown').textContent = '';

    fetch('api/fetch_paystack_transactions.php', {
        method:  'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body:    'date=' + encodeURIComponent(selectedDate)
    })
    .then(r => r.json())
    .then(data => {
        btn.disabled  = false;
        btn.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh from Paystack';

        if (!data.success) {
            document.getElementById('paystackInflowTotal').innerHTML =
                '<span class="text-rose-500 text-sm"><i class="fas fa-exclamation-circle"></i> API Error</span>';
            document.getElementById('paystackInflowCount').textContent = 'Could not load';
            body.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> '
                + (data.message || 'Unable to fetch Paystack records. Please try again.') + '</div>';
            return;
        }

        document.getElementById('paystackInflowTotal').textContent = naira(data.api_total_amount_naira);
        document.getElementById('paystackInflowCount').textContent = data.api_total_count + ' transactions (live)';

        let breakdown = '';
        for (const [ch, info] of Object.entries(data.by_channel || {})) {
            const label = ch.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
            breakdown += label + ': ' + naira(info.amount) + ' (' + info.count + ')\n';
        }
        document.getElementById('paystackInflowBreakdown').textContent = breakdown.trim();

        updateVarianceCard(data.api_total_amount_naira, data.local_paystack_total);
        renderPaystackData(data);
    })
    .catch(() => {
        btn.disabled  = false;
        btn.innerHTML = '<i class="fas fa-sync-alt"></i> Refresh from Paystack';
        document.getElementById('paystackInflowTotal').innerHTML =
            '<span class="text-rose-500 text-sm"><i class="fas fa-exclamation-circle"></i> Unavailable</span>';
        document.getElementById('paystackInflowCount').textContent = 'Could not reach Paystack';
        body.innerHTML = '<div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> '
            + 'Unable to fetch Paystack records. Please try again.</div>';
    });
}

// ── Render full Paystack API table section ────────────────────────────────────
function renderPaystackData(data) {
    const varianceLabel = Math.abs(data.api_variance) < 0.01
        ? '<span class="text-success"><i class="fas fa-check-circle"></i> Matched</span>'
        : '<span class="text-danger"><i class="fas fa-exclamation-triangle"></i> Discrepancy: &#8358;'
          + Math.abs(data.api_variance).toLocaleString('en-NG', {minimumFractionDigits: 2}) + '</span>';

    let channelHtml = '';
    for (const [ch, info] of Object.entries(data.by_channel || {})) {
        const label = ch.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
        channelHtml += `<span class="badge badge-secondary mr-1">${label}: &#8358;${info.amount.toLocaleString('en-NG', {minimumFractionDigits: 2})} (${info.count})</span>`;
    }

    let tableRows = '';
    (data.transactions || []).forEach(tx => {
        let rowClass, badge;
        if (tx.match_status === 'matched') {
            rowClass = 'table-success';
            badge    = '<span class="badge badge-success">Matched</span>';
        } else {
            rowClass = 'table-warning';
            badge    = '<span class="badge badge-warning">Missing Locally</span>';
        }
        tableRows += `<tr class="${rowClass}">
            <td>${tx.reference}</td>
            <td>${tx.customer_name || '—'}</td>
            <td>${tx.customer_email}</td>
            <td>&#8358;${parseFloat(tx.amount_naira).toLocaleString('en-NG', {minimumFractionDigits: 2})}</td>
            <td>${tx.status}</td>
            <td>${tx.channel}</td>
            <td>${tx.paid_at}</td>
            <td>${badge}</td>
        </tr>`;
    });

    document.getElementById('paystackApiBody').innerHTML = `
        <div class="row mb-3">
            <div class="col-md-3"><strong>API Total:</strong> &#8358;${data.api_total_amount_naira.toLocaleString('en-NG', {minimumFractionDigits: 2})}</div>
            <div class="col-md-2"><strong>Count:</strong> ${data.api_total_count}</div>
            <div class="col-md-4"><strong>Channels:</strong> ${channelHtml}</div>
            <div class="col-md-3"><strong>Variance vs Local DB:</strong> ${varianceLabel}</div>
        </div>
        <div class="table-responsive">
        <table class="table table-sm table-hover table-bordered">
            <thead class="thead-dark">
                <tr>
                    <th>Reference</th>
                    <th>Customer Name</th>
                    <th>Customer Email</th>
                    <th>Amount (&#8358;)</th>
                    <th>Status</th>
                    <th>Channel</th>
                    <th>Date &amp; Time</th>
                    <th>Match</th>
                </tr>
            </thead>
            <tbody>${tableRows || '<tr><td colspan="8" class="text-center text-muted">No transactions returned by Paystack API.</td></tr>'}</tbody>
        </table>
        </div>`;
}
</script>

</body>
</html>
