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

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 this country-city combination for the current year
        $query = "SELECT file_number FROM files 
                  WHERE file_number LIKE 'RFT/{$countryPrefix}/{$cityPrefix}/%/{$year}' 
                  ORDER BY id DESC LIMIT 1";
        
        $result = $conn->query($query);
        
        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $lastFileNumber = $row['file_number'];
            
            // Extract the numeric part
            $parts = explode('/', $lastFileNumber);
            $lastNumber = intval($parts[3]);
            $newNumber = $lastNumber + 1;
        } else {
            // No existing records for this combination, 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 {
        echo "Invalid parameters";
    }
} else {
    echo "Invalid request method";
}
?>