<?php 
ob_start();
header('Content-Type: application/json');
$response_data = ['success' => false, 'services' => [], '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);

    $stmt = $pdo->query("SELECT id, name, price, category, description, show_on_web FROM services ORDER BY name ASC");
    $services = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_services = [];
    foreach ($services as $service) {
        $formatted_services[] = [
            'id' => (int)$service['id'],
            'name' => filter_var($service['name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
            'price' => (float)$service['price'],
            'category' => filter_var($service['category'], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
            'description' => filter_var($service['description'], FILTER_SANITIZE_FULL_SPECIAL_CHARS),
            'show_on_web' => (bool)$service['show_on_web']
        ];
    }

    $response_data = ['success' => true, 'services' => $formatted_services];
} catch (PDOException $e) {
    error_log("Error PDO al cargar servicios desde la DB en services-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general al cargar servicios en services-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR INESPERADO';
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response_data);
exit;
?>