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

try {
    require_once __DIR__ . '/../core/api.php';
    global $pdo;

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    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');
    }

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

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

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