<?php
// school_admission/includes/functions.php

// Prevent direct access to this file
if (basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
    die("Access denied!");
}

/**
 * Redirects to a specified URL.
 * @param string $url The URL to redirect to.
 */
function redirect($url) {
    header("Location: " . $url);
    exit();
}

/**
 * Sanitizes input string to prevent XSS.
 * @param string $data The input string.
 * @return string The sanitized string.
 */
function sanitize_input($data) {
    return htmlspecialchars(stripslashes(trim($data)));
}

/**
 * Generates a unique application number.
 * Format: MITI/FT/YYYY/BXXX
 * @param int $branchId The branch ID.
 * @return string The generated application number.
 */
function generateApplicationNumber($branchId) {
    global $conn; // Access the global database connection

    $year = date('Y');
    // Pad branch ID to ensure consistent length, e.g., B001, B010
    $branchCode = 'B' . str_pad($branchId, 3, '0', STR_PAD_LEFT);

    // Get the highest existing application number for the current year and branch
    $stmt = $conn->prepare("SELECT application_no FROM applicants WHERE application_no LIKE ? ORDER BY application_no DESC LIMIT 1");
    $prefix = "MITI/FT/{$year}/{$branchCode}%";
    $stmt->bind_param("s", $prefix);
    $stmt->execute();
    $result = $stmt->get_result();

    $nextNumber = 1;
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $lastAppNo = $row['application_no'];
        // Extract the numeric part (e.g., from MITI/FT/2025/B001005, get 005)
        preg_match('/(\d+)$/', $lastAppNo, $matches);
        if (isset($matches[1])) {
            $lastNumericPart = (int)$matches[1];
            $nextNumber = $lastNumericPart + 1;
        }
    }
    // Pad the numeric part to ensure consistent length, e.g., 001, 010, 100
    return "MITI/FT/{$year}/{$branchCode}" . str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
}

// Add more utility functions as needed
?>