<?php

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);

include('includes/dbconnection.php');

require_once __DIR__ . '/includes/session_term_helper.php';
// Fetch current session and term (with gap/fallback support)
$stResult = resolveCurrentSessionTerm($con);
$currentSessionId   = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId      = $stResult['term_id'];
$currentTermName    = $stResult['term_name'];


if (strlen($_SESSION['sid'] == 0)) {

    header('location:logout.php');

    exit;

}

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;

use Dotenv\Dotenv;



require 'phpmailer/src/Exception.php';

require 'phpmailer/src/PHPMailer.php';

require 'phpmailer/src/SMTP.php';

require_once 'vendor/autoload.php';



$dotenv = Dotenv::createImmutable(__DIR__);

$dotenv->load();



// --- FILTERS & PAGINATION ---

$limit  = 25;

$page   = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;

$offset = ($page - 1) * $limit;



$search     = isset($_GET['search'])   ? trim($_GET['search'])   : '';

$filter_type = isset($_GET['type'])    ? trim($_GET['type'])     : '';

$filter_date = isset($_GET['date'])    ? trim($_GET['date'])     : '';



// --- BUILD WHERE ---

$where_parts = [];

$params      = [];

$types       = "";



if (!empty($search)) {

    $where_parts[] = "(s.studentName LIKE ? OR s.studentno LIKE ? OR wt.reference LIKE ?)";

    $st = "%$search%";

    $params[] = $st; $params[] = $st; $params[] = $st;

    $types .= "sss";

}

if (!empty($filter_type)) {

    $where_parts[] = "wt.type LIKE ?";

    $params[] = "%$filter_type%";

    $types .= "s";

}

if (!empty($filter_date)) {

    $where_parts[] = "DATE(wt.created_at) = ?";

    $params[] = $filter_date;

    $types .= "s";

}



$where_sql = count($where_parts) ? " WHERE " . implode(" AND ", $where_parts) : "";



// --- CSV EXPORT ---

if (isset($_GET['export']) && $_GET['export'] === 'csv') {

    $export_params  = $params;

    $export_types   = $types;

    $export_params[] = PHP_INT_MAX; // no real limit

    $export_params[] = 0;

    $export_stmt = $con->prepare(

        "SELECT wt.id, s.studentName, s.studentno, wt.reference, wt.type, wt.amount, wt.status, wt.notes, wt.created_at

         FROM wallet_transactions wt LEFT JOIN students s ON wt.student_id = s.id

         $where_sql ORDER BY wt.created_at DESC LIMIT ? OFFSET ?"

    );

    if (!$export_stmt) { die("Export failed: " . $con->error); }

    $export_stmt->bind_param($export_types . "ii", ...$export_params);

    $export_stmt->execute();

    $export_result = $export_stmt->get_result();



    $filename = 'wallet_logs_' . date('Y-m-d') . '.csv';

    header('Content-Type: text/csv; charset=utf-8');

    header('Content-Disposition: attachment; filename="' . $filename . '"');

    $out = fopen('php://output', 'w');

    fputcsv($out, ['Transaction ID', 'Student Name', 'ADM Number', 'Reference', 'Type', 'Amount', 'Status', 'Notes', 'Date']);

    while ($row = $export_result->fetch_assoc()) {

        fputcsv($out, [

            $row['id'],

            $row['studentName'] ?? '',

            $row['studentno']   ?? '',

            $row['reference'],

            $row['type'],

            $row['amount'],

            $row['status'],

            $row['notes'] ?? '',

            date('d M Y, h:i A', strtotime($row['created_at'])),

        ]);

    }

    fclose($out);

    exit;

}



// --- PDF EXPORT ---

if (isset($_GET['export']) && $_GET['export'] === 'pdf') {

    require_once 'vendor/autoload.php';



    $pdf_params = $params;

    $pdf_types  = $types;



    $pdf_sql = "SELECT wt.id, s.studentName, s.studentno, wt.reference, wt.type, wt.amount, wt.status, wt.notes, wt.created_at

                FROM wallet_transactions wt LEFT JOIN students s ON wt.student_id = s.id

                $where_sql ORDER BY wt.created_at DESC";



    if (!empty($pdf_params)) {

        $pdf_stmt = $con->prepare($pdf_sql);

        if (!$pdf_stmt) { die("Export failed: " . $con->error); }

        $pdf_stmt->bind_param($pdf_types, ...$pdf_params);

        $pdf_stmt->execute();

        $pdf_result = $pdf_stmt->get_result();

    } else {

        $pdf_result = $con->query($pdf_sql);

    }



    // Summary stats for footer

    $pdf_summary = $con->query(

        "SELECT

            SUM(CASE WHEN type='deposit' AND status='success' THEN amount ELSE 0 END) as total_deposits,

            SUM(CASE WHEN type LIKE 'Wallet Payment%' AND status='success' THEN amount ELSE 0 END) as total_payments,

            COUNT(*) as total_txns

         FROM wallet_transactions"

    )->fetch_assoc();



    $school_name = $_ENV['SCHOOL_NAME'] ?? 'School Portal';

    $gen_date    = date('d M Y, h:i A');

    // Active filter summary

    $filter_parts = [];

    if (!empty($search))      $filter_parts[] = 'Search: ' . htmlspecialchars($search);

    if (!empty($filter_type)) $filter_parts[] = 'Type: '   . htmlspecialchars($filter_type);

    if (!empty($filter_date)) $filter_parts[] = 'Date: '   . htmlspecialchars($filter_date);

    $filter_summary = $filter_parts ? implode(' | ', $filter_parts) : 'None';



    // Build table rows

    $rows_html = '';

    $has_rows  = false;

    while ($row = $pdf_result->fetch_assoc()) {

        $has_rows   = true;

        $is_credit  = ($row['type'] === 'deposit');

        $amt_color  = $is_credit ? '#059669' : '#dc2626';

        $amt_prefix = $is_credit ? '+' : '-';

        $rows_html .= '<tr>

            <td>' . (int)$row['id'] . '</td>

            <td>' . htmlspecialchars($row['studentName'] ?? 'N/A') . '</td>

            <td>' . htmlspecialchars($row['studentno'] ?? '') . '</td>

            <td><code>' . htmlspecialchars($row['reference']) . '</code></td>

            <td>' . htmlspecialchars($row['type']) . '</td>

            <td style="color:' . $amt_color . ';font-weight:700;">' . $amt_prefix . '&#8358;' . number_format((float)$row['amount'], 2) . '</td>

            <td>' . ucfirst(htmlspecialchars($row['status'])) . '</td>

            <td style="font-size:10px;">' . htmlspecialchars($row['notes'] ?? '—') . '</td>

            <td style="white-space:nowrap;">' . date('d M Y, h:i A', strtotime($row['created_at'])) . '</td>

        </tr>';

    }



    if (!$has_rows) {

        $rows_html = '<tr><td colspan="9" style="text-align:center;padding:20px;color:#94a3b8;">No records found.</td></tr>';

    }



    $html = '<!DOCTYPE html><html><head><meta charset="UTF-8">

    <style>

        body { font-family: DejaVu Sans, sans-serif; font-size: 11px; color: #1e293b; }

        .header { background: #1e293b; color: #fff; padding: 16px 20px; border-radius: 8px; margin-bottom: 16px; }

        .header h1 { margin: 0 0 4px; font-size: 18px; }

        .header p  { margin: 2px 0; font-size: 10px; color: #94a3b8; }

        table { width: 100%; border-collapse: collapse; margin-top: 10px; }

        thead th { background: #f1f5f9; color: #475569; font-size: 9px; text-transform: uppercase; padding: 7px 6px; border-bottom: 2px solid #e2e8f0; text-align: left; }

        tbody td { padding: 6px 6px; border-bottom: 1px solid #f1f5f9; font-size: 10px; vertical-align: top; }

        tbody tr:nth-child(even) td { background: #f8fafc; }

        .footer { margin-top: 20px; padding: 12px 16px; background: #f8fafc; border-top: 2px solid #e2e8f0; border-radius: 6px; font-size: 10px; color: #475569; }

        .footer span { margin-right: 24px; }

        code { background: #f1f5f9; padding: 1px 4px; border-radius: 3px; font-size: 9px; }

    </style>

    </head><body>

    <div class="header">

        <h1>' . htmlspecialchars($school_name) . ' — Wallet Transaction Log</h1>

        <p>Generated: ' . $gen_date . '</p>

        <p>Filters: ' . $filter_summary . '</p>

    </div>

    <table>

        <thead>

            <tr>

                <th>ID</th><th>Student Name</th><th>ADM No</th><th>Reference</th>

                <th>Type</th><th>Amount</th><th>Status</th><th>Notes</th><th>Date</th>

            </tr>

        </thead>

        <tbody>' . $rows_html . '</tbody>

    </table>

    <div class="footer">

        <span><strong>Total Transactions:</strong> ' . number_format((int)($pdf_summary['total_txns'] ?? 0)) . '</span>

        <span><strong>Total Deposits:</strong> &#8358;' . number_format((float)($pdf_summary['total_deposits'] ?? 0), 2) . '</span>

        <span><strong>Total Payments:</strong> &#8358;' . number_format((float)($pdf_summary['total_payments'] ?? 0), 2) . '</span>

    </div>

    </body></html>';



    try {

        $mpdf = new \Mpdf\Mpdf([

            'margin_top'    => 10,

            'margin_bottom' => 10,

            'margin_left'   => 10,

            'margin_right'  => 10,

            'orientation'   => 'L',

        ]);

        $mpdf->WriteHTML($html);

        $mpdf->Output('wallet_logs_' . date('Y-m-d') . '.pdf', 'D');

    } catch (\Mpdf\MpdfException $e) {

        echo '<p style="color:red;font-family:sans-serif;">PDF generation failed: ' . htmlspecialchars($e->getMessage()) . '</p>';

    }

    exit;

}



$base = "FROM wallet_transactions wt LEFT JOIN students s ON wt.student_id = s.id";



// Total count

$count_stmt = $con->prepare("SELECT COUNT(*) as total $base $where_sql");

if (!empty($params)) $count_stmt->bind_param($types, ...$params);

$count_stmt->execute();

$total_rows  = $count_stmt->get_result()->fetch_assoc()['total'];

$total_pages = ceil($total_rows / $limit);



// Data

$data_params  = $params;

$data_types   = $types . "ii";

$data_params[] = $limit;

$data_params[] = $offset;



$data_stmt = $con->prepare(

    "SELECT wt.*, s.studentName, s.studentno, s.class, s.section

     $base $where_sql ORDER BY wt.created_at DESC LIMIT ? OFFSET ?"

);

$data_stmt->bind_param($data_types, ...$data_params);

$data_stmt->execute();

$result = $data_stmt->get_result();



// --- SUMMARY STATS ---

$summary = $con->query(

    "SELECT

        SUM(CASE WHEN type='deposit' AND status='success' THEN amount ELSE 0 END) as total_deposits,

        SUM(CASE WHEN type LIKE 'Wallet Payment%' AND status='success' THEN amount ELSE 0 END) as total_payments,

        COUNT(*) as total_txns

     FROM wallet_transactions"

)->fetch_assoc();



// Distinct types for filter dropdown

$types_res = $con->query("SELECT DISTINCT type FROM wallet_transactions ORDER BY type ASC");

?>

<!DOCTYPE html>

<html lang="en">

<head>

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



    <style>

        .bento-card { @apply bg-white p-5 rounded-3xl border border-slate-100 shadow-sm hover:shadow-xl hover:border-blue-100 transition-all duration-300; }

        .pagination .page-item.active .page-link { background-color: #3b82f6 !important; border-color: #3b82f6 !important; color: white !important; }

        .page-link { color: #64748b; border-radius: 8px !important; margin: 0 2px; }

    </style>

</head>

<body class="hold-transition sidebar-mini layout-fixed">

<div class="wrapper">

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

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



    <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-wallet"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Wallet Management

                                <span class="premium-subtitle text-secondary">Audit Trail</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"><a href="manage_wallet.php" class="text-primary">Wallet Manager</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Logs</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section> 



        <section class="content">

            <div class="container-fluid">

                <div class="row">

                    <div class="col-md-12">

                        <div class="card card-primary">

                            <div class="card-header">

                                <h5 class="card-title font-weight-bold">

                                    <i class="fas fa-history"></i> Transaction Audit Trail

                                </h5>

                            </div>

                            <div class="card-body">



                                <!-- Summary Stats -->

                                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">

                                    <div class="bento-card flex items-center gap-4">

                                        <div class="w-12 h-12 bg-slate-100 text-slate-500 rounded-2xl flex items-center justify-center text-xl flex-shrink-0">

                                            <i class="fas fa-list-alt"></i>

                                        </div>

                                        <div>

                                            <p class="text-xs font-bold uppercase text-slate-400 tracking-widest">Total Transactions</p>

                                            <h3 class="text-2xl font-black text-slate-800 mt-0.5"><?php echo number_format($summary['total_txns']); ?></h3>

                                        </div>

                                    </div>

                                    <div class="bento-card flex items-center gap-4">

                                        <div class="w-12 h-12 bg-emerald-50 text-emerald-500 rounded-2xl flex items-center justify-center text-xl flex-shrink-0">

                                            <i class="fas fa-arrow-down"></i>

                                        </div>

                                        <div>

                                            <p class="text-xs font-bold uppercase text-emerald-500 tracking-widest">Total Deposits</p>

                                            <h3 class="text-2xl font-black text-emerald-600 mt-0.5">₦<?php echo number_format($summary['total_deposits'] ?? 0, 2); ?></h3>

                                        </div>

                                    </div>

                                    <div class="bento-card flex items-center gap-4">

                                        <div class="w-12 h-12 bg-rose-50 text-rose-500 rounded-2xl flex items-center justify-center text-xl flex-shrink-0">

                                            <i class="fas fa-arrow-up"></i>

                                        </div>

                                        <div>

                                            <p class="text-xs font-bold uppercase text-rose-500 tracking-widest">Total Payments</p>

                                            <h3 class="text-2xl font-black text-rose-600 mt-0.5">₦<?php echo number_format($summary['total_payments'] ?? 0, 2); ?></h3>

                                        </div>

                                    </div>

                                </div>



                                <!-- Filters -->

                                <div class="card card-outline card-primary shadow-sm rounded-2xl overflow-hidden border-0 mb-4">

                                    <div class="card-header text-white py-3 d-flex justify-content-between align-items-center">

                                        <h3 class="card-title font-weight-bold mb-0"><i class="fas fa-filter text-primary mr-2"></i> Filter Transactions</h3>

                                        <a href="wallet_logs.php?export=pdf&search=<?php echo urlencode($search); ?>&type=<?php echo urlencode($filter_type); ?>&date=<?php echo urlencode($filter_date); ?>"

                                           class="btn btn-sm btn-danger rounded-lg">

                                            <i class="fas fa-file-pdf mr-1"></i> Export PDF

                                        </a>

                                    </div>

                                    <div class="card-body">

                                        <form method="GET" class="row g-2 align-items-end">

                                            <div class="col-md-4">

                                                <label class="text-xs font-bold text-slate-500 uppercase mb-1 d-block">Search</label>

                                                <div class="input-group input-group-sm">

                                                    <div class="input-group-prepend">

                                                        <span class="input-group-text bg-slate-50 border-slate-200"><i class="fas fa-search text-slate-400"></i></span>

                                                    </div>

                                                    <input type="text" name="search" class="form-control border-slate-200" placeholder="Name, ADM No, Reference..." value="<?php echo htmlspecialchars($search); ?>">

                                                </div>

                                            </div>

                                            <div class="col-md-4">

                                                <label class="text-xs font-bold text-slate-500 uppercase mb-1 d-block">Type</label>

                                                <select name="type"  id="type" class="form-control  border-slate-200">

                                                    <option value="">All Types</option>

                                                    <?php while ($t = $types_res->fetch_assoc()): ?>

                                                        <option value="<?php echo htmlspecialchars($t['type']); ?>" <?php if($filter_type === $t['type']) echo 'selected'; ?>>

                                                            <?php echo htmlspecialchars($t['type']); ?>

                                                        </option>

                                                    <?php endwhile; ?>

                                                </select>

                                            </div>

                                            <div class="col-md-4">

                                                <label class="text-xs font-bold text-slate-500 uppercase mb-1 d-block">Date</label>

                                                <input type="date" name="date" class="form-control  border-slate-200" value="<?php echo htmlspecialchars($filter_date); ?>">

                                            </div>

                                            <div class="col-md-4 d-flex mt-2">

                                                <button type="submit" class="btn btn-primary btn-sm rounded-lg flex-fill"><i class="fas fa-search mr-1"></i> Filter</button>

                                                <a href="wallet_logs.php" class="btn btn-outline-secondary btn-sm rounded-lg" title="Clear filters"><i class="fas fa-times"></i></a>

                                            </div>

                                        </form>

                                    </div>

                                </div>



                                <!-- Table -->

                                <div class="card card-outline card-primary shadow-sm rounded-2xl overflow-hidden border-0 mt-4">

                                    <div class="card-body p-0">

                                        <div class="table-responsive">

                                            <table class="table table-hover align-middle mb-0">

                                                <thead class="bg-slate-50 text-slate-500 uppercase text-xs">

                                                    <tr>

                                                        <th class="px-4 py-3">#</th>

                                                        <th>Student</th>

                                                        <th>Reference</th>

                                                        <th>Type</th>

                                                        <th>Amount</th>

                                                        <th>Status</th>

                                                        <th>Notes</th>

                                                        <th>Date</th>

                                                    </tr>

                                                </thead>

                                                <tbody>

                                                    <?php $sn = $offset + 1; while ($row = $result->fetch_assoc()):

                                                        $is_credit = ($row['type'] === 'deposit');

                                                        $status_class = match($row['status']) {

                                                            'success' => 'badge-success',

                                                            'pending' => 'badge-warning',

                                                            default   => 'badge-danger'

                                                        };

                                                    ?>

                                                    <tr>

                                                        <td class="px-4 text-muted text-xs"><?php echo $sn++; ?></td>

                                                        <td>

                                                            <a href="wallet_history.php?id=<?php echo (int)$row['student_id']; ?>" class="font-bold text-dark text-sm hover:text-blue-600 d-block"><?php echo htmlspecialchars($row['studentName'] ?? 'N/A'); ?></a>

                                                            <div class="text-xs text-muted"><?php echo htmlspecialchars($row['studentno'] ?? ''); ?></div>

                                                        </td>

                                                        <td><code class="text-xs bg-slate-100 px-2 py-1 rounded"><?php echo htmlspecialchars($row['reference']); ?></code></td>

                                                        <td>

                                                            <span class="badge <?php echo $is_credit ? 'badge-light border border-emerald-200 text-emerald-700' : 'badge-light border border-rose-200 text-rose-700'; ?> text-xs">

                                                                <i class="fas <?php echo $is_credit ? 'fa-arrow-down' : 'fa-arrow-up'; ?> mr-1"></i>

                                                                <?php echo htmlspecialchars($row['type']); ?>

                                                            </span>

                                                        </td>

                                                        <td>

                                                            <span class="font-bold <?php echo $is_credit ? 'text-emerald-600' : 'text-rose-600'; ?>">

                                                                <?php echo $is_credit ? '+' : '-'; ?>₦<?php echo number_format($row['amount'], 2); ?>

                                                            </span>

                                                        </td>

                                                        <td><span class="badge <?php echo $status_class; ?>"><?php echo ucfirst($row['status']); ?></span></td>

                                                        <td class="text-xs text-muted" style="max-width:180px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="<?php echo htmlspecialchars($row['notes'] ?? ''); ?>">

                                                            <?php echo htmlspecialchars($row['notes'] ?? '—'); ?>

                                                        </td>

                                                        <td class="text-xs text-muted"><?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?></td>

                                                    </tr>

                                                    <?php endwhile; ?>

                                                    <?php if ($total_rows == 0): ?>

                                                        <tr><td colspan="8" class="text-center py-5 text-muted">No transactions found.</td></tr>

                                                    <?php endif; ?>

                                                </tbody>

                                            </table>

                                        </div>

                                    </div>

                                    <div class="card-footer bg-white py-3">

                                        <div class="d-flex justify-content-between align-items-center">

                                            <div class="text-xs text-slate-500">

                                                Showing <?php echo $total_rows > 0 ? ($offset + 1) : 0; ?> to <?php echo min($offset + $limit, $total_rows); ?> of <?php echo $total_rows; ?> records

                                            </div>

                                            <nav>

                                                <ul class="pagination pagination-sm mb-0">

                                                    <li class="page-item <?php if($page <= 1) echo 'disabled'; ?>">

                                                        <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&type=<?php echo urlencode($filter_type); ?>&date=<?php echo urlencode($filter_date); ?>">Prev</a>

                                                    </li>

                                                    <?php for($i = max(1,$page-2); $i <= min($total_pages,$page+2); $i++): ?>

                                                        <li class="page-item <?php echo ($page==$i)?'active':''; ?>">

                                                            <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&type=<?php echo urlencode($filter_type); ?>&date=<?php echo urlencode($filter_date); ?>"><?php echo $i; ?></a>

                                                        </li>

                                                    <?php endfor; ?>

                                                    <li class="page-item <?php if($page >= $total_pages) echo 'disabled'; ?>">

                                                        <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&type=<?php echo urlencode($filter_type); ?>&date=<?php echo urlencode($filter_date); ?>">Next</a>

                                                    </li>

                                                </ul>

                                            </nav>

                                        </div>

                                    </div>

                                </div>



                            </div><!-- /.card-body -->

                        </div><!-- /.card -->

                    </div>

                </div>

            </div>

        </section>

    </div>


    <script>
        $(document).ready(function () {
            $('#type').select2({
                allowClear: true,
                placeholder: '-- Select Type --'
            });
        });
    </script>
    <?php @include("includes/footer.php"); ?>

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

</div>

</body>

</html>

