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

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;

}



$student_id = isset($_GET['id']) ? (int) $_GET['id'] : null;



// --- Pagination Configuration ---

$limit = 20; // Results per page

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

if ($page < 1)
  $page = 1;

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



// 1. Get total records for pagination calculation

$count_query = "SELECT COUNT(*) as total FROM wallet_transactions";

if ($student_id) {

  $count_query .= " WHERE student_id = ?";

}

$stmt_count = $con->prepare($count_query);

if ($student_id) {

  $stmt_count->bind_param("i", $student_id);

}

$stmt_count->execute();

$total_results = $stmt_count->get_result()->fetch_assoc()['total'];

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



// 2. Optimized Query with LIMIT and OFFSET

$query_str = "SELECT t.*, s.studentName, s.studentno 

              FROM wallet_transactions t 

              LEFT JOIN students s ON t.student_id = s.id";



if ($student_id) {

  $query_str .= " WHERE t.student_id = ? ";

}

$query_str .= " ORDER BY t.id DESC LIMIT ? OFFSET ?";



$stmt = $con->prepare($query_str);

if ($student_id) {

  // "iii" stands for integer student_id, integer limit, integer offset

  $stmt->bind_param("iii", $student_id, $limit, $offset);

} else {

  // "ii" stands for integer limit, integer offset

  $stmt->bind_param("ii", $limit, $offset);

}

$stmt->execute();

$transactions = $stmt->get_result();



// Counter starts based on the current page offset

$counter = $offset + 1;

?>



<!DOCTYPE html>

<html>

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



    <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">

                      Payment Management

                      <span class="premium-subtitle text-secondary">Wallet & History</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">Wallet History</li>

                  </ol>

                </nav>

              </div>

            </div>

          </div>

        </div>

      </section>



      <section class="content">

        <div class="container-fluid">

          <div class="row">

            <div class="col-12">

              <div class="card card-primary">

                <div class="card-header">

                  <h3 class="card-title"> <i class="fas fa-history"></i> Recent Payment</h3>

                  <div class="card-tools">

                    <a href="view_wallet_payment.php">

                      <button type="button" class="btn btn-sm btn-primary">

                        <span style="color: #fff;"><i class="fas fa-wallet"></i> Wallet Payment</span>

                      </button>

                    </a>

                  </div>

                </div>



                <div class="card-body mt-2">

                  <table id="example1" class="table table-bordered table-hover">

                    <thead>

                      <tr>

                        <th>#</th>

                        <th>Date/Time</th>

                        <th>Student</th>

                        <th>Type</th>

                        <th>Reference</th>

                        <th>Amount</th>

                        <th>Status</th>

                      </tr>

                    </thead>

                    <tbody class="text-sm">

                      <?php while ($row = $transactions->fetch_assoc()) {

                        $is_credit = in_array($row['type'], ['deposit', 'refund', 'credit', 'Transfer In', 'Payment(Transfer In)']);

                        $amt_color = $is_credit ? 'text-emerald-600' : 'text-red-600';

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

                        ?>

                        <tr>

                          <td class="text-muted"><?php echo $counter++; ?></td>

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

                          <td>

                            <div class="font-bold"><?php echo htmlspecialchars($row['studentName'] ?? 'N/A'); ?></div>

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

                          </td>

                          <td><span class="badge badge-light border uppercase"><?php echo $row['type']; ?></span></td>

                          <td class="text-xs font-mono text-slate-500"><?php echo $row['reference'] ?? 'N/A'; ?></td>

                          <td class="font-bold <?php echo $amt_color; ?>">

                            <?php echo $prefix; ?>₦<?php echo number_format($row['amount'], 2); ?>

                          </td>

                          <td>

                            <span
                              class="px-2 py-1 rounded-full text-[10px] font-bold <?php echo $row['status'] == 'success' ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'; ?>">

                              <?php echo strtoupper($row['status']); ?>

                            </span>

                          </td>

                        </tr>

                      <?php } ?>

                    </tbody>

                  </table>



                  <div
                    class="flex items-center justify-between border-t border-gray-200 bg-white px-4 py-3 sm:px-6 mt-4">

                    <div class="flex flex-1 justify-between sm:hidden">

                      <a href="?page=<?php echo max(1, $page - 1); ?><?php echo $student_id ? '&id=' . $student_id : ''; ?>"
                        class="relative inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">Previous</a>

                      <a href="?page=<?php echo min($total_pages, $page + 1); ?><?php echo $student_id ? '&id=' . $student_id : ''; ?>"
                        class="relative ml-3 inline-flex items-center rounded-md border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">Next</a>

                    </div>

                    <div class="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">

                      <div>

                        <p class="text-sm text-gray-700">

                          Showing <span class="font-medium"><?php echo ($total_results > 0) ? $offset + 1 : 0; ?></span>
                          to

                          <span class="font-medium"><?php echo min($offset + $limit, $total_results); ?></span> of

                          <span class="font-medium"><?php echo $total_results; ?></span> results

                        </p>

                      </div>

                      <div>

                        <nav class="isolate inline-flex -space-x-px rounded-md shadow-sm" aria-label="Pagination">

                          <a href="?page=<?php echo max(1, $page - 1); ?><?php echo $student_id ? '&id=' . $student_id : ''; ?>"
                            class="relative inline-flex items-center rounded-l-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">

                            <i class="fas fa-chevron-left"></i>

                          </a>



                          <?php

                          // Simple page number loop
                          
                          for ($i = 1; $i <= $total_pages; $i++):

                            $activeClass = ($i == $page) ? 'z-10 bg-blue-600 text-white' : 'text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50';

                            ?>

                            <a href="?page=<?php echo $i; ?><?php echo $student_id ? '&id=' . $student_id : ''; ?>"
                              class="relative inline-flex items-center px-4 py-2 text-sm font-semibold <?php echo $activeClass; ?>">

                              <?php echo $i; ?>

                            </a>

                          <?php endfor; ?>



                          <a href="?page=<?php echo min($total_pages, $page + 1); ?><?php echo $student_id ? '&id=' . $student_id : ''; ?>"
                            class="relative inline-flex items-center rounded-r-md px-2 py-2 text-gray-400 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:z-20 focus:outline-offset-0">

                            <i class="fas fa-chevron-right"></i>

                          </a>

                        </nav>

                      </div>

                    </div>

                  </div>

                </div>

              </div>

            </div>

          </div>

        </div>

      </section>

    </div>

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

  </div>

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

</body>

</html>