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

try {
    include_once 'db_connection.php';
    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);

    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR JSON INVALIDO');
    }
    if (!$data || !isset($data['id']) || !isset($data['name']) || !isset($data['price'])) {
        throw new Exception('DATOS INCOMPLETOS');
    }

    $id = filter_var($data['id'], FILTER_VALIDATE_INT);
    $name = filter_var(trim($data['name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $price = filter_var($data['price'], FILTER_VALIDATE_FLOAT);
    $category = isset($data['category']) ? filter_var(trim($data['category']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $description = isset($data['description']) ? filter_var(trim($data['description']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;

    if ($id === false || $price === false) {
        throw new Exception('ID O PRECIO INVALIDO');
    }

    $sql = "UPDATE services SET name = ?, price = ?, category = ?, description = ? WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    
    if ($stmt->execute([$name, $price, $category, $description, $id])) {
        $response = ['success' => true, 'message' => 'SERVICIO ACTUALIZADO'];
    } else {
        throw new Exception('FALLO AL EJECUTAR ACTUALIZACION');
    }
} catch (PDOException $e) {
    error_log("PDO Error en services-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("General Error en services-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}

echo json_encode($response);
exit;
?>