<?php
/**
 * AJAX Endpoint for Billing Portal WiFi Card
 * Returns HTML content for the "Informasi ONU" card
 */

session_start();
date_default_timezone_set('Asia/Jakarta');

require_once(__DIR__ . '/../include/db_config.php');
require_once(__DIR__ . '/../lib/BillingService.class.php');
require_once(__DIR__ . '/../include/genieacs_setup.php');

if (!isset($_SESSION['billing_portal_customer_id']) || (int)$_SESSION['billing_portal_customer_id'] <= 0) {
    exit('<div class="alert alert-danger">Sesi berakhir. Silakan login kembali.</div>');
}

$activeCustomerId = (int)$_SESSION['billing_portal_customer_id'];

try {
    $billingService = new BillingService();
    $customer = $billingService->getCustomerById($activeCustomerId);

    if (!$customer) {
        exit('<div class="alert alert-danger">Data pelanggan tidak ditemukan.</div>');
    }

    // Initialize variables
    $deviceSnapshot = [];
    $currentWiFi = [
        'ssid' => null,
        'password' => null,
        'enabled' => null,
        'error' => null
    ];
    $wifiDebug = [];

    // Caching mechanism for GenieACS data
    $cacheKey = 'genieacs_cache_' . $customer['id'];
    $cacheDuration = 300; // 5 minutes cache
    $dataLoadedFromCache = false;

    // Force refresh if requested
    if (isset($_GET['refresh_device']) && $_GET['refresh_device'] === '1') {
        unset($_SESSION[$cacheKey]);
    }

    if (isset($_SESSION[$cacheKey]) && (time() - $_SESSION[$cacheKey]['time'] < $cacheDuration)) {
         $deviceSnapshot = $_SESSION[$cacheKey]['deviceSnapshot'];
         $currentWiFi = $_SESSION[$cacheKey]['currentWiFi'];
         $wifiDebug[] = "Data loaded from cache (expires in " . ($cacheDuration - (time() - $_SESSION[$cacheKey]['time'])) . "s)";
         $dataLoadedFromCache = true;
    }

    if (!$dataLoadedFromCache) {
        try {
            // Load config first
            loadGenieACSForPortal();
            
            // Check if GenieACS class is available
            if (!class_exists('GenieACS')) {
                throw new Exception('GenieACS class tidak tersedia.');
            }
            
            $genieacs = new GenieACS();
            
            if ($genieacs->isEnabled()) {
                // Find device using helper function
                $deviceSearch = findDeviceByCustomer($customer, $genieacs);
                $device = $deviceSearch['device'];
                $searchMethod = $deviceSearch['method'];
                
                if ($device) {
                    // Use VirtualParameters like admin page does
                    $ssidPath = 'VirtualParameters.SSID';
                    $ssidPathAlt = 'VirtualParameters.SSID_ALL';
                    $passwordPath = 'InternetGatewayDevice.LANDevice.1.WLANConfiguration.1.PreSharedKey.1.KeyPassphrase';
                    
                    // Parse SSID from VirtualParameters - try multiple possible names
                    $ssidFound = false;
                    $possibleSSIDKeys = ['SSID', 'SSID_ALL', 'WlanSSID', 'wlanSSID', 'ssid', 'Ssid'];
                    foreach ($possibleSSIDKeys as $key) {
                        if (isset($device['VirtualParameters'][$key])) {
                            $currentWiFi['ssid'] = $device['VirtualParameters'][$key]['_value'] ?? $device['VirtualParameters'][$key];
                            $ssidFound = true;
                            break;
                        }
                    }
                    
                    if (!$ssidFound) {
                        // Try to get from raw TR-069 path as fallback
                        if (isset($device['InternetGatewayDevice']['LANDevice']['1']['WLANConfiguration']['1']['SSID'])) {
                            $currentWiFi['ssid'] = $device['InternetGatewayDevice']['LANDevice']['1']['WLANConfiguration']['1']['SSID']['_value'] ?? null;
                        }
                    }
                    
                    // Get password from WlanPassword VirtualParameter
                    if (isset($device['VirtualParameters']['WlanPassword'])) {
                        $currentWiFi['password'] = $device['VirtualParameters']['WlanPassword']['_value'] ?? $device['VirtualParameters']['WlanPassword'];
                    }
                    
                    // WiFi enabled status
                    if (isset($device['InternetGatewayDevice']['LANDevice']['1']['WLANConfiguration']['1']['Enable'])) {
                        $currentWiFi['enabled'] = $device['InternetGatewayDevice']['LANDevice']['1']['WLANConfiguration']['1']['Enable']['_value'] ?? null;
                    }
                    
                    // Get connected devices from SSID 1
                    $connectedDevicesSSID1 = 'N/A';
                    if (isset($device['InternetGatewayDevice']['LANDevice']['1']['WLANConfiguration']['1']['TotalAssociations']['_value'])) {
                        $connectedDevicesSSID1 = (int)$device['InternetGatewayDevice']['LANDevice']['1']['WLANConfiguration']['1']['TotalAssociations']['_value'];
                    } elseif (isset($device['InternetGatewayDevice']['LANDevice']['1']['WLANConfiguration']['1']['AssociatedDeviceNumberOfEntries']['_value'])) {
                        $connectedDevicesSSID1 = (int)$device['InternetGatewayDevice']['LANDevice']['1']['WLANConfiguration']['1']['AssociatedDeviceNumberOfEntries']['_value'];
                    } elseif (isset($device['VirtualParameters']['activedevices']['_value'])) {
                        $connectedDevicesSSID1 = $device['VirtualParameters']['activedevices']['_value'];
                    } elseif (isset($device['VirtualParameters']['activedevices'])) {
                        $connectedDevicesSSID1 = $device['VirtualParameters']['activedevices'];
                    } elseif (isset($device['VirtualParameters']['ActiveDevices']['_value'])) {
                        $connectedDevicesSSID1 = $device['VirtualParameters']['ActiveDevices']['_value'];
                    } elseif (isset($device['VirtualParameters']['ConnectedDevices']['_value'])) {
                        $connectedDevicesSSID1 = $device['VirtualParameters']['ConnectedDevices']['_value'];
                    }
                    
                    $statusValue = 'offline';
                    if (isset($device['_lastInform'])) {
                        $lastInformTs = strtotime($device['_lastInform']);
                        if ($lastInformTs !== false) {
                            $statusValue = (time() - $lastInformTs) < GENIEACS_ONLINE_THRESHOLD ? 'online' : 'offline';
                        }
                    }
                    
                    // Populate ONU device snapshot from GenieACS data
                    $deviceSnapshot = [
                        'status' => $statusValue,
                        'device_id' => $device['_id'] ?? 'N/A',
                        'pppoe_username' => $device['VirtualParameters']['pppoeUsername']['_value'] ?? $device['VirtualParameters']['pppoeUsername'] ?? 'N/A',
                        'connected_devices' => $connectedDevicesSSID1,
                        'rx_power' => $device['VirtualParameters']['RXPower']['_value'] ?? $device['VirtualParameters']['RXPower'] ?? 'N/A',
                        'temperature' => $device['VirtualParameters']['gettemp']['_value'] ?? $device['VirtualParameters']['gettemp'] ?? 'N/A',
                        'serial_number' => $device['VirtualParameters']['getSerialNumber']['_value'] ?? $device['VirtualParameters']['getSerialNumber'] ?? 'N/A',
                        'pppoe_ip' => $device['VirtualParameters']['pppoeIP']['_value'] ?? $device['VirtualParameters']['pppoeIP'] ?? 'N/A',
                    ];
                } else {
                    $deviceSnapshot = [];
                }
                
                // Save to cache
                $_SESSION[$cacheKey] = [
                    'time' => time(),
                    'deviceSnapshot' => $deviceSnapshot,
                    'currentWiFi' => $currentWiFi
                ];

            }
        } catch (Throwable $e) {
            error_log("Billing Portal WiFi fetch error: " . $e->getMessage());
            if (strpos($e->getMessage(), 'GENIEACS_API_URL') === false) {
                $currentWiFi['error'] = $e->getMessage();
            }
        }
    }
    
    // RENDER HTML
    if (!empty($deviceSnapshot)) {
        $snapshotStatus = $deviceSnapshot['status'] ?? null;
        $statusLabel = $snapshotStatus ? strtoupper($snapshotStatus) : 'TIDAK DIKETAHUI';
        $statusClass = $snapshotStatus === 'online' ? 'online' : ($snapshotStatus === 'offline' ? 'offline' : '');
        $connectedDevices = $deviceSnapshot['connected_devices'] ?? null;
        $connectedLabel = $connectedDevices !== null ? $connectedDevices : 'N/A';
        $rxPowerRaw = $deviceSnapshot['rx_power'] ?? null;
        $rxLabel = ($rxPowerRaw !== null && $rxPowerRaw !== 'N/A' && $rxPowerRaw !== '') ? $rxPowerRaw . ' dBm' : 'N/A';
        $temperatureRaw = $deviceSnapshot['temperature'] ?? null;
        $temperatureLabel = ($temperatureRaw !== null && $temperatureRaw !== 'N/A' && $temperatureRaw !== '') ? $temperatureRaw . '°C' : 'N/A';
        $pppoeLabel = $deviceSnapshot['pppoe_username'] ?? 'N/A';
        ?>
        <div class="card">
            <div class="card-header">
                <h3><i class="fa fa-signal"></i> Informasi ONU</h3>
                <p style="margin:0; color:var(--dg-muted);">Data ditarik langsung dari GenieACS untuk memantau perangkat Anda.</p>
            </div>
            <div class="card-body">
                <div class="device-stats-grid">
                        <div class="device-stat">
                            <div class="label">Status ONU</div>
                            <div class="value device-status <?= htmlspecialchars($statusClass); ?>"><?= htmlspecialchars($statusLabel); ?></div>
                        <small style="color:var(--dg-muted);">Terhubung ke ACS sebagai <?= htmlspecialchars($deviceSnapshot['device_id'] ?? 'N/A'); ?></small>
                        </div>
                    
                    <?php if (!empty($currentWiFi['ssid'])): ?>
                    <div class="device-stat">
                        <div class="label">SSID Aktif</div>
                        <div class="value small" style="color: var(--dg-accent);"><?= htmlspecialchars($currentWiFi['ssid']); ?></div>
                        <small style="color:var(--dg-muted);">Nama WiFi yang terlihat</small>
                    </div>
                    <?php endif; ?>
                    
                    <div class="device-stat">
                        <div class="label">PPPoE Username</div>
                        <div class="value small"><?= htmlspecialchars($pppoeLabel ?: 'N/A'); ?></div>
                    </div>
                    <div class="device-stat">
                        <div class="label">Perangkat Terkoneksi</div>
                        <div class="value"><?= htmlspecialchars((string)$connectedLabel); ?></div>
                        <small style="color:var(--dg-muted);">Termasuk perangkat WiFi aktif</small>
                    </div>
                    <div class="device-stat">
                        <div class="label">RX Power</div>
                        <div class="value"><?= htmlspecialchars($rxLabel); ?></div>
                        <small style="color:var(--dg-muted);">Semakin dekat ke 0 dBm semakin baik</small>
                    </div>
                    <?php if ($temperatureLabel !== 'N/A'): ?>
                    <div class="device-stat">
                        <div class="label">Suhu Perangkat</div>
                        <div class="value"><?= htmlspecialchars($temperatureLabel); ?></div>
                        <small style="color:var(--dg-muted);">Suhu perangkat saat ini</small>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php
    } else {
        // Optional: Show message if no device found, or nothing
        echo '<div class="alert alert-warning">Tidak dapat menemukan data perangkat ONU. Pastikan perangkat hidup dan terhubung.</div>';
    }

} catch (Throwable $e) {
    echo '<div class="alert alert-danger">Terjadi kesalahan: ' . htmlspecialchars($e->getMessage()) . '</div>';
}
?>
