<?php
// /user/portal_blocked.php
// allow this page to load even if portal is blocked
$ALLOW_BLOCKED = true;

require_once __DIR__ . '/_user_auth.php';
require_once __DIR__ . '/_user_layout.php';

// Optional flash from redirect: ?reason=UNPAID or ?msg=
$reason  = $_GET['reason'] ?? '';
$flash   = $_GET['msg'] ?? '';

// Load student basic
$sq = mysqli_query($conn, "SELECT full_name, cnic, contact_number, email FROM students WHERE id={$student_id} LIMIT 1");
$me = mysqli_fetch_assoc($sq);

// Latest registration
$reg = null;
$regQ = mysqli_query($conn, "
  SELECT r.id, r.reg_no, r.fee_status, r.approved_at,
         c.id AS course_id, c.name AS course, c.fee_type, c.course_fee, c.monthly_fee
  FROM registrations r
  JOIN courses c ON c.id=r.course_id
  WHERE r.student_id={$student_id}
  ORDER BY r.approved_at DESC
  LIMIT 1
");
if ($regQ) $reg = mysqli_fetch_assoc($regQ);

// Latest fee snapshot (from fee_payments)
$snap = null;
if ($reg && $reg['course_id']) {
  $snapQ = mysqli_query($conn, "
    SELECT total_fee, paid_amount, discount, extra_charges, status, updated_at
    FROM fee_payments
    WHERE student_id={$student_id} AND course_id=".(int)$reg['course_id']."
    ORDER BY updated_at DESC
    LIMIT 1
  ");
  if ($snapQ) $snap = mysqli_fetch_assoc($snapQ);
}

// Try to read portal policy row (to show grace date if set)
$pol = mysqli_query($conn, "
  SELECT policy, grace_until, note
  FROM student_portal_access
  WHERE student_id={$student_id}
  LIMIT 1
");
$policy = null;
if ($pol) $policy = mysqli_fetch_assoc($pol);

// Try to show last few payments (if history table exists)
$has_history = false;
$hist = [];
$chk = mysqli_query($conn, "
  SELECT COUNT(*) AS n
  FROM INFORMATION_SCHEMA.TABLES
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'fee_payments_history'
");
if ($chk && (int)mysqli_fetch_assoc($chk)['n'] > 0 && $reg) {
  $hQ = mysqli_query($conn, "
    SELECT paid_on, amount, method, ref_no, note
    FROM fee_payments_history
    WHERE student_id={$student_id} AND course_id=".(int)$reg['course_id']."
    ORDER BY paid_on DESC
    LIMIT 5
  ");
  while ($hQ && $row = mysqli_fetch_assoc($hQ)) { $hist[] = $row; }
  if (!empty($hist)) $has_history = true;
}

user_header('Portal Access Blocked');
?>
<style>
  .hero {
    background: linear-gradient(135deg, #eff6ff, #ffffff);
    border: 1px solid #bfdbfe;
    border-radius: 14px; padding: 18px;
    display:flex; gap:14px; align-items:center;
  }
  .mark {
    width: 56px; height:56px; border-radius:12px;
    background:#fee2e2; border:1px solid #fecaca;
    display:flex; align-items:center; justify-content:center;
    color:#b91c1c; font-size:24px; font-weight:900;
  }
  .kpi { text-align:center; background:#fff; border:1px solid #e5e7eb; border-radius:12px; padding:14px }
  .kpi .label{font-size:12px; color:#64748b}
  .kpi .val{margin-top:6px;font-size:20px;font-weight:800}
  .badge{padding:2px 8px;border-radius:999px;font-size:12px;font-weight:700;border:1px solid transparent;display:inline-block}
  .badge.ok{background:#dcfce7;color:#166534;border-color:#86efac}
  .badge.warn{background:#fff7ed;color:#9a3412;border-color:#fed7aa}
  .badge.danger{background:#fee2e2;color:#991b1b;border-color:#fecaca}
  .muted{color:#64748b}
  .grid{display:grid; grid-template-columns: repeat(12,1fr); gap:10px}
  .col-12{grid-column:span 12} .col-6{grid-column:span 6} .col-4{grid-column:span 4} .col-3{grid-column:span 3}
  @media(max-width:900px){ .col-6,.col-4,.col-3{grid-column:span 12} }
  .card.note{background:#fff7ed; border:1px solid #fed7aa}
</style>

<!-- HERO -->
<div class="hero">
  <div class="mark">!</div>
  <div style="flex:1">
    <div style="font-weight:800;font-size:18px;color:#0f172a">Portal access is temporarily blocked</div>
    <div class="muted">
      <?php
        if ($reason==='UNPAID') echo "Reason: Pending fee.";
        elseif ($reason==='POLICY') echo "Reason: Admin policy.";
        else echo "Reason: Fee or policy restriction.";
      ?>
      <?php if($policy && $policy['policy']==='FORCE_BLOCK'): ?>
        • <span class="badge danger">Forced Block</span>
      <?php elseif($policy && $policy['policy']==='AUTO' && !empty($policy['grace_until']) && $policy['grace_until'] < date('Y-m-d')): ?>
        • Grace period ended on <b><?=h($policy['grace_until'])?></b>
      <?php endif; ?>
    </div>
  </div>
  <div>
    <a class="btn" href="user_login.php">Back to Login</a>
  </div>
</div>

<?php if($flash): ?>
  <div class="card mt-3" style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e40af"><?=h($flash)?></div>
<?php endif; ?>

<!-- WHAT YOU CAN DO -->
<div class="card mt-3">
  <h3 style="margin:0 0 8px;color:#1e40af">What you can do</h3>
  <ul style="margin:0 0 8px 16px; line-height:1.7">
    <li>Pay pending dues to restore access immediately.</li>
    <li>If you need time, request a <b>grace period</b> from the admin.</li>
    <li>If you believe this is a mistake, contact support.</li>
  </ul>
  <div class="muted">Contact: <a href="mailto:zetechup@gmail.com">academy@zetechup.com</a> • <a href="tel:0345-2377795">0345-2377795</a></div>
</div>

<!-- FEE SNAPSHOT -->
<div class="card mt-3">
  <h3 style="margin:0 0 8px;color:#1e40af">Your Fee Snapshot</h3>
  <?php if($reg): ?>
    <?php
      $status = $snap['status'] ?? ($reg['fee_status'] ?: 'UNPAID');
      $badge =
        $status==='PAID'    ? '<span class="badge ok">PAID</span>' :
        ($status==='PARTIAL'? '<span class="badge warn">PARTIAL</span>' :
                              '<span class="badge danger">UNPAID</span>');
      $total  = $snap ? (float)$snap['total_fee'] : (($reg['fee_type']==='PER_MONTH') ? (float)$reg['monthly_fee'] : (float)$reg['course_fee']);
      $paid   = $snap ? (float)$snap['paid_amount'] : 0.0;
      $disc   = $snap ? (float)$snap['discount'] : 0.0;
      $extra  = $snap ? (float)$snap['extra_charges'] : 0.0;
      $bal    = $total - ($paid + $disc - $extra);
      if ($bal < 0) $bal = 0;
    ?>
    <div class="grid">
      <div class="kpi col-3">
        <div class="label">Student</div>
        <div class="val"><?=h($me['full_name'] ?? '-')?></div>
      </div>
      <div class="kpi col-3">
        <div class="label">Course</div>
        <div class="val"><?=h($reg['course'])?></div>
      </div>
      <div class="kpi col-3">
        <div class="label">Fee Status</div>
        <div class="val"><?=$badge?></div>
      </div>
      <div class="kpi col-3">
        <div class="label">Total Fee</div>
        <div class="val"><?=number_format($total)?></div>
      </div>
      <div class="kpi col-3">
        <div class="label">Paid</div>
        <div class="val"><?=number_format($paid)?></div>
      </div>
      <div class="kpi col-3">
        <div class="label">Discount</div>
        <div class="val"><?=number_format($disc)?></div>
      </div>
      <div class="kpi col-3">
        <div class="label">Extra</div>
        <div class="val"><?=number_format($extra)?></div>
      </div>
      <div class="kpi col-3">
        <div class="label">Balance</div>
        <div class="val" style="color:#b91c1c"><?=number_format($bal)?></div>
      </div>
    </div>
    <?php if($policy): ?>
      <div class="card note mt-3">
        <div><b>Admin Policy:</b> <?=h($policy['policy'])?><?= !empty($policy['grace_until']) ? " • Grace until: <b>".h($policy['grace_until'])."</b>" : "" ?></div>
        <?php if(!empty($policy['note'])): ?>
          <div class="muted">Note: <?=h($policy['note'])?></div>
        <?php endif; ?>
      </div>
    <?php endif; ?>
  <?php else: ?>
    <div class="muted">No registration found yet.</div>
  <?php endif; ?>
</div>

<!-- LATEST PAYMENTS (optional) -->
<div class="card mt-3">
  <h3 style="margin:0 0 8px;color:#1e40af">Recent Payments</h3>
  <?php if($has_history): ?>
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>Date</th><th style="text-align:right">Amount</th><th>Method</th><th>Ref#</th><th>Note</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($hist as $p): ?>
            <tr>
              <td><?=h($p['paid_on'])?></td>
              <td style="text-align:right"><?=number_format((float)$p['amount'])?></td>
              <td><?=h($p['method'] ?: '-')?></td>
              <td><?=h($p['ref_no'] ?: '-')?></td>
              <td><?=h($p['note'] ?: '-')?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php else: ?>
    <div class="muted">No payment history to display.</div>
  <?php endif; ?>
</div>

<!-- HELP BOX -->
<div class="card mt-3">
  <div style="display:flex; gap:10px; align-items:center">
    <div class="badge warn" style="font-size:14px">Need Help?</div>
    <div class="muted">Visit academy office or contact: <a href="mailto:academy@zetechup.com">academy@zetechup.com</a></div>
  </div>
</div>

<?php user_footer(); ?>
