<?php
ob_start();

error_reporting(0);
ini_set('display_errors', 0);

include_once 'db_connection.php';

$response = [];

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

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Error: JSON inválido recibido.');
    }
    if (!$data || !isset($data['id']) || !isset($data['name']) || !isset($data['price'])) {
        throw new Exception('Datos incompletos. ID, Nombre y precio son requeridos.');
    }

    $id = $data['id'];
    $name = trim($data['name']);
    $price = filter_var($data['price'], FILTER_VALIDATE_FLOAT);
    $category = isset($data['category']) ? trim($data['category']) : null;
    $description = isset($data['description']) ? trim($data['description']) : null;
    $show_on_web = (isset($data['show_on_web']) && $data['show_on_web']) ? 1 : 0;

    $sql = "UPDATE services SET name = ?, price = ?, category = ?, description = ?, show_on_web = ? WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    
    if ($stmt->execute([$name, $price, $category, $description, $show_on_web, $id])) {
        $response = ['success' => true, 'message' => 'Servicio actualizado con éxito.'];
    } else {
        throw new Exception('Falló la ejecución de la consulta de actualización.');
    }
} catch (PDOException $e) {
    error_log("PDO Error en services-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'Error de Base de Datos: ' . $e->getMessage()];
} catch (Exception $e) {
    error_log("General Error en services-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => $e->getMessage()];
}

ob_end_clean();

header('Content-Type: application/json');
echo json_encode($response);
exit;