<?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');
include('includes/flash.php');
require_once __DIR__ . '/includes/session_term_helper.php';

$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];
$currentSessionRank = (int) substr($currentSessionName ?? '', 0, 4);

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

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['id_address'];
$url = $_ENV['BASE_URL'];

if (strlen($_SESSION['sid']) == 0) {
    header('location:logout.php');
    exit();
}

function smartRoundToThousand($value)
{
    $remainder = $value % 1000;
    return ($remainder > 100) ? ceil($value / 1000) * 1000 : floor($value / 1000) * 1000;
}

/**
 * Resolve the new student school fee for a given class/stream/session/term.
 * Checks fee_records first (session+term specific), falls back to fees catalogue.
 */
function resolveNewStudentFee(mysqli $con, string $class, string $stream, string $session, string $term): float
{
    // Try fee_records for the exact session + term
    $stmt = $con->prepare(
        "SELECT amount FROM fee_records
         WHERE name = 'School Fees (New Student)' AND class = ? AND stream = ?
           AND student_type = 'New' AND session = ? AND term = ?
         ORDER BY id DESC LIMIT 1"
    );
    if ($stmt) {
        $stmt->bind_param("ssss", $class, $stream, $session, $term);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        if ($row && (float) $row['amount'] > 0) {
            return (float) $row['amount'];
        }
    }
    // Fall back to fees catalogue
    $stmt2 = $con->prepare(
        "SELECT amount FROM fees
         WHERE name = 'School Fees (New Student)' AND class = ? AND stream = ?
           AND student_type = 'New'
         LIMIT 1"
    );
    if ($stmt2) {
        $stmt2->bind_param("ss", $class, $stream);
        $stmt2->execute();
        $row2 = $stmt2->get_result()->fetch_assoc();
        $stmt2->close();
        if ($row2 && (float) $row2['amount'] > 0) {
            return (float) $row2['amount'];
        }
    }
    return 0.0;
}

/**
 * Resolve a student's admission session and term.
 * If empty, in a past session, or same session but past term → fall back to current session/term.
 */
function resolveAdmissionSessionTerm(
    string $studentSession,
    string $studentTerm,
    string $currentSession,
    string $currentTerm,
    int    $currentSessionRank
): array {
    $termRanksMap = ['First Term' => 1, 'Second Term' => 2, 'Third Term' => 3];

    $sessionRank = (int) substr($studentSession, 0, 4);
    $termRank    = $termRanksMap[$studentTerm]    ?? 0;
    $curTermRank = $termRanksMap[$currentTerm]    ?? 0;

    $isPast = $studentSession === '' || $studentTerm === ''
        || $sessionRank < $currentSessionRank
        || ($sessionRank === $currentSessionRank && $termRank < $curTermRank);

    if ($isPast) {
        return ['session' => $currentSession, 'term' => $currentTerm, 'resolved' => true];
    }
    return ['session' => $studentSession, 'term' => $studentTerm, 'resolved' => false];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_deadlines'])) {
    $studentId = intval($_POST['student_id']);
    $acceptanceDeadline = $_POST['acceptance_deadline'] ?? '';
    $schoolFeeDeadline = $_POST['schoolfee_deadline'];
    $acceptanceDeadlineFormatted = !empty($acceptanceDeadline) ? date("F j, Y", strtotime($acceptanceDeadline)) : '';
    $schoolFeeDeadlineFormatted = date("F j, Y", strtotime($schoolFeeDeadline));

    $query = mysqli_query($con, "SELECT * FROM students WHERE id = '$studentId'");
    $student = mysqli_fetch_assoc($query);

    if (!$student) {
        flash_alert('Student not found.', 'studentlist.php');
        header('Location: studentlist.php');
        exit;
        exit();
    }

    $email = $student['email'];
    $name = $student['studentName'];
    $class = $student['class'];
    $stream = $student['stream'];

    $resolved = resolveAdmissionSessionTerm(
        $student['academic_session'] ?? '',
        $student['admission_term']   ?? '',
        $currentSessionName,
        $currentTermName,
        $currentSessionRank
    );
    $session      = $resolved['session'];
    $admissionTerm = $resolved['term'];

    $totalFee = resolveNewStudentFee($con, $class, $stream, $session, $admissionTerm);

    if ($totalFee <= 0) {
        flash_alert('Fee structure not found for ' . $class . ' / ' . $stream . ' — ' . $session . ' ' . $admissionTerm . '.', 'studentlist.php');
        header('Location: studentlist.php');
        exit;
    }

    $acceptanceRatio = 30000 / 190000;
    $rawAcceptance = $acceptanceRatio * $totalFee;
    $acceptanceFee = smartRoundToThousand($rawAcceptance);

    // === Generate Registration Number ===
    $regPrefix = $_ENV['registration_prefix'];
    $sessionParts = explode("/", $session);
    $year1 = (int) trim($sessionParts[0]);
    $year2 = (int) trim($sessionParts[1] ?? ($year1 + 1));

    // e.g. 2025/2026 → 5, 26 → base = 526151
    $sessionBaseNumber    = (int)(substr($year1, -1) . substr($year2, -2) . '151');
    // Upper bound = next session's base (exclusive), e.g. 627151 for 2026/2027
    $nextYear1 = $year1 + 1;
    $nextYear2 = $year2 + 1;
    $nextSessionBase = (int)(substr($nextYear1, -1) . substr($nextYear2, -2) . '151');

    mysqli_query($con, "LOCK TABLES students WRITE");
    $checkResult = mysqli_query($con,
        "SELECT studentRegNo FROM students
         WHERE studentRegNo LIKE '$regPrefix/%'
           AND CAST(SUBSTRING_INDEX(studentRegNo, '/', -1) AS UNSIGNED) >= $sessionBaseNumber
           AND CAST(SUBSTRING_INDEX(studentRegNo, '/', -1) AS UNSIGNED) < $nextSessionBase
         ORDER BY CAST(SUBSTRING_INDEX(studentRegNo, '/', -1) AS UNSIGNED) DESC
         LIMIT 1"
    );
    if ($checkResult && mysqli_num_rows($checkResult) > 0) {
        $latest = mysqli_fetch_assoc($checkResult)['studentRegNo'];
        $newNumber = (string)((int) substr($latest, strrpos($latest, '/') + 1) + 1);
    } else {
        $newNumber = (string) $sessionBaseNumber;
    }
    $regNo = "$regPrefix/$newNumber";
    $hashedPassword = password_hash($regNo, PASSWORD_BCRYPT);
    mysqli_query($con, "UNLOCK TABLES");
    // === End Generate Registration Number ===

    $updStmt = $con->prepare("
        UPDATE students
        SET status = 2,
            studentRegNo = ?,
            password = ?,
            acceptance_deadline = NULL,
            schoolfee_deadline = ?,
            academic_session = ?,
            admission_term = ?
        WHERE id = ?
    ");
    $updStmt->bind_param("sssssi", $regNo, $hashedPassword, $schoolFeeDeadline, $session, $admissionTerm, $studentId);
    $updStmt->execute();
    $updStmt->close();

    $acceptanceNote = '';
    $acceptanceDeadlineListItem = '';

    if (!empty($acceptanceDeadline)) {
        $acceptanceNote = "<p>You are required to pay an acceptance fee of <strong>₦" . number_format($acceptanceFee) . "</strong> (non-refundable and non-transferable), which has already been deducted from the full school fees of <strong>₦" . number_format($totalFee) . "</strong>.</p>
    <p>This fee allows the school to prepare ahead of resumption and avoid last-minute congestion.</p>";
        $acceptanceDeadlineListItem = "<li>Acceptance Fee Payment Deadline: <strong>$acceptanceDeadlineFormatted</strong></li>";
    } else {
        $acceptanceNote = "<p><strong>Note:</strong> Acceptance fee payment has closed for this session. You may proceed to pay the full school fees directly to complete your admission process.</p>";
        $acceptanceDeadlineListItem = "<li>Acceptance Fee Payment: <strong>Closed</strong></li>";
    }


    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = $_ENV['SMTP_HOST'];
        $mail->SMTPAuth = true;
        $mail->Username = $_ENV['SMTP_NO_REPLY'];
        $mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->Port = $_ENV['SMTP_PORT'];
        $mail->Timeout = 10;

        $mail->setFrom($_ENV['SMTP_NO_REPLY'], $school_name);
        $mail->addAddress($email, $name);
        $mail->addBCC($_ENV['ADMISSION_EMAIL'], $school_name . ' Admissions');
        $mail->isHTML(true);
        $mail->CharSet = 'UTF-8';
        $mail->Subject = "$school_name Admission Notification";
        $mail->Body = "
<html>
<body>
<div style='max-width: 600px; margin: auto; font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 30px; border: 1px solid #ddd;'>
    <h2 style='color: #ffffff; text-align: center; padding: 15px 0; background-color: #2e6da4; border-radius: 5px;'>Admission Offer Letter</h2>
    <p>Dear <strong>$name</strong>,</p>

    <p><strong>Congratulations!</strong></p>

    <p>We are delighted to inform you that you passed the just concluded entrance examination into <strong>$class ($session session)</strong> and your registration number has been issued successfully.</p>

    <p><strong>Your login credentials for the student portal are as follows:</strong></p>
    <ul>
        <li><strong>Registration Number:</strong> $regNo</li>
        <li><strong>Password:</strong> $regNo</li>
    </ul>

    <p>Portal link: <a href='$url/portal/new_student.php'>$url/portal/new_student.php</a></p>

    <p>After a successful login, please fill in all the required information on the portal to complete your profile.</p>

    <p><strong>Payment Information:</strong></p>
    $acceptanceNote

    <p><strong>Important Deadlines:</strong></p>
    <ul>
        $acceptanceDeadlineListItem
        <li>Full School Fees Payment Deadline: <strong>$schoolFeeDeadlineFormatted</strong></li>
    </ul>
    <p style='color: red; font-weight: bold;'>NOTE: All School Fees payments must be made directly on the student portal only</p>

    <p>Once your full payment has been confirmed by the school, a follow-up message will be sent to schedule your uniform collection day.</p>

    <p>Please note that the admission letter, school uniforms, and other essentials will be provided only after the full school fees have been paid.</p>

    <p>Thank you for choosing <strong>$school_name</strong>. We look forward to welcoming you into our academic community.</p>

    <p>Warm regards,<br>
    <strong>Admissions Office</strong><br>
    $school_name<br>
    $school_address</p>

    <hr style='margin-top: 40px;'>
    <center>
        <small style='color: #888;'>$school_name &copy; " . date("Y") . ". All rights reserved.</small>
    </center>
</div>
</body>
</html>
";


        $mail->send();
        flash_alert('Student admitted and email sent.', 'studentlist.php');
        header('Location: studentlist.php');
        exit;
    } catch (Exception $e) {
        flash_alert('Student admitted, but email failed: ' . $mail->ErrorInfo, 'studentlist.php');
        header('Location: studentlist.php');
        exit;
    }
} else if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_bulk_deadlines'])) {
    $studentIds = explode(",", $_POST['bulk_student_ids']);
    $acceptanceDeadline = $_POST['acceptance_deadline'];
    $schoolFeeDeadline = $_POST['schoolfee_deadline'];
    $acceptanceDeadlineFormatted = !empty($acceptanceDeadline) ? date("F j, Y", strtotime($acceptanceDeadline)) : '';
    $schoolFeeDeadlineFormatted = date("F j, Y", strtotime($schoolFeeDeadline));

    $successCount = 0;
    $failCount = 0;

    foreach ($studentIds as $studentId) {
        $studentId = intval($studentId);
        $query = mysqli_query($con, "SELECT * FROM students WHERE id = '$studentId'");
        $student = mysqli_fetch_assoc($query);

        if (!$student)
            continue;

        $email = $student['email'];
        $name = $student['studentName'];
        $class = $student['class'];
        $stream = $student['stream'];

        $resolved = resolveAdmissionSessionTerm(
            $student['academic_session'] ?? '',
            $student['admission_term']   ?? '',
            $currentSessionName,
            $currentTermName,
            $currentSessionRank
        );
        $session       = $resolved['session'];
        $admissionTerm = $resolved['term'];

        $totalFee = resolveNewStudentFee($con, $class, $stream, $session, $admissionTerm);

        if ($totalFee <= 0)
            continue;
        $acceptanceFee = smartRoundToThousand((30000 / 190000) * $totalFee);

        // === Generate Registration Number ===
        $regPrefix = $_ENV['registration_prefix'];
        $sessionParts = explode("/", $session);
        $year1 = (int) trim($sessionParts[0]);
        $year2 = (int) trim($sessionParts[1] ?? ($year1 + 1));

        // e.g. 2025/2026 → 5, 26 → base = 526151
        $sessionBaseNumber = (int)(substr($year1, -1) . substr($year2, -2) . '001');
        // Upper bound = next session's base (exclusive)
        $nextYear1 = $year1 + 1;
        $nextYear2 = $year2 + 1;
        $nextSessionBase = (int)(substr($nextYear1, -1) . substr($nextYear2, -2) . '001');

        mysqli_query($con, "LOCK TABLES students WRITE");
        $checkResult = mysqli_query($con,
            "SELECT studentRegNo FROM students
             WHERE studentRegNo LIKE '$regPrefix/%'
               AND CAST(SUBSTRING_INDEX(studentRegNo, '/', -1) AS UNSIGNED) >= $sessionBaseNumber
               AND CAST(SUBSTRING_INDEX(studentRegNo, '/', -1) AS UNSIGNED) < $nextSessionBase
             ORDER BY CAST(SUBSTRING_INDEX(studentRegNo, '/', -1) AS UNSIGNED) DESC
             LIMIT 1"
        );
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $latest = mysqli_fetch_assoc($checkResult)['studentRegNo'];
            $newNumber = (string)((int) substr($latest, strrpos($latest, '/') + 1) + 1);
        } else {
            $newNumber = (string) $sessionBaseNumber;
        }
        $regNo = "$regPrefix/$newNumber";
        $hashedPassword = password_hash($regNo, PASSWORD_BCRYPT);
        mysqli_query($con, "UNLOCK TABLES");
        // === End Generate Registration Number ===

        $updStmt = $con->prepare("
            UPDATE students
            SET status = 2,
                studentRegNo = ?,
                password = ?,
                acceptance_deadline = NULL,
                schoolfee_deadline = ?,
                academic_session = ?,
                admission_term = ?
            WHERE id = ?
        ");
        $updStmt->bind_param("sssssi", $regNo, $hashedPassword, $schoolFeeDeadline, $session, $admissionTerm, $studentId);
        $updStmt->execute();
        $updStmt->close();

        $acceptanceNote = '';
        $acceptanceDeadlineListItem = '';

        if (!empty($acceptanceDeadline)) {
            $acceptanceNote = "<p>You are required to pay an acceptance fee of <strong>₦" . number_format($acceptanceFee) . "</strong> (non-refundable and non-transferable), which has already been deducted from the full school fees of <strong>₦" . number_format($totalFee) . "</strong>.</p>
    <p>This fee allows the school to prepare ahead of resumption and avoid last-minute congestion.</p>";
            $acceptanceDeadlineListItem = "<li>Acceptance Fee Payment Deadline: <strong>$acceptanceDeadlineFormatted</strong></li>";
        } else {
            $acceptanceNote = "<p><strong>Note:</strong> Acceptance fee payment has closed for this session. You may proceed to pay the full school fees directly to complete your admission process.</p>";
            $acceptanceDeadlineListItem = "<li>Acceptance Fee Payment: <strong>Closed</strong></li>";
        }


        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = $_ENV['SMTP_HOST'];
            $mail->SMTPAuth = true;
            $mail->Username = $_ENV['SMTP_NO_REPLY'];
            $mail->Password = $_ENV['SMTP_NO_REPLY_PASSWORD'];
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port = $_ENV['SMTP_PORT'];
            $mail->Timeout = 10;

            $mail->setFrom($_ENV['SMTP_NO_REPLY'], $school_name);
            $mail->addAddress($email, $name);
            $mail->addBCC($_ENV['ADMISSION_EMAIL'], $school_name . ' Admissions');
            $mail->isHTML(true);
            $mail->Subject = "$school_name Admission Notification";
            $mail->Body = "
<html>
<body>
<div style='max-width: 600px; margin: auto; font-family: Arial, sans-serif; background-color: #f9f9f9; padding: 30px; border: 1px solid #ddd;'>
    <h2 style='color: #ffffff; text-align: center; padding: 15px 0; background-color: #2e6da4; border-radius: 5px;'>Admission Offer Letter</h2>
    <p>Dear <strong>$name</strong>,</p>

    <p><strong>Congratulations!</strong></p>

    <p>We are delighted to inform you that you passed the just concluded entrance examination into <strong>$class ($session session)</strong> and your registration number has been issued successfully.</p>

    <p><strong>Your login credentials for the student portal are as follows:</strong></p>
    <ul>
        <li><strong>Registration Number:</strong> $regNo</li>
        <li><strong>Password:</strong> 12345678</li>
    </ul>

    <p>Portal link: <a href='$url/new_student.php'>$url/new_student.php</a></p>

    <p>After a successful login, please fill in all the required information on the portal to complete your profile.</p>

    <p><strong>Payment Information:</strong></p>
    $acceptanceNote

    <p><strong>Important Deadlines:</strong></p>
    <ul>
        $acceptanceDeadlineListItem
        <li>Full School Fees Payment Deadline: <strong>$schoolFeeDeadlineFormatted</strong></li>
    </ul>

    <p style='color: red; font-weight: bold;'>NOTE: All School Fees payments must be made directly on the student portal only</p>

    <p>Once your full payment has been confirmed by the school, a follow-up message will be sent to schedule your uniform collection day.</p>

    <p>Please note that the admission letter, school uniforms, and other essentials will be provided only after the full school fees have been paid.</p>

    <p>Thank you for choosing <strong>$school_name</strong>. We look forward to welcoming you into our academic community.</p>

    <p>Warm regards,<br>
    <strong>Admissions Office</strong><br>
    $school_name<br>
    $school_address</p>

    <hr style='margin-top: 40px;'>
    <center>
        <small style='color: #888;'>$school_name &copy; " . date("Y") . ". All rights reserved.</small>
    </center>
</div>
</body>
</html>
";

            $mail->send();
            $successCount++;
        } catch (Exception $e) {
            $failCount++;
            continue;
        }
    }

    flash_alert('Bulk Admission Complete. Successful emails: ' . $successCount . ', Failed emails: ' . $failCount, 'studentlist.php');
    header('Location: studentlist.php');
    exit;
}
?>