<?php
declare(strict_types=1);

// Definición de Protocolo y Host
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$base_url = "$protocol://$host";

// Configuración de Rutas del Portal
$PORTAL_PATHS = [
    'booking'       => $base_url . '/booking.php',
    'client_portal' => $base_url . '/portal/index.php',
    'member_portal' => $base_url . '/panel/index.php',
    'security_key'  => '#',
    'editor'        => '#',
    'toast'         => '#',
    'footer'        => '#',
];

// Constantes Globales
const GOOGLE_FONT_URL = 'https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap';

// Datos por Defecto (Fallback)
$platform_owner_name = 'Owner Name';
$platform_owner_photo_url = 'core/owner.webp';

$branding_defaults = [
    'full_title'  => 'FlowCRM Powered By OrozCO',
    'short_title' => 'FlowCRM™',
    'slogan'      => 'The #1 Platform to Boost Your Business'
];

if (!isset($client_info)) {
    $client_info = [];
}

// Conexión a Base de Datos
$pdo = $pdo ?? null;
if (!$pdo) {
    if (isset($conn) && $conn instanceof mysqli) {
        $pdo = new PDO(
            "mysql:host={$conn->host_info};dbname=" . $conn->query("SELECT DATABASE()")->fetch_row()[0],
            $conn->user,
            $conn->passwd,
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            ]
        );
    } else {
        $dbFile = __DIR__ . '/../db/db_connection.php';
        if (is_file($dbFile)) {
            require_once $dbFile;
        }
    }
}

try {
    $stmt = $pdo->prepare("SELECT * FROM business_info ORDER BY id DESC LIMIT 1");
    $stmt->execute();
    $biz = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$biz) {
        throw new Exception("No business info found");
    }

    $business_id = (int)$biz['id'];
    $user_id     = (int)$biz['user_id'];

    if (!empty($biz['timezone'])) {
        date_default_timezone_set($biz['timezone']);
    }

    // 2. Obtener Foto del Usuario Principal
    // Tabla: users
    $stmtUser = $pdo->prepare("SELECT profile_photo_url FROM users WHERE user_id = ? LIMIT 1");
    $stmtUser->execute([$user_id]);
    $userProfile = $stmtUser->fetch(PDO::FETCH_ASSOC);
    $userPhotoUrl = $userProfile['profile_photo_url'] ?? '';

    // 3. Códigos de Rastreo
    // Tabla: tracking_codes
    $stmtTrack = $pdo->prepare("SELECT tracking_codes_head, tracking_codes_body FROM tracking_codes WHERE business_info_id = ?");
    $stmtTrack->execute([$business_id]);
    $trackingData = $stmtTrack->fetch(PDO::FETCH_ASSOC);

    // 4. Enlaces de Reseñas
    // Tabla: review_links
    $stmtLinks = $pdo->prepare("SELECT platform_name, link_url FROM review_links WHERE business_info_id = ?");
    $stmtLinks->execute([$business_id]);
    
    $reviewsData = [];
    while ($row = $stmtLinks->fetch()) {
        $reviewsData[strtolower($row['platform_name'])] = $row['link_url'];
    }

    // 5. Ciudades de Cobertura
    // Tabla: coverage_cities
    $stmtCities = $pdo->prepare("SELECT city_name FROM coverage_cities");
    $stmtCities->execute();
    $citiesList = $stmtCities->fetchAll(PDO::FETCH_COLUMN);

    // 6. Conteo de Empleados
    // Tabla: staff
    // CORRECCIÓN: En tu DB el enum es 'active', no 'activo'
    $stmtEmployees = $pdo->prepare("SELECT COUNT(id) AS count FROM staff WHERE user_id = ? AND status = 'active'");
    $stmtEmployees->execute([$user_id]);
    $employeeCount = $stmtEmployees->fetchColumn();

    // 7. Configuración de Horarios
    // Tabla: schedule_config
    $stmtSched = $pdo->prepare("SELECT start_time, end_time, work_days FROM schedule_config WHERE user_id = ? LIMIT 1");
    $stmtSched->execute([$user_id]);
    $sched = $stmtSched->fetch(PDO::FETCH_ASSOC);

    $hoursData = [];
    $daysMap = [0 => 'Domingo', 1 => 'Lunes', 2 => 'Martes', 3 => 'Miércoles', 4 => 'Jueves', 5 => 'Viernes', 6 => 'Sábado'];
    $activeDays = !empty($sched['work_days']) ? explode(',', $sched['work_days']) : [];

    foreach ($daysMap as $num => $name) {
        $isOpen = in_array((string)$num, $activeDays);
        $hoursData[$name] = [
            'abierto'       => $isOpen,
            'dia_bloqueado' => !$isOpen,
            'inicio'        => $isOpen ? date('g:i A', strtotime($sched['start_time'])) : null,
            'fin'           => $isOpen ? date('g:i A', strtotime($sched['end_time'])) : null
        ];
    }

    $branding = $branding_defaults;
    if (!empty($biz['value_proposition'])) {
        $branding['slogan'] = $biz['value_proposition'];
    }

    // 8. Construcción del Array Maestro
    $client_info = [
        'id'                => $biz['id'],
        'business_name'     => $biz['company_name'],
        'contact_name'      => $biz['full_name'],
        'user_photo_url'    => $userPhotoUrl,
        'license_number'    => $biz['license_number'] ?? '',
        'logo_url'          => $biz['logo_url'],
        'state_region'      => $biz['state'] ?? '',
        'timezone'          => $biz['timezone'] ?? '',
        'cities_array'      => $citiesList,
        'cities_text'       => implode(', ', $citiesList),
        'phone_primary'     => $biz['phone_primary'],
        'phone_secondary'   => $biz['phone_secondary'] ?? '',
        'email_address'     => $biz['site_email'],
        'website_url'       => $biz['website_url'],
        'active_employees'  => $employeeCount,
        'branding'          => $branding,
        'value_proposition' => $biz['value_proposition'] ?? '',
        'urls' => [
            'booking_db'        => $biz['url_booking'] ?? '#',
            'client_portal_db'  => $biz['url_client_portal'] ?? '#',
            'member_portal_db'  => $biz['url_employee_portal'] ?? '#',
            'booking'           => $PORTAL_PATHS['booking'],
            'client_portal'     => $PORTAL_PATHS['client_portal'],
            'member_portal'     => $PORTAL_PATHS['member_portal'],
            'security_key'      => $PORTAL_PATHS['security_key'],
            'editor'            => $PORTAL_PATHS['editor'],
            'toast'             => $PORTAL_PATHS['toast'],
            'footer'            => $PORTAL_PATHS['footer'],
        ],
        'whatsapp' => [
            'display' => $biz['whatsapp'],
            'link'    => 'https://wa.me/' . preg_replace('/\D/', '', $biz['whatsapp'] ?? '')
        ],
        'hours_schedule'    => $hoursData,
        'reviews_links'     => $reviewsData,
        'tracking_codes'    => [
            'head' => $trackingData['tracking_codes_head'] ?? '',
            'body' => $trackingData['tracking_codes_body'] ?? ''
        ],
        'platform_owner'    => [
            'name'  => $platform_owner_name,
            'photo' => $platform_owner_photo_url
        ]
    ];
    
} catch (Exception $e) {
    error_log("Business Loader Error: " . $e->getMessage());
    if(empty($client_info)) {
        $client_info = [
            'branding'       => $branding_defaults,
            'urls'           => $PORTAL_PATHS,
            'whatsapp'       => [], 
            'tracking_codes' => [],
            'platform_owner' => [
                'name'  => $platform_owner_name,
                'photo' => $platform_owner_photo_url
            ]
        ];
    }
}

// --- VARIABLES DE ACCESO RÁPIDO ---

$google_font_url = GOOGLE_FONT_URL;