<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR POR DEFECTO'];

try {
    require_once '../files/guardiankey.php';
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    include_once 'db_connection.php';

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('MÉTODO DE SOLICITUD NO VÁLIDO');
    }
    
    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['client_id'])) {
        throw new Exception('ID DE CLIENTE NO PROPORCIONADO');
    }

    $client_id = filter_var($input['client_id'], FILTER_VALIDATE_INT);

    if ($client_id === false) {
        throw new Exception('ID DE CLIENTE INVÁLIDO');
    }

    $new_code = random_int(10000, 99999);

    $stmt = $pdo->prepare("UPDATE clients SET access_code = ? WHERE id = ?");
    
    if ($stmt->execute([$new_code, $client_id])) {
        $response['success'] = true;
        $response['new_code'] = $new_code;
        $response['message'] = 'CÓDIGO GENERADO';
    } else {
        throw new Exception('NO SE PUDO ACTUALIZAR EL CÓDIGO');
    }

} catch (PDOException $e) {
    error_log("Error PDO en clients-generate-code.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
     error_log("Error general en clients-generate-code.php: " . $e->getMessage());
     $response['message'] = $e->getMessage();
}

ob_end_clean();
echo json_encode($response);
exit();