<?php
// hr_api/get-next-emp-no.php

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';


// Ensure that nothing is echoed before this header.
// This header ensures the client knows to expect JSON.
header('Content-Type: application/json');


require_once __DIR__ . '/db.php';

try {
    $stmt = $pdo->query("SELECT emp_no FROM employee_details ORDER BY id DESC LIMIT 1");
    $lastEmpNoRow = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($lastEmpNoRow && isset($lastEmpNoRow['emp_no'])) {
        // Extract numeric part from format mcdo/00012 (example from your output)
        $lastEmpNo = $lastEmpNoRow['emp_no'];
        // Corrected preg_match: escape the forward slash in the pattern
        // The pattern is now /MCDO\/(\d+)/i
        preg_match('/MCDO\/(\d+)/i', $lastEmpNo, $matches);
        $lastNumber = isset($matches[1]) ? (int)$matches[1] : 0;
        $nextNumber = $lastNumber + 1;
        $nextEmpNo = 'MCDO/' . str_pad($nextNumber, 5, '0', STR_PAD_LEFT);
    } else {
        $nextEmpNo = 'MCDO/00001'; // Start fresh
    }

    echo json_encode([
        'success' => true,
        'emp_no' => $nextEmpNo
    ]);
} catch (PDOException $e) {
    // It's crucial that only JSON is outputted, even on error.
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
// It's good practice to exit after echoing JSON, especially in a simple API endpoint.
exit();
?>