<?php
require_once '../includes/config.php';
requireAdmin();
$db = getDB();

// Create error_logs table if not exists
$db->exec("CREATE TABLE IF NOT EXISTS error_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    type VARCHAR(50) DEFAULT 'error',
    source VARCHAR(100),
    message TEXT,
    context TEXT,
    user_id INT DEFAULT NULL,
    ip VARCHAR(50),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    is_read TINYINT DEFAULT 0
)");

// Actions
if ($_POST['action'] ?? '' === 'clear_all') {
    $db->exec("DELETE FROM error_logs WHERE is_read=1");
    $msg = ['ok'=>true,'text'=>'Read logs cleared!'];
}
if ($_POST['action'] ?? '' === 'mark_read') {
    $db->exec("UPDATE error_logs SET is_read=1");
    $msg = ['ok'=>true,'text'=>'All marked as read!'];
}
if ($_POST['action'] ?? '' === 'delete_all') {
    $db->exec("TRUNCATE TABLE error_logs");
    $msg = ['ok'=>true,'text'=>'All logs deleted!'];
}

// Live API Tests
$testResults = [];
if ($_GET['test'] ?? '' === '1') {
    // Test ECARE
    try {
        require_once '../includes/ecare.php';
        $ecBal = ecareBalance();
        $testResults['ecare'] = $ecBal['status']==='OK'
            ? ['ok'=>true,'msg'=>'✅ Connected | Balance: ৳'.$ecBal['main_balance']]
            : ['ok'=>false,'msg'=>'❌ '.$ecBal['message']];
    } catch(Exception $e) { $testResults['ecare'] = ['ok'=>false,'msg'=>'❌ '.$e->getMessage()]; }

    // Test SuccessTopUp
    try {
        require_once '../includes/successtopup.php';
        $stBal = successTopupBalance();
        $testResults['st'] = isset($stBal['balance'])
            ? ['ok'=>true,'msg'=>'✅ Connected | Balance: ৳'.$stBal['balance']]
            : ['ok'=>false,'msg'=>'❌ '.($stBal['message']??'Failed')];
    } catch(Exception $e) { $testResults['st'] = ['ok'=>false,'msg'=>'❌ '.$e->getMessage()]; }

    // Test DB
    try {
        $db->query("SELECT 1");
        $testResults['db'] = ['ok'=>true,'msg'=>'✅ Connected'];
    } catch(Exception $e) { $testResults['db'] = ['ok'=>false,'msg'=>'❌ '.$e->getMessage()]; }

    // Test Telegram
    try {
        require_once '../includes/telegram.php';
        $token = getSetting('telegram_bot_token');
        $chatId = getSetting('telegram_chat_id');
        $testResults['telegram'] = ($token && $chatId)
            ? ['ok'=>true,'msg'=>'✅ Configured | Token: '.substr($token,0,10).'...']
            : ['ok'=>false,'msg'=>'❌ Token or Chat ID not set'];
    } catch(Exception $e) { $testResults['telegram'] = ['ok'=>false,'msg'=>'❌ '.$e->getMessage()]; }

    // Test DingConnect
    try {
        require_once '../includes/dingconnect.php';
        $testResults['ding'] = dingIsConfigured()
            ? ['ok'=>true,'msg'=>'✅ Configured']
            : ['ok'=>false,'msg'=>'❌ API Key not configured'];
    } catch(Exception $e) { $testResults['ding'] = ['ok'=>false,'msg'=>'❌ '.$e->getMessage()]; }
}

// Load logs
$type   = $_GET['type'] ?? '';
$where  = $type ? "WHERE type=?" : "WHERE 1=1";
$params = $type ? [$type] : [];
$logs   = $db->prepare("SELECT * FROM error_logs $where ORDER BY created_at DESC LIMIT 200");
$logs->execute($params);
$logs   = $logs->fetchAll();

// Stats
$stats = $db->query("SELECT type, COUNT(*) as cnt, SUM(is_read=0) as unread FROM error_logs GROUP BY type")->fetchAll();
$total = $db->query("SELECT COUNT(*) FROM error_logs WHERE is_read=0")->fetchColumn();

// Recent API failures from transactions
$apiFailures = $db->query("
    SELECT t.*, u.name as uname FROM transactions t
    JOIN users u ON t.user_id=u.id
    WHERE t.status='failed' AND t.created_at >= NOW()-INTERVAL 24 HOUR
    ORDER BY t.created_at DESC LIMIT 20
")->fetchAll();

$recentPending = $db->query("
    SELECT t.*, u.name as uname FROM transactions t
    JOIN users u ON t.user_id=u.id
    WHERE t.status='pending' AND t.created_at >= NOW()-INTERVAL 2 HOUR
    ORDER BY t.created_at DESC LIMIT 20
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Error Logs — Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
:root{--primary:#1a3c8f;--dark:#0d1f4e;--success:#38a169;--danger:#e53e3e;--warn:#d69e2e}
.card{background:white;border-radius:14px;box-shadow:0 2px 10px rgba(0,0,0,0.06);margin-bottom:18px;overflow:hidden}
.card-h{padding:14px 18px;font-size:14px;font-weight:700;border-bottom:1px solid #f5f5f5;display:flex;align-items:center;justify-content:space-between;gap:8px}
.card-b{padding:0}
.btn{padding:8px 14px;border:none;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px;transition:0.15s}
.btn-primary{background:var(--primary);color:white}
.btn-danger{background:#fff5f5;color:var(--danger)}
.btn-warn{background:#fffbeb;color:var(--warn)}
.btn-sm{padding:5px 10px;font-size:11px}
.alert{padding:10px 14px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}

/* API Status Cards */
.api-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px;margin-bottom:20px}
.api-card{background:white;border-radius:12px;padding:14px 16px;box-shadow:0 2px 8px rgba(0,0,0,0.06);border-left:4px solid #e8ecf4}
.api-card.ok{border-left-color:var(--success)}
.api-card.fail{border-left-color:var(--danger)}
.api-card.unknown{border-left-color:#e8ecf4}
.api-name{font-size:12px;font-weight:800;color:#555;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:6px}
.api-status{font-size:13px;font-weight:700}
.api-status.ok{color:var(--success)}
.api-status.fail{color:var(--danger)}

/* Log table */
.log-table{width:100%;border-collapse:collapse}
.log-table th{padding:9px 14px;text-align:left;font-size:11px;color:#888;font-weight:700;text-transform:uppercase;border-bottom:2px solid #f5f5f5;background:#fafbfc}
.log-table td{padding:10px 14px;border-bottom:1px solid #f9f9f9;font-size:12px;vertical-align:top}
.log-table tr:hover td{background:#fafbff}
.log-table tr.unread td{background:#fffbeb}
.type-badge{display:inline-block;padding:2px 9px;border-radius:20px;font-size:10px;font-weight:800;text-transform:uppercase}
.t-error{background:#fff5f5;color:var(--danger)}
.t-warning{background:#fffbeb;color:var(--warn)}
.t-info{background:#ebf8ff;color:#2b6cb0}
.t-api{background:#f0fff4;color:var(--success)}

/* Stat pills */
.stat-pills{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px}
.pill{padding:6px 14px;border-radius:20px;font-size:12px;font-weight:700;cursor:pointer;border:2px solid transparent;transition:0.15s}
.pill.active,.pill:hover{border-color:var(--primary);color:var(--primary)}
.pill-all{background:#f0f4ff}
.pill-error{background:#fff5f5;color:var(--danger)}
.pill-warning{background:#fffbeb;color:var(--warn)}
.pill-api{background:#f0fff4;color:var(--success)}

/* Recent failures */
.fail-row{padding:12px 16px;border-bottom:1px solid #f5f5f5;display:flex;align-items:flex-start;gap:10px}
.fail-row:last-child{border:none}
.fail-icon{width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0}
.fi-fail{background:#fff5f5}
.fi-pend{background:#fffbeb}
.fail-info{flex:1;min-width:0}
.fail-ref{font-size:11px;font-family:monospace;color:#aaa}
.fail-note{font-size:12px;color:#555;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.fail-time{font-size:11px;color:#aaa;flex-shrink:0}

.empty-state{text-align:center;padding:40px;color:#ccc}
.empty-state i{font-size:36px;display:block;margin-bottom:10px}
</style>
</head>
<body>
<div style="display:flex;min-height:100vh">
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title"><i class="fas fa-exclamation-triangle" style="color:var(--danger)"></i> Error & System Logs</span>
    </div>
    <div class="topbar-right" style="gap:8px">
        <a href="?test=1" class="btn btn-primary"><i class="fas fa-plug"></i> Test APIs</a>
        <form method="POST" style="display:inline">
            <input type="hidden" name="action" value="mark_read">
            <button type="submit" class="btn btn-warn btn-sm"><i class="fas fa-check-double"></i> Mark All Read</button>
        </form>
        <form method="POST" style="display:inline" onsubmit="return confirm('Delete all logs?')">
            <input type="hidden" name="action" value="delete_all">
            <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i> Clear All</button>
        </form>
    </div>
</div>

<div class="content">
<?php if(isset($msg)): ?>
<div class="alert alert-ok"><?= $msg['text'] ?></div>
<?php endif; ?>

<!-- API Status Tests -->
<?php if(!empty($testResults)): ?>
<div class="card" style="margin-bottom:18px">
    <div class="card-h"><i class="fas fa-plug" style="color:var(--primary)"></i> API Connection Test</div>
    <div style="padding:16px">
        <div class="api-grid">
            <?php
            $apiNames = ['ecare'=>'⚡ ECARE','st'=>'🔄 SuccessTopUp','db'=>'🗄️ Database','telegram'=>'📱 Telegram','ding'=>'🌍 DingConnect'];
            foreach($apiNames as $key=>$name):
                $r = $testResults[$key] ?? null;
                $cls = $r ? ($r['ok']?'ok':'fail') : 'unknown';
            ?>
            <div class="api-card <?= $cls ?>">
                <div class="api-name"><?= $name ?></div>
                <?php if($r): ?>
                <div class="api-status <?= $r['ok']?'ok':'fail' ?>"><?= $r['msg'] ?></div>
                <?php else: ?>
                <div style="font-size:12px;color:#aaa">Not tested</div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php else: ?>
<!-- Quick API Status (live check without test param) -->
<div class="api-grid" style="margin-bottom:18px">
    <?php
    $checks = [
        ['⚡ ECARE', getSetting('ecare_username') && getSetting('ecare_password')],
        ['🔄 SuccessTopUp', getSetting('st_api_key')],
        ['🌍 DingConnect', getSetting('ding_api_key')],
        ['📱 Telegram', getSetting('telegram_bot_token') && getSetting('telegram_chat_id')],
        ['🗄️ Database', true],
    ];
    foreach($checks as $c):
        $ok = (bool)$c[1];
    ?>
    <div class="api-card <?= $ok?'ok':'fail' ?>">
        <div class="api-name"><?= $c[0] ?></div>
        <div class="api-status <?= $ok?'ok':'fail' ?>"><?= $ok?'✅ Configured':'❌ Not Configured' ?></div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:18px">

    <!-- Recent API Failures -->
    <div class="card">
        <div class="card-h">
            <span><i class="fas fa-times-circle" style="color:var(--danger)"></i> Recent Failures (24h)</span>
            <span style="background:#fff5f5;color:var(--danger);font-size:11px;font-weight:800;padding:3px 10px;border-radius:20px"><?= count($apiFailures) ?></span>
        </div>
        <div class="card-b">
            <?php if(empty($apiFailures)): ?>
            <div class="empty-state"><i class="fas fa-check-circle" style="color:var(--success)"></i>No failures!</div>
            <?php else: foreach($apiFailures as $f): ?>
            <div class="fail-row">
                <div class="fail-icon fi-fail">❌</div>
                <div class="fail-info">
                    <div style="font-size:12px;font-weight:700"><?= htmlspecialchars($f['uname']) ?> · <?= $f['type'] ?></div>
                    <div class="fail-note"><?= htmlspecialchars(substr($f['note']??'—',0,80)) ?></div>
                    <div class="fail-ref"><?= $f['reference'] ?></div>
                </div>
                <div class="fail-time"><?= date('h:i A',strtotime($f['created_at'])) ?></div>
            </div>
            <?php endforeach; endif; ?>
        </div>
    </div>

    <!-- Pending > 1hr -->
    <div class="card">
        <div class="card-h">
            <span><i class="fas fa-clock" style="color:var(--warn)"></i> Stuck Pending (2h)</span>
            <span style="background:#fffbeb;color:var(--warn);font-size:11px;font-weight:800;padding:3px 10px;border-radius:20px"><?= count($recentPending) ?></span>
        </div>
        <div class="card-b">
            <?php if(empty($recentPending)): ?>
            <div class="empty-state"><i class="fas fa-check-circle" style="color:var(--success)"></i>All clear!</div>
            <?php else: foreach($recentPending as $p): ?>
            <div class="fail-row">
                <div class="fail-icon fi-pend">⏳</div>
                <div class="fail-info">
                    <div style="font-size:12px;font-weight:700"><?= htmlspecialchars($p['uname']) ?> · <?= $p['type'] ?> · ৳<?= number_format($p['amount'],2) ?></div>
                    <div class="fail-note"><?= htmlspecialchars(substr($p['note']??'—',0,80)) ?></div>
                    <div class="fail-ref"><?= $p['reference'] ?></div>
                </div>
                <div class="fail-time"><?= date('h:i A',strtotime($p['created_at'])) ?></div>
            </div>
            <?php endforeach; endif; ?>
        </div>
    </div>

</div>

<!-- System Error Logs -->
<div class="card">
    <div class="card-h">
        <span><i class="fas fa-list-alt" style="color:#805ad5"></i> System Logs</span>
        <span style="font-size:12px;color:#aaa"><?= count($logs) ?> entries</span>
    </div>
    <div style="padding:14px 16px;border-bottom:1px solid #f5f5f5">
        <div class="stat-pills">
            <a href="?" class="pill pill-all <?= !$type?'active':'' ?>">All (<?= array_sum(array_column($stats,'cnt')) ?>)</a>
            <?php foreach($stats as $s): ?>
            <a href="?type=<?= $s['type'] ?>" class="pill pill-<?= $s['type'] ?> <?= $type===$s['type']?'active':'' ?>">
                <?= ucfirst($s['type']) ?> (<?= $s['cnt'] ?>)
                <?php if($s['unread']>0): ?><span style="background:var(--danger);color:white;font-size:10px;padding:1px 6px;border-radius:10px;margin-left:3px"><?= $s['unread'] ?></span><?php endif; ?>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php if(empty($logs)): ?>
    <div class="empty-state"><i class="fas fa-shield-alt"></i>No logs found<?= $type ? " for type: $type" : '' ?></div>
    <?php else: ?>
    <div style="overflow-x:auto">
    <table class="log-table">
        <thead><tr>
            <th>#</th><th>Type</th><th>Source</th><th>Message</th><th>User</th><th>Time</th>
        </tr></thead>
        <tbody>
        <?php foreach($logs as $l): ?>
        <tr class="<?= $l['is_read']?'':'unread' ?>">
            <td style="color:#aaa"><?= $l['id'] ?></td>
            <td><span class="type-badge t-<?= $l['type'] ?>"><?= $l['type'] ?></span></td>
            <td style="font-family:monospace;font-size:11px;color:#888"><?= htmlspecialchars($l['source']??'—') ?></td>
            <td style="max-width:400px">
                <div style="font-size:12px;color:#333"><?= htmlspecialchars(substr($l['message']??'',0,150)) ?></div>
                <?php if($l['context']): ?>
                <div style="font-size:11px;color:#aaa;font-family:monospace;margin-top:3px"><?= htmlspecialchars(substr($l['context']??'',0,100)) ?></div>
                <?php endif; ?>
            </td>
            <td style="font-size:11px;color:#888"><?= $l['user_id'] ? '#'.$l['user_id'] : '—' ?></td>
            <td style="font-size:11px;color:#aaa;white-space:nowrap"><?= date('d M, h:i A',strtotime($l['created_at'])) ?></td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>
</div>

</div>
</div>
</div>
</body>
</html>
