<?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 (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR AL DECODIFICAR DATOS');
    }
    if (empty($input) || !isset($input['id'])) {
        throw new Exception('ID DE CLIENTE NO PROPORCIONADO');
    }

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

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

    $pdo->beginTransaction(); 

    $stmt = $pdo->prepare("DELETE FROM clients WHERE id = ?");
    $stmt->execute([$client_id]);

    $pdo->commit(); 
    $response['success'] = true;
    $response['message'] = 'CLIENTE ELIMINADO';

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Error PDO al eliminar cliente en clients-delete.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Error general al eliminar cliente en clients-delete.php: " . $e->getMessage());
    $response['message'] = $e->getMessage();
}

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