<?php
// Include database connection
include 'layouts/dbconn.php';

// Set headers to prevent caching
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-Type: text/plain');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get country and city prefix from POST request
    $countryPrefix = $_POST['countryPrefix'] ?? '';
    $cityPrefix = $_POST['cityPrefix'] ?? '';
    
    if (!empty($countryPrefix) && !empty($cityPrefix)) {
        // Get current year
        $year = date('y');
        
        // Query to find the last used number for ANY country-city combination for the current year
        // This creates a global sequence rather than per-destination sequences
        $query = "SELECT MAX(CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(file_number, '/', -2), '/', 1) AS UNSIGNED)) as last_number 
                  FROM files 
                  WHERE file_number LIKE 'RFT/%/%/%/{$year}'";
        
        $result = $conn->query($query);
        
        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $lastNumber = intval($row['last_number']);
            $newNumber = $lastNumber + 1;
        } else {
            // No existing records for this year, start with 1
            $newNumber = 1;
        }
        
        // Format with leading zeros (3 digits)
        $formattedNumber = sprintf("%03d", $newNumber);
        
        // Construct the file number in format RFT/DR/BUK/001/24
        $fileNumber = "RFT/{$countryPrefix}/{$cityPrefix}/{$formattedNumber}/{$year}";
        
        echo $fileNumber;
    } else {
        http_response_code(400);
        echo "Invalid parameters";
    }
} else {
    http_response_code(405);
    echo "Method Not Allowed";
}
?>