<?php
declare(strict_types=1);
session_start();
require_once '../config.php';
require_once __DIR__ . '/helpers.php';
if (!isset($_SESSION['user_id'])) { header('Location: ../login.php'); exit; }

// AI Settings are admin-only; tutors are not permitted here
if (($_SESSION['role'] ?? '') === 'tutor') {
    header('Location: index.php');
    exit;
}

$conn = getDBConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('Database connection failed.'); }

// Load current engine priority from DB
$priorityRow = $conn->query("SELECT setting_value FROM ai_engine_config WHERE setting_key='engine_priority' LIMIT 1");
$priorityOrder = ['claude', 'groq', 'gemini'];
if ($priorityRow && $row = $priorityRow->fetch_assoc()) {
    $parts = array_values(array_intersect(
        array_map('trim', explode(',', (string) $row['setting_value'])),
        ['claude', 'groq', 'gemini']
    ));
    if (count($parts) === 3) {
        $priorityOrder = $parts;
    }
}

$engineMeta = [
    'claude' => [
        'label'  => 'Claude AI',
        'icon'   => 'fas fa-robot',
        'color'  => 'primary',
        'note'   => 'Claude produces the highest quality exam questions. Recommended as primary engine.',
        'link'   => null,
        'models' => ['claude-opus-4-5', 'claude-sonnet-4-5', 'claude-haiku-4-5-20251001'],
        'key_const'   => 'CLAUDE_API_KEY',
        'model_const' => 'CLAUDE_MODEL',
    ],
    'groq' => [
        'label'  => 'Groq AI',
        'icon'   => 'fas fa-bolt',
        'color'  => 'warning',
        'note'   => 'Free tier: 14,400 requests/day. Very fast response times.',
        'link'   => 'https://console.groq.com',
        'models' => ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768', 'gemma2-9b-it'],
        'key_const'   => 'GROQ_API_KEY',
        'model_const' => 'GROQ_MODEL',
    ],
    'gemini' => [
        'label'  => 'Gemini Flash',
        'icon'   => 'fas fa-gem',
        'color'  => 'success',
        'note'   => 'Free tier: 1,500 requests/day.',
        'link'   => 'https://aistudio.google.com',
        'models' => ['gemini-1.5-flash', 'gemini-1.5-pro', 'gemini-2.0-flash'],
        'key_const'   => 'GEMINI_API_KEY',
        'model_const' => 'GEMINI_MODEL',
    ],
];

// Helper: mask API key — show last 6 chars
function maskKey(string $key): string {
    if ($key === '' || str_contains($key, 'YOUR_')) return '';
    $len = strlen($key);
    if ($len <= 6) return str_repeat('*', $len);
    return str_repeat('*', max(0, $len - 6)) . substr($key, -6);
}

function currentKey(string $constant): string {
    return defined($constant) ? (string) constant($constant) : '';
}
function currentModel(string $constant): string {
    return defined($constant) ? (string) constant($constant) : '';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exams — AI Settings</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .status-dot{width:10px;height:10px;border-radius:50%;display:inline-block;background:#ccc;transition:background .3s ease;flex-shrink:0}
        .status-dot.online{background:#28a745;box-shadow:0 0 6px #28a74580}
        .status-dot.offline{background:#dc3545}
        .status-dot.checking{background:#ffc107;animation:pulse 1s infinite}
        @keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}
        .priority-item{cursor:default;background:#fff;border:1px solid #dee2e6;border-radius:.5rem;padding:.75rem 1rem;display:flex;align-items:center;gap:.75rem;user-select:none}
        .priority-item .rank{width:1.8rem;height:1.8rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.85rem;flex-shrink:0}
    </style>
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar"><?php if (!defined('EDUTRACK_MODULES')) require_once __DIR__ . '/../module_definitions.php'; echo buildSidebar('exams_generator/' . basename($_SERVER['PHP_SELF'])); ?></nav>
    <div id="content" class="content">
        <header class="top-navbar d-flex justify-content-between align-items-center flex-wrap gap-2">
            <div>
                <h4 class="mb-1">Exams — AI Settings</h4>
                <div class="text-muted small">Configure API keys, engine priority, and monitor generation activity.</div>
            </div>
        </header>
        <main class="container-fluid py-4">
            <?= examsRenderTabs('ai-settings') ?>

            <div id="toast-area" style="position:fixed;top:1rem;right:1rem;z-index:9999;min-width:280px"></div>

            <!-- ── SECTION 1: API KEY CONFIGURATION ──────────────────── -->
            <h5 class="mb-3"><i class="fas fa-key me-2 text-primary"></i>API Key Configuration</h5>
            <form id="keysForm">
                <input type="hidden" name="action" value="keys">

                <?php foreach ($engineMeta as $engine => $meta):
                    $existingKey   = currentKey($meta['key_const']);
                    $existingModel = currentModel($meta['model_const']);
                    $masked        = maskKey($existingKey);
                    $isSet         = ($masked !== '');
                    $collapseId    = "collapse-{$engine}";
                ?>
                <div class="card shadow-sm border-0 mb-3">
                    <div class="card-header d-flex align-items-center justify-content-between gap-2">
                        <div class="d-flex align-items-center gap-2">
                            <span class="status-dot checking" id="dot-<?= $engine ?>"></span>
                            <i class="<?= $meta['icon'] ?> text-<?= $meta['color'] ?>"></i>
                            <strong><?= htmlspecialchars($meta['label']) ?></strong>
                            <?php if ($isSet): ?>
                                <span class="badge bg-success ms-1">Key Set</span>
                            <?php else: ?>
                                <span class="badge bg-secondary ms-1">Not Configured</span>
                            <?php endif; ?>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <span class="badge bg-light text-dark border" id="lat-<?= $engine ?>"></span>
                            <button type="button" class="btn btn-sm btn-outline-<?= $meta['color'] ?>"
                                    onclick="testEngine('<?= $engine ?>')">
                                <i class="fas fa-plug me-1"></i>Test
                            </button>
                            <button class="btn btn-sm btn-outline-secondary" type="button"
                                    data-bs-toggle="collapse" data-bs-target="#<?= $collapseId ?>">
                                <i class="fas fa-chevron-down"></i>
                            </button>
                        </div>
                    </div>
                    <div class="collapse" id="<?= $collapseId ?>">
                        <div class="card-body">
                            <div class="alert alert-light border mb-3">
                                <i class="fas fa-info-circle me-1 text-muted"></i>
                                <?= htmlspecialchars($meta['note']) ?>
                                <?php if ($meta['link']): ?>
                                    — <a href="<?= htmlspecialchars($meta['link']) ?>" target="_blank" rel="noopener">
                                        Get free key <i class="fas fa-external-link-alt ms-1 small"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                            <div class="row g-3">
                                <div class="col-md-8">
                                    <label class="form-label fw-semibold">API Key</label>
                                    <input type="password" class="form-control font-monospace"
                                           name="<?= $engine ?>_api_key"
                                           placeholder="<?= $isSet ? 'Leave blank to keep existing (' . htmlspecialchars($masked) . ')' : 'Paste your API key here' ?>"
                                           autocomplete="new-password">
                                    <div class="form-text">Leave blank to keep the current value.</div>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label fw-semibold">Model</label>
                                    <select class="form-select" name="<?= $engine ?>_model">
                                        <?php foreach ($meta['models'] as $m): ?>
                                            <option value="<?= htmlspecialchars($m) ?>"
                                                <?= ($existingModel === $m) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($m) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>

                <div class="d-flex align-items-center gap-3 mb-5">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i>Save API Keys & Models
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="checkAllEngines()">
                        <i class="fas fa-sync-alt me-1"></i>Check All Engines
                    </button>
                </div>
            </form>

            <!-- ── SECTION 2: ENGINE PRIORITY ────────────────────────── -->
            <h5 class="mb-3"><i class="fas fa-sort-amount-down me-2 text-primary"></i>Engine Priority Order</h5>
            <div class="card shadow-sm border-0 mb-5">
                <div class="card-body">
                    <div class="alert alert-light border mb-3">
                        <i class="fas fa-info-circle me-1 text-muted"></i>
                        The system tries engines in this order. If the first engine fails or is not configured,
                        it automatically tries the next.
                    </div>
                    <div id="priority-list" class="d-flex flex-column gap-2 mb-3" style="max-width:480px">
                        <?php
                        $rankColors = ['bg-primary', 'bg-warning', 'bg-success'];
                        foreach ($priorityOrder as $idx => $engine):
                            $meta = $engineMeta[$engine];
                        ?>
                        <div class="priority-item" data-engine="<?= $engine ?>">
                            <span class="rank <?= $rankColors[$idx] ?> text-white"><?= $idx + 1 ?></span>
                            <i class="<?= $meta['icon'] ?> text-<?= $meta['color'] ?>"></i>
                            <span class="fw-semibold"><?= htmlspecialchars($meta['label']) ?></span>
                            <div class="ms-auto d-flex gap-1">
                                <button type="button" class="btn btn-sm btn-outline-secondary"
                                        onclick="movePriority('<?= $engine ?>', -1)" title="Move up">
                                    <i class="fas fa-arrow-up"></i>
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary"
                                        onclick="movePriority('<?= $engine ?>', 1)" title="Move down">
                                    <i class="fas fa-arrow-down"></i>
                                </button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="button" class="btn btn-primary" onclick="savePriority()">
                        <i class="fas fa-save me-1"></i>Save Priority Order
                    </button>
                </div>
            </div>

            <!-- ── SECTION 3: GENERATION LOG ─────────────────────────── -->
            <h5 class="mb-3"><i class="fas fa-history me-2 text-primary"></i>Generation Log</h5>
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-body">
                    <div class="table-responsive">
                        <table id="genLogTable" class="table table-sm align-middle w-100">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Subject</th>
                                    <th>Class</th>
                                    <th>Questions</th>
                                    <th>Engine Used</th>
                                    <th>Status</th>
                                    <th>Duration</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script>
function esc(v){return String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));}

const engineLabels = {
    claude: '<span class="badge bg-primary"><i class="fas fa-robot me-1"></i>Claude AI</span>',
    groq:   '<span class="badge bg-warning text-dark"><i class="fas fa-bolt me-1"></i>Groq AI</span>',
    gemini: '<span class="badge bg-success"><i class="fas fa-gem me-1"></i>Gemini AI</span>',
};

// ── Toast ────────────────────────────────────────────────────────
function toast(msg, type='success') {
    const id = 'toast_' + Date.now();
    const color = type === 'success' ? 'bg-success' : (type === 'warning' ? 'bg-warning text-dark' : 'bg-danger');
    document.getElementById('toast-area').insertAdjacentHTML('beforeend',
        `<div id="${id}" class="toast show align-items-center text-white ${color} border-0 mb-2" role="alert">
           <div class="d-flex"><div class="toast-body">${esc(msg)}</div>
           <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div>
         </div>`
    );
    setTimeout(() => document.getElementById(id)?.remove(), 4000);
}

// ── Single engine test ───────────────────────────────────────────
function testEngine(engine) {
    const dot = document.getElementById('dot-' + engine);
    const lat = document.getElementById('lat-' + engine);
    dot.className = 'status-dot checking';
    lat.textContent = '...';
    fetch('ajax/check_ai_status.php')
        .then(r => r.json())
        .then(data => {
            const info = data[engine];
            if (!info) return;
            if (info.status === 'online') {
                dot.className = 'status-dot online';
                lat.textContent = info.latency;
                toast(engine.charAt(0).toUpperCase() + engine.slice(1) + ' is online (' + info.latency + ')');
            } else {
                dot.className = 'status-dot offline';
                lat.textContent = '✕';
                toast('Engine offline: ' + (info.error ?? 'unknown error'), 'danger');
            }
        })
        .catch(() => { dot.className = 'status-dot offline'; lat.textContent = '✕'; });
}

// ── Check all engines ────────────────────────────────────────────
function checkAllEngines() {
    ['claude','groq','gemini'].forEach(e => {
        document.getElementById('dot-' + e).className = 'status-dot checking';
        document.getElementById('lat-' + e).textContent = '...';
    });
    fetch('ajax/check_ai_status.php')
        .then(r => r.json())
        .then(data => {
            ['claude','groq','gemini'].forEach(e => {
                const dot  = document.getElementById('dot-' + e);
                const lat  = document.getElementById('lat-' + e);
                const info = data[e];
                if (!info) return;
                if (info.status === 'online') {
                    dot.className = 'status-dot online';
                    lat.textContent = info.latency;
                } else {
                    dot.className = 'status-dot offline';
                    lat.textContent = '✕';
                    lat.title = info.error ?? '';
                }
            });
        })
        .catch(() => {});
}

// ── Save API keys form ───────────────────────────────────────────
document.getElementById('keysForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const btn = this.querySelector('[type=submit]');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';
    try {
        const res  = await fetch('ajax/save_ai_settings.php', {method:'POST', body: new FormData(this)});
        const data = await res.json();
        toast(data.message ?? (data.success ? 'Saved' : 'Error'), data.success ? 'success' : 'danger');
    } catch {
        toast('Request failed', 'danger');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-save me-1"></i>Save API Keys & Models';
    }
});

// ── Priority reordering ──────────────────────────────────────────
const rankColors = ['bg-primary','bg-warning','bg-success'];

function refreshRankBadges() {
    document.querySelectorAll('#priority-list .priority-item').forEach((el, idx) => {
        const span = el.querySelector('.rank');
        span.className = 'rank ' + rankColors[idx] + ' text-white';
        span.textContent = idx + 1;
    });
}

function movePriority(engine, dir) {
    const list  = document.getElementById('priority-list');
    const items = [...list.querySelectorAll('.priority-item')];
    const idx   = items.findIndex(el => el.dataset.engine === engine);
    const newIdx = idx + dir;
    if (newIdx < 0 || newIdx >= items.length) return;

    if (dir === -1) {
        list.insertBefore(items[idx], items[idx - 1]);
    } else {
        list.insertBefore(items[idx + 1], items[idx]);
    }
    refreshRankBadges();
}

async function savePriority() {
    const order = [...document.querySelectorAll('#priority-list .priority-item')]
        .map(el => el.dataset.engine)
        .join(',');
    const body = new URLSearchParams({action: 'priority', priority: order});
    try {
        const res  = await fetch('ajax/save_ai_settings.php', {method:'POST', body});
        const data = await res.json();
        toast(data.message ?? (data.success ? 'Priority saved' : 'Error'), data.success ? 'success' : 'danger');
    } catch {
        toast('Request failed', 'danger');
    }
}

// ── Generation log DataTable ─────────────────────────────────────
async function loadGenLog() {
    const res  = await fetch('ajax/get_generation_jobs.php', {method:'POST'});
    const jobs = await res.json();

    const table = $('#genLogTable').DataTable({
        destroy: true,
        data: jobs.slice(0, 50),
        order: [[0, 'desc']],
        columns: [
            {data: 'created_at', render: v => esc(v)},
            {data: null, render: r => esc(r.subject_name ?? '')},
            {data: 'class_name', render: v => esc(v)},
            {data: null, render: r => {
                const n = (parseInt(r.mcq_count||0,10) + parseInt(r.theory_count||0,10) + parseInt(r.fill_blank_count||0,10));
                return esc(String(n));
            }},
            {data: 'engine_used', render: v => engineLabels[v] || (v ? esc(v) : '<span class="text-muted">—</span>')},
            {data: 'status', render: v => {
                const cls = v === 'done' ? 'bg-success' : v === 'failed' ? 'bg-danger' : 'bg-warning text-dark';
                return `<span class="badge ${cls}">${esc(v)}</span>`;
            }},
            {data: 'duration_seconds', render: v => v != null ? esc(String(v)) + 's' : '—'},
        ],
        language: {emptyTable: 'No generation jobs yet.'},
    });
}

// On page load
checkAllEngines();
loadGenLog();
</script>
</body>
</html>
