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

try {
    require_once('../files/guardiankey.php');
    require_once('db_connection.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 = [
        'general' => [],
        'social_links' => [],
        'tracking_codes' => [],
        'sections_enabled' => []
    ];

    $stmt = $pdo->prepare("SELECT * FROM business_info WHERE id = ? LIMIT 1");
    $stmt->execute([1]);
    $generalData = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($generalData) {
        $businessInfoId = $generalData['id'];
        $data['general'] = $generalData;

        $stmtLinks = $pdo->prepare("SELECT link_icon, link_url FROM social_links WHERE business_info_id = ?");
        $stmtLinks->execute([$businessInfoId]);
        $data['social_links'] = $stmtLinks->fetchAll(PDO::FETCH_ASSOC);

        $stmtTracking = $pdo->prepare("SELECT tracking_codes_head, tracking_codes_body FROM tracking_codes WHERE business_info_id = ?");
        $stmtTracking->execute([$businessInfoId]);
        $trackingData = $stmtTracking->fetch(PDO::FETCH_ASSOC);
        $data['tracking_codes'] = $trackingData ?: ['tracking_codes_head' => null, 'tracking_codes_body' => null];

        $stmtSections = $pdo->prepare("SELECT * FROM sections_enabled WHERE business_info_id = ?");
        $stmtSections->execute([$businessInfoId]);
        $sectionsData = $stmtSections->fetch(PDO::FETCH_ASSOC);
        $data['sections_enabled'] = $sectionsData ?: [];
    } else {
         error_log("Advertencia business-info-read.php: No se encontró registro ID=1");
    }

    $response = ['success' => true, 'data' => $data];

} catch (PDOException $e) {
    error_log("Error PDO en business-info-read.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("Error general en business-info-read.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR INTERNO'];
}

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