<?php
$student_id = $_SESSION['student'];

$query = "
    SELECT students.*, role.role_name 
    FROM students 
    JOIN role ON students.role = role.id 
    WHERE students.id = ?
";
$stmt = $connection->prepare($query);
$stmt->bind_param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows === 1) {
    $student = $result->fetch_assoc();
    $reg_number = $student['reg_number'];
    $student_class = $student['class'];
} else {
    $_SESSION['msg'] = "Student not found.";
    $_SESSION['type'] = "danger";
    header("Location: ../login.php");
    exit;
}
$stmt->close();

$sql = "
SELECT 
  fp.fee_session, fp.fee_term,
  SUM(fp.amount_paid) AS total_paid,
  MAX(fp.date_of_upload) AS last_payment_date,
  MAX(fp.teller_no) AS last_teller,
  MAX(fp.payment_status) AS last_status,
  fs.amount AS expected_fee
FROM fee_payment fp
JOIN fee_structure fs ON fs.class = ? AND fs.session = fp.fee_session AND fs.term = fp.fee_term
WHERE fp.reg_number = ?
GROUP BY fp.fee_session, fp.fee_term
ORDER BY last_payment_date DESC
";

$stmt = $connection->prepare($sql);
$stmt->bind_param("ss", $student_class, $reg_number);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
  $_SESSION['msg'] = "No payment history found for your account.";
  $_SESSION['type'] = "danger";
}
?>

<style>
  .form-inline .form-control {
    min-width: 180px;
  }
  .table th,
  .table td {
    vertical-align: middle !important;
  }
</style>

<div class="page-title">
  <div>
    <h1><i class="fa fa-money"></i> My Fee Payment History</h1>
    <p>Records of your past payments</p>
  </div>  
</div>

<?php if (!empty($_SESSION['msg'])): ?>
  <div class="alert alert-<?= $_SESSION['type'] ?>">
    <?= $_SESSION['msg'] ?>
  </div>
  <?php unset($_SESSION['msg'], $_SESSION['type']); ?>
<?php endif; ?>

<div class="card">
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h4 class="text-center">My Payment History</h4>
    </div>
    <div class="panel-body table-responsive">
      <table class="table table-bordered table-striped mb-0">
        <thead class="thead-light text-center">
          <tr>
            <th>Session</th>
            <th>Term</th>
            <th>Expected Fee (₦)</th>
            <th>Total Paid (₦)</th>
            <th>Balance (₦)</th>
            <th>Last Teller</th>
            <th>Last Payment Date</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <?php while ($row = $result->fetch_assoc()):
            $expected = $row['expected_fee'];
            $paid = $row['total_paid'];
            $balance = $expected - $paid;
          ?>
          <tr class="text-center">
            <td><?= $row['fee_session'] ?></td>
            <td><?= $row['fee_term'] ?></td>
            <td><b>₦<?= number_format($expected, 2) ?></b></td>
            <td class="text-success">₦<?= number_format($paid, 2) ?></td>
            <td class="<?= $balance > 1000 ? 'text-danger' : 'text-success' ?>">₦<?= number_format($balance, 2) ?></td>
            <td><?= $row['last_teller'] ?></td>
            <td><?= $row['last_payment_date'] ?></td>
            <td>
              <?= $row['last_status'] === 'Cleared'
                ? "<span class='badge badge-success'>Cleared</span>"
                : "<span class='badge badge-warning'>Pending</span>" ?>
            </td>
          </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
    <?php
    $invoice_sql = "
        SELECT * FROM inventory_invoices 
        WHERE reg_number = ? 
        ORDER BY issued_at DESC
    ";
    $invoice_stmt = $connection->prepare($invoice_sql);
    $invoice_stmt->bind_param("s", $reg_number);
    $invoice_stmt->execute();
    $invoice_result = $invoice_stmt->get_result();
    ?>
    
    <div class="card mt-4">
      <div class="panel panel-info">
        <div class="panel-heading">
          <h4 class="text-center">My Invoice Records</h4>
        </div>
        <div class="panel-body table-responsive">
          <table class="table table-bordered table-striped mb-0">
            <thead class="thead-light text-center">
              <tr>
                <th>Invoice No</th>
                <th>Class</th>
                <th>Total Amount (₦)</th>
                <th>Paid (₦)</th>
                <th>Balance</th>
                <th>Issued At</th>
                <th>View</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($invoice_result->num_rows > 0): ?>
                <?php while ($invoice = $invoice_result->fetch_assoc()): 
                  $total = floatval($invoice['total_amount']);
                  $paid = floatval($invoice['amount_paid']);
                  $balance = $total - $paid;
                  ?>
                  <tr class="text-center">
                    <td><?= htmlspecialchars($invoice['invoice_no']) ?></td>
                    <td><?= htmlspecialchars($invoice['student_class']) ?></td>
                    <td>₦<?= number_format($total, 2) ?></td>
                    <td>₦<?= number_format($paid, 2) ?></td>
                    <td>
                      <?= ($balance <= 0) 
                          ? "<span class='badge badge-success'>Cleared</span>" 
                          : "₦" . number_format($balance, 2) ?>
                    </td>
                    <td><?= date('Y-m-d H:i', strtotime($invoice['issued_at'])) ?></td>
                    <td>
                      <form onsubmit="openInvoiceAndRedirect(event, <?= $invoice['id'] ?>)">
                        <button type="submit" class="btn btn-sm btn-primary">Print</button>
                      </form>
                    </td>
                    
                    <script>
                      function openInvoiceAndRedirect(event, invoiceId) {
                        event.preventDefault(); // Prevent actual form submission
                        window.open('print_invoice.php?invoice_id=' + invoiceId, '_blank'); // Open PDF in new tab
                        window.location.href = 'view_my_payment'; // Redirect current page
                      }
                    </script>
                  </tr>
                <?php endwhile; ?>
              <?php else: ?>
                <tr>
                  <td colspan="7" class="text-center text-muted">No invoice records found.</td>
                </tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

