<?php
/**
 * NOC DASHBOARD - POWER SMPP DATABASE INTEGRATION
 * Based on Busybee API Documentation v2
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

$accounts = [
    'ItnioTech_S'     => ['id' => '80ded92d-39f3-417b-b905-6a8fb6c819ca', 'key' => 'H9m//5YGbcK2zqS+A6T4J/jASOVKBHizHa2NNX2hUGw=', 'type' => 'Smart'],
    'ItnioTech_G'     => ['id' => 'b00cff7b-6ac8-40c0-ad3e-e8ab1f1416d5', 'key' => 'cBGgg8Hd1VJALFBsy230PeuQwJqq5iZpewhWGz2S0EA=', 'type' => 'Globe'],
    'ItnioTech_OTP_S' => ['id' => 'e502c0d3-a31c-4255-a51a-e36f2aeb4ea0', 'key' => 'dyPBVNTnS2dMAo/DGKQSmcriIJWm1HGyXU/7ECWKUDs=', 'type' => 'Smart'],
    'ItnioTech_OTP_G' => ['id' => '161823ed-6eb7-439f-94f4-ec80152956c6', 'key' => 'cOpePXOe6n6AWhXdqXeHN5c8g41SFKY/ZCyq/4eZbHc=', 'type' => 'Globe'],
];

if (isset($_GET['action']) && $_GET['action'] == 'poll') {
    header('Content-Type: application/json');
    $results = [];
    
    // Per Manual Page 28: Date format must be yyyy-mm-dd
    $today = date('Y-m-d');

    foreach ($accounts as $name => $creds) {
        $apiKey = urlencode($creds['key']);
        $clientId = urlencode($creds['id']);
        
        // 1. Connection/Balance Check (Manual Page 1)
        $ch = curl_init("http://34.80.139.96/api/v2/Balance?ApiKey={$apiKey}&ClientId={$clientId}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        $resBal = curl_exec($ch);
        $balData = json_decode($resBal, true);
        $isOnline = (isset($balData['ErrorCode']) && $balData['ErrorCode'] === 0);

        // 2. Get Sent Message List (Manual Page 28)
        // URL Structure: /api/v2/SMS?ApiKey={K}&ClientId={I}&start=0&length=7&fromdate={D}&enddate={D}
        $smsUrl = "http://34.80.139.96/api/v2/SMS?ApiKey={$apiKey}&ClientId={$clientId}&start=0&length=7&fromdate={$today}&enddate={$today}";
        
        curl_setopt($ch, CURLOPT_URL, $smsUrl);
        $resSms = curl_exec($ch);
        curl_close($ch);

        $apiData = json_decode($resSms, true);
        
        // Path: Data -> messages (Manual Page 29)
        $smsList = $apiData['Data']['messages'] ?? [];
        
        $finalMessages = [];
        if (is_array($smsList)) {
            foreach ($smsList as $m) {
                // Status mapping per Manual Page 30 (e.g., DELIVRD)
                $status = $m['Status'] ?? 'PENDING';
                if ($status === "DELIVRD") $status = "DELIVERED";

                $finalMessages[] = [
                    'mobile' => $m['MobileNumber'] ?? 'Unknown',
                    'status' => $status,
                    // SubmitDate format: "16-Mar-2018 05:12:28 PM"
                    'time'   => isset($m['SubmitDate']) ? substr($m['SubmitDate'], 12, 8) : '--:--'
                ];
            }
        }

        $results[$name] = [
            'type' => $creds['type'],
            'online' => $isOnline,
            'messages' => $finalMessages
        ];
    }
    echo json_encode($results);
    exit;
}

// Global Feed (Webhook logs)
if (isset($_GET['action']) && $_GET['action'] == 'smpp_feed') {
    header('Content-Type: application/json');
    $feed = [];
    $logFile = __DIR__ . '/smpp_logs.json';
    if (file_exists($logFile)) {
        $lines = array_slice(file($logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES), -15);
        foreach (array_reverse($lines) as $line) {
            $d = json_decode($line, true);
            if ($d) $feed[] = $d;
        }
    }
    echo json_encode($feed);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <title>NOC DASHBOARD</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background-color: #020617; color: #f1f5f9; font-family: ui-monospace, monospace; }
        .card { background: #0f172a; border: 1px solid #1e293b; border-radius: 8px; min-height: 350px; }
    </style>
</head>
<body class="p-6">
    <div class="max-w-[1600px] mx-auto">
        <div class="flex justify-between items-end mb-8 border-b border-slate-800 pb-4">
            <div>
                <h1 class="text-2xl font-black tracking-tighter text-white">NOC_REPORTS</h1>
                <p class="text-[10px] text-slate-500 font-bold uppercase">Source: Busybee API v2 Database</p>
            </div>
            <div id="sync" class="text-[10px] text-emerald-500 font-bold italic uppercase">Initializing...</div>
        </div>

        <div class="grid grid-cols-4 gap-6">
            <div id="boxes" class="col-span-3 grid grid-cols-2 gap-4">
                </div>
            
            <div class="col-span-1 card p-4 h-[750px] flex flex-col">
                <h3 class="text-center text-[10px] font-bold text-slate-400 uppercase mb-4 border-b border-slate-800 pb-2">Global Webhook Feed</h3>
                <div id="feed" class="overflow-y-auto space-y-1"></div>
            </div>
        </div>
    </div>

    <script>
        async function update() {
            try {
                const res = await fetch('?action=poll');
                const data = await res.json();
                const container = document.getElementById('boxes');
                container.innerHTML = '';

                for (const [name, acc] of Object.entries(data)) {
                    let rows = acc.messages.map(m => {
                        let color = 'text-cyan-400';
                        if (m.status.includes('DELIV')) color = 'text-emerald-400';
                        if (m.status.includes('FAIL') || m.status.includes('REJECT')) color = 'text-rose-500';

                        return `<div class="flex justify-between items-center py-2 border-b border-slate-800/40">
                                    <span class="text-slate-300 text-xs font-bold">${m.mobile}</span>
                                    <div class="text-right">
                                        <span class="${color} font-black text-[10px] uppercase">${m.status}</span>
                                        <div class="text-[8px] text-slate-600">${m.time}</div>
                                    </div>
                                </div>`;
                    }).join('');

                    container.innerHTML += `
                        <div class="card p-5">
                            <div class="flex justify-between items-start mb-4">
                                <div>
                                    <h3 class="font-black text-slate-100 tracking-tight text-sm">${name}</h3>
                                    <span class="text-[9px] bg-slate-800 px-2 py-0.5 rounded text-slate-400 font-bold uppercase">${acc.type}</span>
                                </div>
                                <div class="text-[9px] font-bold ${acc.online?'text-emerald-500':'text-rose-500'}">
                                    ${acc.online ? '● LIVE' : '○ ERROR'}
                                </div>
                            </div>
                            <div class="min-h-[250px]">
                                ${rows || '<div class="text-center py-20 text-slate-800 text-xs font-bold uppercase tracking-widest">No Records Today</div>'}
                            </div>
                        </div>`;
                }

                const fRes = await fetch('?action=smpp_feed');
                const fData = await fRes.json();
                document.getElementById('feed').innerHTML = fData.length ? fData.map(l => `
                    <div class="p-2 border border-slate-800/50 rounded bg-slate-900/50 text-[10px]">
                        <div class="flex justify-between font-bold ${l.status.includes('DELIV')?'text-emerald-500':'text-cyan-400'}">
                            <span>${l.status}</span><span class="text-slate-700 text-[8px]">${l.time.split(' ')[1] || ''}</span>
                        </div>
                        <div class="flex justify-between mt-1 text-slate-500">
                            <span>${l.mobile}</span><span class="text-[8px] uppercase font-black">${l.user}</span>
                        </div>
                    </div>`).join('') : '<div class="text-center py-10 text-slate-800 text-[9px] uppercase font-bold">Waiting for webhooks...</div>';

                document.getElementById('sync').innerText = 'LAST_SYNC: ' + new Date().toLocaleTimeString();
            } catch (e) { 
                console.error("Dashboard Sync Error:", e);
                document.getElementById('sync').innerText = 'SYNC_FAILED';
            }
        }
        setInterval(update, 5000); 
        update();
    </script>
</body>
</html>