<?php
// /user/_user_auth.php
require_once __DIR__ . '/_bootstrap.php';

// --------------------------------------
// Step 1: Check login session
// --------------------------------------
if (empty($_SESSION['student_id'])) {
  $_SESSION['after_login'] = basename($_SERVER['PHP_SELF']);
  header('Location: user_login.php');
  exit;
}

// --------------------------------------
// Step 2: Load student basic info
// --------------------------------------
$student_id = (int)$_SESSION['student_id'];
$stu = mysqli_query($conn, "SELECT id, full_name, email, portal_enabled FROM students WHERE id={$student_id} LIMIT 1");
$me  = mysqli_fetch_assoc($stu);

if (!$me || (int)$me['portal_enabled'] !== 1) {
  session_destroy();
  header('Location: user_login.php?err=' . urlencode('Portal access disabled. Contact academy.'));
  exit;
}

// --------------------------------------
// Step 3: Skip enforcement if page allows blocked users
// --------------------------------------
if (!isset($ALLOW_BLOCKED) || !$ALLOW_BLOCKED) {

  // ---- Portal access enforcement ----
  $fee_status = 'UNPAID';
  $course_id  = null;

  // latest registration
  $q = mysqli_query($conn, "
    SELECT r.course_id, r.fee_status, r.approved_at
    FROM registrations r
    WHERE r.student_id={$student_id}
    ORDER BY r.approved_at DESC
    LIMIT 1
  ");
  if ($r = mysqli_fetch_assoc($q)) {
    $course_id  = (int)$r['course_id'];
    $fee_status = $r['fee_status'] ?: 'UNPAID';

    // prefer fee_payments snapshot if exists
    $q2 = mysqli_query($conn, "
      SELECT status
      FROM fee_payments
      WHERE student_id={$student_id} AND course_id={$course_id}
      ORDER BY updated_at DESC
      LIMIT 1
    ");
    if ($snap = mysqli_fetch_assoc($q2)) {
      $fee_status = $snap['status'];
    }
  }

  // policy row
  $pol = mysqli_query($conn, "
    SELECT policy, grace_until
    FROM student_portal_access
    WHERE student_id={$student_id}
    LIMIT 1
  ");
  $policy = 'AUTO'; 
  $grace = null;
  if ($p = mysqli_fetch_assoc($pol)) {
    $policy = $p['policy'] ?: 'AUTO';
    $grace  = $p['grace_until'] ?: null;
  }

  // Decision logic
  $today = date('Y-m-d');
  $allow = false;

  if ($policy === 'FORCE_ALLOW') {
    $allow = true;
  } elseif ($policy === 'FORCE_BLOCK') {
    $allow = false;
  } else {
    // AUTO mode
    if ($fee_status === 'PAID') {
      $allow = true;
    } elseif (!empty($grace) && $grace >= $today) {
      $allow = true; // grace wins
    } else {
      $allow = false;
    }
  }

  // --------------------------------------
  // Step 4: Redirect to Block Page if not allowed
  // --------------------------------------
  if (!$allow) {
    $reason = ($policy === 'FORCE_BLOCK') ? 'POLICY' : 'UNPAID';
    header("Location: portal_blocked.php?reason={$reason}&msg=" . urlencode("Access restricted. Please clear dues or contact admin."));
    exit;
  }
  // ---- end enforcement ----
}
