<?php

/**

 * RBC AI Agent — EduTrack Hub

 * Full conversational agent with streaming responses and memory.

 */

if (session_status() === PHP_SESSION_NONE) session_start();

set_time_limit(300); // 5 minutes for AI operations



if (!isset($_SESSION['user_id'])) {

    header('Location: index.php');

    exit;

}



$allowed_roles = ['admin', 'accountant', 'director', 'supervisor', 'headteacher'];

if (!in_array($_SESSION['role'], $allowed_roles)) {

    header('Location: dashboard.php?error=access_denied');

    exit;

}



require_once 'config.php';

requireModule('ai_agent');

require_once 'ai/provider_engine.php';

require_once 'ai/agent_guard.php';

$rbc_csrf = rbcAgentCsrfToken();



$conn = getDBConnection();



// Provider status

$providers       = ['claude', 'groq', 'gemini', 'openai'];

$provider_status = [];

foreach ($providers as $p) {

    $provider_status[$p] = RBCAIEngine::isConfigured($p);

}

$any_provider_configured = in_array(true, $provider_status, true);



// Recent tasks

$recent_tasks = [];

$tasks_result = $conn->query(

    "SELECT id, task_type, status, provider_used, created_at, completed_at,

            SUBSTRING(result, 1, 120) AS result_preview

     FROM ai_tasks ORDER BY created_at DESC LIMIT 50"

);

if ($tasks_result) {

    while ($row = $tasks_result->fetch_assoc()) $recent_tasks[] = $row;

}



// Schedules

$schedules   = [];

$sched_result = $conn->query("SELECT * FROM ai_schedules ORDER BY is_active DESC, next_run ASC LIMIT 50");

if ($sched_result) {

    while ($row = $sched_result->fetch_assoc()) $schedules[] = $row;

}



// Classes & subjects for action modal selects — primary: Class Management; fallback: students

$modal_classes = [];

$cr = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");

if ($cr) while ($cl = $cr->fetch_assoc()) $modal_classes[] = $cl['class_name'];

$cr2 = $conn->query("SELECT DISTINCT class FROM students WHERE class IS NOT NULL AND class != '' ORDER BY class");

if ($cr2) while ($cl = $cr2->fetch_assoc()) { if (!in_array($cl['class'], $modal_classes)) $modal_classes[] = $cl['class']; }

sort($modal_classes);



$modal_subjects = [];

$sr = $conn->query("SELECT subject_name FROM subjects ORDER BY subject_name");

if ($sr) while ($s = $sr->fetch_assoc()) $modal_subjects[] = $s['subject_name'];



// Schedule POST handlers (unchanged)

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form_action'] ?? '') === 'save_schedule') {

    $task_type   = trim((string) ($_POST['sched_task_type']   ?? ''));

    $description = trim((string) ($_POST['sched_description'] ?? ''));

    $day_of_week = trim((string) ($_POST['sched_day']         ?? 'Daily'));

    $run_time    = trim((string) ($_POST['sched_time']         ?? '08:00'));

    $payload     = trim($_POST['sched_payload']          ?? '{}');

    $sched_id    = (int) ($_POST['sched_id']             ?? 0);

    $next_run    = date('Y-m-d') . ' ' . $run_time . ':00';

    if ($sched_id) {

        $upd = $conn->prepare(

            "UPDATE ai_schedules SET task_type=?,schedule_description=?,day_of_week=?,run_time=?,payload=?,next_run=? WHERE id=?"

        );

        $upd->bind_param('ssssssi', $task_type, $description, $day_of_week, $run_time, $payload, $next_run, $sched_id);

        $upd->execute();

    } else {

        $ins = $conn->prepare(

            "INSERT INTO ai_schedules (task_type,schedule_description,day_of_week,run_time,payload,next_run) VALUES (?,?,?,?,?,?)"

        );

        $ins->bind_param('ssssss', $task_type, $description, $day_of_week, $run_time, $payload, $next_run);

        $ins->execute();

    }

    header('Location: ai_dashboard.php?tab=schedules&msg=saved'); exit;

}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form_action'] ?? '') === 'toggle_schedule') {

    $sid = (int) ($_POST['sched_id'] ?? 0);

    $conn->query("UPDATE ai_schedules SET is_active = 1 - is_active WHERE id = $sid");

    header('Location: ai_dashboard.php?tab=schedules'); exit;

}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form_action'] ?? '') === 'delete_schedule') {

    $sid = (int) ($_POST['sched_id'] ?? 0);

    $conn->query("DELETE FROM ai_schedules WHERE id = $sid");

    header('Location: ai_dashboard.php?tab=schedules'); exit;

}



$active_tab  = $_GET['tab'] ?? 'chat';

$school_name = getSettingValue('school_name') ?: 'EduTrack School';

$acad_year   = getSettingValue('academic_year') ?: date('Y');

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>RBC AI Agent — EduTrack</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<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>

/* ── Hub Header ─────────────────────────────────────────────────────────── */

.rbc-hub-header{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);color:#fff;padding:16px 24px;border-radius:12px;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px}

.rbc-hub-header h4{margin:0;font-size:1.25rem}

.provider-pill{display:inline-flex;align-items:center;gap:5px;background:rgba(255,255,255,.18);border-radius:20px;padding:4px 12px;font-size:.78rem}

.provider-dot{width:8px;height:8px;border-radius:50%;display:inline-block}

.dot-green{background:#2ecc71}.dot-gray{background:#95a5a6}



/* ── Agent Layout ───────────────────────────────────────────────────────── */

.agent-layout{display:flex;gap:0;height:calc(100vh - 220px);min-height:520px;border-radius:12px;overflow:hidden;box-shadow:0 2px 16px rgba(0,0,0,.10)}



/* ── Sidebar (Quick Actions) ────────────────────────────────────────────── */

.agent-sidebar{width:220px;flex-shrink:0;background:#f8f9ff;border-right:1px solid #e5e8f0;overflow-y:auto;padding:16px 12px;display:flex;flex-direction:column;gap:4px}

.agent-sidebar-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;padding-bottom:10px;border-bottom:1px solid #e5e8f0}

.agent-sidebar-header h6{margin:0;font-size:.8rem;font-weight:700;color:#374151}

.provider-badge-sm{font-size:.68rem;display:flex;align-items:center;gap:4px;color:#6b7280}

.provider-badge-sm .dot{width:7px;height:7px;border-radius:50%;background:#2ecc71}

.action-group-label{font-size:.62rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:#9ca3af;margin:10px 0 4px 4px}

.action-btn{width:100%;text-align:left;border:none;background:transparent;border-radius:8px;font-size:.78rem;padding:7px 10px;color:#374151;cursor:pointer;display:flex;align-items:center;gap:7px;transition:all .15s;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}

.action-btn:hover{background:#667eea;color:#fff}

.action-btn i{width:14px;text-align:center;flex-shrink:0}

.action-badge{margin-left:auto;font-size:.6rem;padding:1px 5px;border-radius:6px;background:rgba(255,110,40,.15);color:#d97706;flex-shrink:0}



/* ── Chat Panel ─────────────────────────────────────────────────────────── */

.agent-chat{flex:1;display:flex;flex-direction:column;background:#fff;min-width:0}

.chat-header{padding:14px 18px;border-bottom:1px solid #f0f0f5;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px}

.chat-title{font-size:.95rem;font-weight:700;color:#1f2937;display:flex;align-items:center}

.chat-actions{display:flex;gap:6px}



/* ── Messages ────────────────────────────────────────────────────────────── */

.chat-messages{flex:1;overflow-y:auto;padding:16px 18px;display:flex;flex-direction:column;gap:14px}

.message{display:flex;gap:10px;align-items:flex-start}

.message-user{flex-direction:row-reverse}

.message-avatar{width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.85rem;flex-shrink:0}

.message-ai .message-avatar{background:linear-gradient(135deg,#667eea,#764ba2);color:#fff}

.message-user .message-avatar{background:#3b82f6;color:#fff}

.message-content{display:flex;flex-direction:column;max-width:82%;gap:4px}

.message-user .message-content{align-items:flex-end}

.message-bubble{padding:10px 14px;border-radius:14px;font-size:.85rem;line-height:1.55;word-break:break-word}

.message-ai .message-bubble{background:#f4f5f8;border:1px solid #e8eaf0;border-bottom-left-radius:4px}

.message-user .message-bubble{background:#3b82f6;color:#fff;border-bottom-right-radius:4px}

.bubble-error{background:#fef2f2 !important;border:1px solid #fca5a5 !important;border-left:3px solid #ef4444 !important;color:#991b1b}

.message-meta{font-size:.68rem;color:#9ca3af;padding:0 4px}



/* ── Thinking dots ───────────────────────────────────────────────────────── */

.thinking-dots{display:flex;align-items:center;gap:4px;padding:10px 14px;background:#f4f5f8;border-radius:14px;border-bottom-left-radius:4px;width:fit-content}

.thinking-dots span{width:7px;height:7px;border-radius:50%;background:#9ca3af;animation:tdot 1.2s infinite}

.thinking-dots span:nth-child(2){animation-delay:.2s}

.thinking-dots span:nth-child(3){animation-delay:.4s}

@keyframes tdot{0%,60%,100%{transform:translateY(0);opacity:.5}30%{transform:translateY(-5px);opacity:1}}



/* ── Action cards ────────────────────────────────────────────────────────── */

.action-cards{display:flex;flex-direction:column;gap:6px;margin-top:4px}

.action-card{padding:8px 12px;border-radius:8px;font-size:.8rem;border:1px solid #e5e7eb}

.action-card.running{background:#fffbeb;border-color:#fcd34d}

.action-card.success{background:#f0fdf4;border-color:#86efac}

.action-card.failed{background:#fef2f2;border-color:#fca5a5}

.action-status{display:flex;align-items:center;gap:6px}



/* ── Plan card ───────────────────────────────────────────────────────────── */

.plan-card{background:#f0f4ff;border:1px solid #c7d2fe;border-radius:8px;padding:10px 14px;margin-top:4px;font-size:.8rem}

.plan-title{font-weight:700;color:#4338ca;margin-bottom:6px}

.plan-step{display:flex;align-items:flex-start;gap:8px;margin-bottom:4px;color:#374151}

.step-num{background:#667eea;color:#fff;width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.65rem;font-weight:700;flex-shrink:0;margin-top:1px}



/* ── Suggestion chips ────────────────────────────────────────────────────── */

.suggestion-chips{padding:6px 18px 8px;display:flex;gap:6px;flex-wrap:wrap;border-top:1px solid #f0f0f5}

.suggestion-chips button{font-size:.73rem;padding:4px 11px;border-radius:12px;background:#f3f4f6;border:1px solid #e5e7eb;cursor:pointer;color:#374151;transition:all .15s;white-space:nowrap}

.suggestion-chips button:hover{background:#667eea;color:#fff;border-color:#667eea}



/* ── Input area ──────────────────────────────────────────────────────────── */

.chat-input-area{padding:12px 18px;border-top:1px solid #f0f0f5}

.input-wrapper{display:flex;gap:8px;align-items:flex-end}

.input-wrapper textarea{flex:1;border-radius:12px;padding:9px 14px;border:1px solid #d1d5db;font-size:.85rem;outline:none;resize:none;line-height:1.4;max-height:150px;overflow-y:auto;font-family:inherit}

.input-wrapper textarea:focus{border-color:#667eea;box-shadow:0 0 0 3px rgba(102,126,234,.15)}

.input-wrapper textarea.highlight{border-color:#f59e0b;box-shadow:0 0 0 3px rgba(245,158,11,.2)}

.send-btn{width:38px;height:38px;border-radius:50%;border:none;background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:transform .15s}

.send-btn:hover:not(:disabled){transform:scale(1.08)}

.send-btn:disabled{opacity:.5;cursor:not-allowed}

.input-footer{display:flex;justify-content:space-between;margin-top:5px;font-size:.7rem;color:#9ca3af}



/* ── Task History ────────────────────────────────────────────────────────── */

.status-pill{padding:2px 8px;border-radius:10px;font-size:.72rem;font-weight:600}

.sp-completed{background:#d1fae5;color:#065f46}.sp-running{background:#dbeafe;color:#1e40af}

.sp-failed{background:#fee2e2;color:#991b1b}.sp-pending{background:#fef9c3;color:#854d0e}

.badge-claude{background:#7c5cbe;color:#fff}.badge-groq{background:#ff6b35;color:#fff}

.badge-gemini{background:#1a73e8;color:#fff}.badge-openai{background:#00a67e;color:#fff}

.provider-badge{display:inline-block;font-size:.68rem;padding:1px 7px;border-radius:10px}



@media(max-width:768px){

  .agent-sidebar{display:none}

  .agent-layout{height:calc(100vh - 180px)}

}

</style>

</head>

<body>

<div class="wrapper">

    <nav id="sidebar" class="sidebar">

        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>

    </nav>



    <div class="main-content">

        <header class="header">

            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>

            <div class="header-right">

                <div class="dropdown">

                    <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">

                        <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>

                    </button>

                    <ul class="dropdown-menu dropdown-menu-end">

                        <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>

                        <li><hr class="dropdown-divider"></li>

                        <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>

                    </ul>

                </div>

            </div>

        </header>



        <main class="content">



            <?php if (!$any_provider_configured): ?>

            <div class="alert alert-warning d-flex align-items-center gap-3 mb-3" role="alert">

                <i class="fas fa-exclamation-triangle fa-lg"></i>

                <div>

                    <strong>No AI providers configured.</strong>

                    The AI agent requires at least one API key to function.

                    <a href="settings.php#ai-config" class="alert-link ms-1">Configure API keys in Settings</a>.

                </div>

            </div>

            <?php endif; ?>



                        <?php if (defined('AI_DEBUG') && AI_DEBUG): ?>

            <?php $rbc_health = RBCAIEngine::healthCheck(); ?>

            <div class="alert alert-secondary mb-3" role="alert">

                <div class="d-flex align-items-center gap-2 mb-2">

                    <i class="fas fa-stethoscope"></i>

                    <strong>Provider health</strong>

                    <span class="badge bg-danger">AI_DEBUG is ON &mdash; turn it off before going live</span>

                </div>

                <table class="table table-sm mb-0 small">

                    <thead><tr><th>Provider</th><th>Status</th><th class="text-end">Latency</th><th>Detail</th></tr></thead>

                    <tbody>

                    <?php foreach ($rbc_health as $prov => $h): ?>

                        <tr>

                            <td><?php echo htmlspecialchars(ucfirst($prov)); ?></td>

                            <td>

                                <?php if ($h['ok']): ?>

                                    <span class="text-success"><i class="fas fa-check-circle me-1"></i>OK</span>

                                <?php elseif (!$h['configured']): ?>

                                    <span class="text-muted"><i class="fas fa-minus-circle me-1"></i>No key</span>

                                <?php else: ?>

                                    <span class="text-danger"><i class="fas fa-times-circle me-1"></i>Failing</span>

                                <?php endif; ?>

                                <?php if ($h['cooling_down']): ?>

                                    <span class="badge bg-warning text-dark ms-1">cooling down</span>

                                <?php endif; ?>

                            </td>

                            <td class="text-end"><?php echo $h['ms'] ? (int) $h['ms'] . ' ms' : '&mdash;'; ?></td>

                            <td class="text-muted"><?php echo htmlspecialchars((string) substr((string) ($h['error'] ?? ''), 0, 160)); ?></td>

                        </tr>

                    <?php endforeach; ?>

                    </tbody>

                </table>

            </div>

            <?php endif; ?>



            <!-- Hub Header -->

            <div class="rbc-hub-header">

                <div>

                    <h4><i class="fas fa-brain me-2"></i>RBC AI Agent</h4>

                    <small>Context-aware · Conversation memory · Live school data</small>

                </div>

                <div class="d-flex gap-2 flex-wrap">

                    <?php foreach ($provider_status as $p => $ok): ?>

                    <div class="provider-pill">

                        <span class="provider-dot <?php echo $ok ? 'dot-green' : 'dot-gray'; ?>"></span>

                        <?php echo ucfirst($p); ?>

                    </div>

                    <?php endforeach; ?>

                </div>

            </div>



            <!-- Tabs -->

            <ul class="nav nav-tabs mb-3" id="hubTabs">

                <li class="nav-item"><a class="nav-link <?php echo $active_tab==='chat'?'active':''; ?>" href="?tab=chat"><i class="fas fa-comments me-1"></i>AI Chat</a></li>

                <li class="nav-item"><a class="nav-link <?php echo $active_tab==='tasks'?'active':''; ?>" href="?tab=tasks"><i class="fas fa-tasks me-1"></i>Task History</a></li>

                <li class="nav-item"><a class="nav-link <?php echo $active_tab==='schedules'?'active':''; ?>" href="?tab=schedules"><i class="fas fa-clock me-1"></i>Schedules</a></li>

            </ul>



            <!-- ══ CHAT TAB ══════════════════════════════════════════════════════ -->

            <div id="tab-chat" <?php echo $active_tab!=='chat' ? 'style="display:none"' : ''; ?>>



                <div class="agent-layout">



                    <!-- Quick Actions Sidebar -->

                    <div class="agent-sidebar">

                        <div class="agent-sidebar-header">

                            <h6>Quick Actions</h6>

                            <span class="provider-badge-sm" id="providerBadge">

                                <span class="dot"></span> Ready

                            </span>

                        </div>



                        <div class="action-group-label">Fees &amp; Finance</div>

                        <button class="action-btn" onclick="quickAction('Send fee reminders to all classes')">

                            <i class="fas fa-bell"></i>Fee Reminders<span class="action-badge">SMS</span>

                        </button>

                        <button class="action-btn" onclick="openActionModal('fee_reminders')">

                            <i class="fas fa-sliders-h"></i>Fee Reminders (Custom)

                        </button>

                        <button class="action-btn" onclick="quickAction('Give me a financial summary for this month')">

                            <i class="fas fa-chart-line"></i>Financial Summary

                        </button>

                        <button class="action-btn" onclick="openActionModal('feeding_summary')">

                            <i class="fas fa-utensils"></i>Feeding Summary

                        </button>



                        <div class="action-group-label">Academic</div>

                        <button class="action-btn" onclick="openActionModal('terminal_reports')">

                            <i class="fas fa-file-alt"></i>Terminal Reports

                        </button>

                        <button class="action-btn" onclick="openActionModal('exam_paper')">

                            <i class="fas fa-pencil-alt"></i>Generate Exam

                        </button>

                        <button class="action-btn" onclick="quickAction('Detect at-risk students across all classes this term')">

                            <i class="fas fa-exclamation-triangle"></i>At-Risk Students

                        </button>

                        <button class="action-btn" onclick="openActionModal('report_pdfs')">

                            <i class="fas fa-file-pdf"></i>Batch Report PDFs

                        </button>



                        <div class="action-group-label">Operations</div>

                        <button class="action-btn" onclick="quickAction('Check for timetable conflicts this term')">

                            <i class="fas fa-calendar-alt"></i>Timetable Check

                        </button>

                        <button class="action-btn" onclick="openActionModal('notify_parents')">

                            <i class="fas fa-users"></i>Notify Parents

                        </button>

                        <button class="action-btn" onclick="quickAction('Create parent portal accounts for students who do not have one yet')">

                            <i class="fas fa-user-plus"></i>Parent Accounts

                        </button>

                    </div>



                    <!-- Chat Panel -->

                    <div class="agent-chat">

                        <div class="chat-header">

                            <div class="chat-title">

                                <i class="fas fa-brain me-2 text-primary"></i>RBC AI Agent

                                <span class="badge bg-success ms-2 fs-75" id="statusBadge">Online</span>

                            </div>

                            <div class="chat-actions">

                                <button class="btn btn-sm btn-outline-secondary" onclick="clearChat()">

                                    <i class="fas fa-trash me-1"></i>Clear

                                </button>

                                <button class="btn btn-sm btn-outline-secondary" onclick="exportChat()">

                                    <i class="fas fa-download me-1"></i>Export

                                </button>

                            </div>

                        </div>



                        <div class="chat-messages" id="chatMessages">

                            <div class="message message-ai" id="welcomeMsg">

                                <div class="message-avatar"><i class="fas fa-brain"></i></div>

                                <div class="message-content">

                                    <div class="message-bubble">

                                        Hello! I'm <strong>RBC AI</strong>, your assistant for <strong><?php echo htmlspecialchars($school_name); ?></strong>.<br>

                                        I know your school's live data and can take real actions on your behalf.<br><br>

                                        Try: <em>"Send fee reminders to JHS 2"</em>, <em>"How many students owe fees?"</em>, or <em>"Generate a Maths exam for Class 5"</em>

                                    </div>

                                    <div class="message-meta">RBC AI</div>

                                </div>

                            </div>

                        </div>



                        <div class="suggestion-chips" id="suggestionChips">

                            <button onclick="quickAction('How many students have outstanding fees?')">Outstanding fees summary</button>

                            <button onclick="quickAction('Which students are at risk this term?')">At-risk students</button>

                            <button onclick="quickAction('What happened in school this month?')">Monthly overview</button>

                        </div>



                        <div class="chat-input-area">

                            <div class="input-wrapper">

                                <textarea id="userInput" rows="1"

                                    placeholder="Type a command or question…"

                                    onkeydown="handleKeyDown(event)"

                                    oninput="autoResize(this)"></textarea>

                                <button id="sendBtn" onclick="sendMessage()" class="send-btn">

                                    <i class="fas fa-paper-plane"></i>

                                </button>

                            </div>

                            <div class="input-footer">

                                <span id="providerLabel">Cascade: Claude → Groq → Gemini → OpenAI</span>

                                <span>Thread: <span id="threadId"></span></span>

                            </div>

                        </div>

                    </div>

                </div>



            </div><!-- /tab-chat -->



            <!-- ══ TASK HISTORY TAB ══════════════════════════════════════════════ -->

            <div id="tab-tasks" <?php echo $active_tab!=='tasks' ? 'style="display:none"' : ''; ?>>

                <div class="card">

                    <div class="card-header"><h5 class="mb-0"><i class="fas fa-history me-2"></i>Recent AI Tasks</h5></div>

                    <div class="card-body">

                        <table class="table table-hover table-sm" id="tasksTable">

                            <thead><tr><th>Time</th><th>Task</th><th>Status</th><th>Provider</th><th>Result Preview</th></tr></thead>

                            <tbody>

                            <?php foreach ($recent_tasks as $t): ?>

                            <tr>

                                <td><small><?php echo date('d M H:i', strtotime($t['created_at'])); ?></small></td>

                                <td><code><?php echo htmlspecialchars(str_replace('_', ' ', $t['task_type'])); ?></code></td>

                                <td><span class="status-pill sp-<?php echo htmlspecialchars($t['status']); ?>"><?php echo ucfirst($t['status']); ?></span></td>

                                <td><?php echo $t['provider_used'] ? '<span class="badge-' . htmlspecialchars($t['provider_used']) . ' provider-badge">' . ucfirst($t['provider_used']) . '</span>' : '-'; ?></td>

                                <td><small class="text-muted"><?php echo htmlspecialchars(substr(strip_tags($t['result_preview'] ?? ''), 0, 80)); ?></small></td>

                            </tr>

                            <?php endforeach; ?>

                            <?php if (empty($recent_tasks)): ?>

                            <tr><td colspan="5" class="text-center text-muted py-4">No tasks yet. Start a conversation!</td></tr>

                            <?php endif; ?>

                            </tbody>

                        </table>

                    </div>

                </div>

            </div>



            <!-- ══ SCHEDULES TAB ════════════════════════════════════════════════ -->

            <div id="tab-schedules" <?php echo $active_tab!=='schedules' ? 'style="display:none"' : ''; ?>>

                <div class="d-flex justify-content-between align-items-center mb-3">

                    <h5 class="mb-0"><i class="fas fa-clock me-2"></i>Scheduled AI Tasks</h5>

                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalAddSchedule">

                        <i class="fas fa-plus me-1"></i>Add Schedule

                    </button>

                </div>

                <div class="card">

                    <div class="card-body">

                        <table class="table table-hover table-sm" id="schedulesTable">

                            <thead><tr><th>Task</th><th>Description</th><th>Schedule</th><th>Last Run</th><th>Next Run</th><th>Status</th><th>Actions</th></tr></thead>

                            <tbody>

                            <?php foreach ($schedules as $s): ?>

                            <tr>

                                <td><code><?php echo htmlspecialchars(str_replace('_', ' ', $s['task_type'])); ?></code></td>

                                <td><?php echo htmlspecialchars($s['schedule_description']); ?></td>

                                <td><?php echo htmlspecialchars($s['day_of_week']); ?> @ <?php echo htmlspecialchars($s['run_time'] ?? ''); ?></td>

                                <td><?php echo $s['last_run'] ? date('d M H:i', strtotime($s['last_run'])) : '-'; ?></td>

                                <td><?php echo $s['next_run'] ? date('d M H:i', strtotime($s['next_run'])) : '-'; ?></td>

                                <td>

                                    <form method="POST" style="display:inline">

                                        <input type="hidden" name="form_action" value="toggle_schedule">

                                        <input type="hidden" name="sched_id" value="<?php echo (int)$s['id']; ?>">

                                        <button type="submit" class="btn btn-sm <?php echo $s['is_active'] ? 'btn-success' : 'btn-secondary'; ?>">

                                            <?php echo $s['is_active'] ? 'Active' : 'Inactive'; ?>

                                        </button>

                                    </form>

                                </td>

                                <td>

                                    <button class="btn btn-sm btn-outline-primary edit-sched-btn"

                                            data-id="<?php echo $s['id']; ?>"

                                            data-task="<?php echo htmlspecialchars($s['task_type']); ?>"

                                            data-desc="<?php echo htmlspecialchars($s['schedule_description']); ?>"

                                            data-day="<?php echo htmlspecialchars($s['day_of_week']); ?>"

                                            data-time="<?php echo htmlspecialchars($s['run_time'] ?? '08:00'); ?>"

                                            data-payload="<?php echo htmlspecialchars($s['payload'] ?? '{}'); ?>"

                                            data-bs-toggle="modal" data-bs-target="#modalAddSchedule">

                                        <i class="fas fa-edit"></i>

                                    </button>

                                    <form method="POST" style="display:inline" onsubmit="return confirm('Delete this schedule?')">

                                        <input type="hidden" name="form_action" value="delete_schedule">

                                        <input type="hidden" name="sched_id" value="<?php echo (int)$s['id']; ?>">

                                        <button type="submit" class="btn btn-sm btn-outline-danger"><i class="fas fa-trash"></i></button>

                                    </form>

                                </td>

                            </tr>

                            <?php endforeach; ?>

                            <?php if (empty($schedules)): ?>

                            <tr><td colspan="7" class="text-center text-muted py-4">No schedules yet.</td></tr>

                            <?php endif; ?>

                            </tbody>

                        </table>

                    </div>

                </div>

            </div>



        </main>

        <footer class="footer"><p>&copy; <?php echo date('Y'); ?> EduTrack PRO. All rights reserved.</p></footer>

    </div><!-- /main-content -->

</div><!-- /wrapper -->



<!-- ══════════════════ ACTION MODAL ══════════════════════════════════════════ -->

<div class="modal fade" id="actionModal" tabindex="-1">

    <div class="modal-dialog">

        <div class="modal-content">

            <div class="modal-header">

                <h5 class="modal-title" id="actionModalTitle">Configure Action</h5>

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

            </div>

            <div class="modal-body" id="actionModalBody"></div>

            <div class="modal-footer">

                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

                <button class="btn btn-primary" onclick="submitActionModal()">

                    <i class="fas fa-paper-plane me-1"></i>Run Action

                </button>

            </div>

        </div>

    </div>

</div>



<!-- ══════════════════ SCHEDULE MODAL ════════════════════════════════════════ -->

<div class="modal fade" id="modalAddSchedule" tabindex="-1">

    <div class="modal-dialog"><div class="modal-content">

        <div class="modal-header"><h5 class="modal-title" id="schedModalTitle"><i class="fas fa-clock me-2"></i>Add Schedule</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>

        <form method="POST" action="ai_dashboard.php?tab=schedules">

            <input type="hidden" name="form_action" value="save_schedule">

            <input type="hidden" name="sched_id" id="sched_id_field" value="0">

            <div class="modal-body">

                <div class="mb-3"><label class="form-label">Task Type *</label>

                    <select class="form-select" name="sched_task_type" id="sched_task_type">

                        <option value="send_fee_reminders">Send Fee Reminders</option>

                        <option value="generate_terminal_reports">Generate Terminal Reports</option>

                        <option value="detect_at_risk_students">Detect At-Risk Students</option>

                        <option value="financial_snapshot">Financial Snapshot</option>

                        <option value="send_weekly_feeding_summary">Weekly Feeding Summary</option>

                        <option value="check_timetable_conflicts">Check Timetable Conflicts</option>

                        <option value="bulk_notify_parents">Bulk Notify Parents</option>

                        <option value="create_parent_accounts_bulk">Create Parent Accounts</option>

                    </select></div>

                <div class="mb-3"><label class="form-label">Description</label>

                    <input type="text" class="form-control" name="sched_description" id="sched_description"></div>

                <div class="row">

                    <div class="col"><label class="form-label">Day</label>

                        <select class="form-select" name="sched_day" id="sched_day">

                            <option>Daily</option><option>Monday</option><option>Tuesday</option>

                            <option>Wednesday</option><option>Thursday</option><option>Friday</option>

                        </select></div>

                    <div class="col"><label class="form-label">Time</label>

                        <input type="time" class="form-control" name="sched_time" id="sched_time" value="08:00"></div>

                </div>

                <div class="mb-3 mt-3"><label class="form-label">Parameters (JSON)</label>

                    <textarea class="form-control font-monospace" name="sched_payload" id="sched_payload" rows="3">{}</textarea></div>

            </div>

            <div class="modal-footer">

                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>

                <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save</button>

            </div>

        </form>

    </div></div>

</div>



<!-- Scripts -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script src="https://code.jquery.com/jquery-3.7.0.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 src="js/main.js"></script>

<script>

// ════════════════════════════════════════════════════════════════════════════

// RBC AI Agent — Chat Engine

// ════════════════════════════════════════════════════════════════════════════



const AGENT_URL = 'ajax/ai_agent_stream.php';

const ACTION_URL = 'ajax/ai_action.php';

const RBC_CSRF   = <?php echo json_encode($rbc_csrf); ?>;



// Thread persistence across page reloads

let threadId = localStorage.getItem('rbc_thread_id') || generateThreadId();

let isProcessing = false;

localStorage.setItem('rbc_thread_id', threadId);

document.getElementById('threadId').textContent = threadId.substring(0, 8) + '…';



function generateThreadId() {

    return 'thread_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);

}



// ── Sending ──────────────────────────────────────────────────────────────────

function sendMessage() {

    const input = document.getElementById('userInput');

    const text  = input.value.trim();

    if (!text || isProcessing) return;

    appendUserMessage(text);

    input.value = '';

    autoResize(input);

    clearSuggestions();

    processMessage(text);

}



function quickAction(text) {

    if (isProcessing) return;

    document.getElementById('userInput').value = text;

    sendMessage();

}



function handleKeyDown(e) {

    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }

}



// ── Streaming via fetch + ReadableStream ─────────────────────────────────────

function processMessage(text) {

    isProcessing = true;

    setProcessing(true);

    const aiMsgId = appendAiMessage();

    showThinking(aiMsgId);



    fetch(AGENT_URL, {

        method:  'POST',

        headers: { 'Content-Type': 'application/json' },

        body:    JSON.stringify({ message: text, thread_id: threadId, csrf_token: RBC_CSRF })

    }).then(response => {

        if (!response.ok) throw new Error('HTTP ' + response.status);

        const reader  = response.body.getReader();

        const decoder = new TextDecoder();

        let buffer    = '';



        function read() {

            reader.read().then(({ done, value }) => {

                if (done) { hideThinking(aiMsgId); isProcessing = false; setProcessing(false); return; }

                buffer += decoder.decode(value, { stream: true });

                const lines = buffer.split('\n');

                buffer = lines.pop(); // keep incomplete line



                let i = 0;

                while (i < lines.length) {

                    const line = lines[i];

                    if (line.startsWith('event: ')) {

                        const event    = line.substring(7).trim();

                        const dataLine = lines[i + 1] || '';

                        if (dataLine.startsWith('data: ')) {

                            try {

                                const data = JSON.parse(dataLine.substring(6));

                                handleSSEEvent(event, data, aiMsgId);

                            } catch (_) {}

                            i += 2;

                            continue;

                        }

                    }

                    i++;

                }

                read();

            }).catch(err => {

                hideThinking(aiMsgId);

                updateAiMessage(aiMsgId, '⚠ Stream read error: ' + err.message, 'error');

                isProcessing = false; setProcessing(false);

            });

        }

        read();

    }).catch(err => {

        hideThinking(aiMsgId);

        updateAiMessage(aiMsgId, '⚠ Connection error. Please try again.', 'error');

        isProcessing = false; setProcessing(false);

    });

}



// ── SSE Event Router ─────────────────────────────────────────────────────────

function handleSSEEvent(event, data, msgId) {

    switch (event) {

        case 'thinking':

            updateThinkingTitle(msgId, data.message);

            break;

        case 'message':

            hideThinking(msgId);

            updateAiMessage(msgId, data.content);

            updateProviderLabel(data.provider);

            break;

        case 'clarification':

            hideThinking(msgId);

            updateAiMessage(msgId, data.message);

            highlightInput();

            break;

        case 'plan':

            appendPlanCard(msgId, data.steps);

            break;

        case 'action_start':

            appendActionProgress(msgId, data.type, data.description);

            break;

        case 'action_result':

            updateActionProgress(msgId, data.type, data.success, data.summary, data.result);

            break;

        case 'data':

            appendDataCard(msgId, data.content);

            break;

        case 'confirm_required':

            appendConfirmCard(msgId, data);

            break;

        case 'suggestions':

            showSuggestions(data.suggestions);

            break;

        case 'error':

            hideThinking(msgId);

            updateAiMessage(msgId, '⚠ ' + data.message, 'error');

            isProcessing = false; setProcessing(false);

            break;

        case 'done':

            hideThinking(msgId);

            isProcessing = false; setProcessing(false);

            break;

    }

}



// ── DOM Builders ─────────────────────────────────────────────────────────────

function appendUserMessage(text) {

    addToChat(`

      <div class="message message-user">

        <div class="message-content">

          <div class="message-bubble">${escHtml(text)}</div>

          <div class="message-meta">You</div>

        </div>

        <div class="message-avatar"><i class="fas fa-user"></i></div>

      </div>`);

    scrollToBottom();

}



function appendAiMessage() {

    const id = 'msg_' + Date.now();

    addToChat(`

      <div class="message message-ai" id="${id}">

        <div class="message-avatar"><i class="fas fa-brain"></i></div>

        <div class="message-content">

          <div class="thinking-dots" id="think_${id}">

            <span></span><span></span><span></span>

          </div>

          <div class="message-bubble" id="bubble_${id}" style="display:none"></div>

          <div class="action-cards" id="actions_${id}"></div>

          <div class="message-meta" id="meta_${id}">RBC AI</div>

        </div>

      </div>`);

    scrollToBottom();

    return id;

}



function showThinking(id) {

    const el = document.getElementById('think_' + id);

    if (el) el.style.display = 'flex';

}

function hideThinking(id) {

    const el = document.getElementById('think_' + id);

    if (el) el.style.display = 'none';

}

function updateThinkingTitle(id, text) {

    const el = document.getElementById('think_' + id);

    if (el) el.title = text;

}



function updateAiMessage(id, text, type = '') {

    const bubble = document.getElementById('bubble_' + id);

    if (!bubble) return;

    bubble.innerHTML  = String(text).replace(/\n/g, '<br>');

    bubble.style.display = 'block';

    bubble.className  = 'message-bubble' + (type === 'error' ? ' bubble-error' : '');

    scrollToBottom();

}



function appendPlanCard(msgId, steps) {

    const cards = document.getElementById('actions_' + msgId);

    if (!cards) return;

    const stepsHtml = steps.map((s, i) =>

        `<div class="plan-step"><span class="step-num">${i+1}</span><span>${escHtml(String(s))}</span></div>`

    ).join('');

    cards.insertAdjacentHTML('beforeend',

        `<div class="plan-card"><div class="plan-title"><i class="fas fa-tasks me-1"></i>Action Plan</div>${stepsHtml}</div>`

    );

    scrollToBottom();

}



function appendActionProgress(msgId, type, desc) {

    const cards    = document.getElementById('actions_' + msgId);

    if (!cards) return;

    const safeType = String(type).replace(/[^a-z_]/g, '');

    cards.insertAdjacentHTML('beforeend',

        `<div class="action-card running" id="act_${msgId}_${safeType}">

           <div class="action-status">

             <div class="spinner-border spinner-border-sm me-2" style="width:14px;height:14px"></div>

             <span>${escHtml(String(desc))}</span>

           </div>

         </div>`

    );

    scrollToBottom();

}



function updateActionProgress(msgId, type, success, summary, result) {

    const safeType = String(type).replace(/[^a-z_]/g, '');

    const card     = document.getElementById('act_' + msgId + '_' + safeType);

    if (!card) return;

    card.className = 'action-card ' + (success ? 'success' : 'failed');

    const icon     = success ? 'fa-check-circle text-success' : 'fa-times-circle text-danger';



    // Summaries can be multi-paragraph (financial brief, canteen report).

    const summaryHtml = escHtml(String(summary === null || summary === undefined ? '' : summary))

                          .replace(/\n/g, '<br>');



    card.innerHTML =

        `<div class="action-status"><i class="fas ${icon} me-2"></i><span>${summaryHtml}</span></div>`

        + renderActionDetail(type, success, result || {});

    scrollToBottom();

}



// ── Structured result renderers ──────────────────────────────────────────────

// Each action returns data the old UI discarded. Render what is worth seeing.

function renderActionDetail(type, success, r) {

    if (!success) {

        // Surface per-item failures so a partial run is diagnosable.

        if (Array.isArray(r.failures) && r.failures.length) {

            return detailBox('Failures', r.failures.map(f =>

                `${escHtml(String(f.student || f.student_id || '?'))}: ${escHtml(String(f.error || ''))}`

            ).join('<br>'));

        }

        return '';

    }



    switch (type) {

        case 'batch_generate_report_pdfs':

            return renderReportPdfs(r);

        case 'financial_snapshot':

            return renderFinancial(r);

        case 'detect_at_risk_students':

            return renderAtRisk(r);

        case 'check_timetable_conflicts':

            return renderConflicts(r);

        case 'canteen_daily_report':

            return renderCanteenReport(r);

        case 'generate_exam_paper':

            return r.paper_id

                ? actionLink('exams_generator/index.php?paper_id=' + encodeURIComponent(r.paper_id),

                             'fa-file-lines', 'Open exam paper', 'btn-primary')

                : '';

        default:

            return '';

    }

}



function detailBox(title, innerHtml) {

    return `<div class="mt-2 p-2 rounded" style="background:rgba(0,0,0,.04);font-size:.8rem">

              <div class="fw-semibold mb-1">${escHtml(title)}</div>${innerHtml}</div>`;

}



function actionLink(href, iconClass, label, btnClass) {

    return `<a href="${escHtml(href)}" target="_blank" class="btn btn-sm ${btnClass || 'btn-success'} mt-2">

              <i class="fas ${iconClass} me-1"></i>${escHtml(label)}</a>`;

}



function miniTable(headers, rows) {

    if (!rows.length) return '';

    const th = headers.map(h => `<th>${escHtml(String(h))}</th>`).join('');

    const tr = rows.map(cols =>

        '<tr>' + cols.map(c => `<td>${escHtml(String(c === null || c === undefined ? '' : c))}</td>`).join('') + '</tr>'

    ).join('');

    return `<div class="table-responsive"><table class="table table-sm mb-0" style="font-size:.78rem">

              <thead><tr>${th}</tr></thead><tbody>${tr}</tbody></table></div>`;

}



function ghs(v) {

    const n = Number(v || 0);

    return 'GHS ' + n.toLocaleString('en-GH', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

}



// Only offer the download when files were actually produced — the old code

// rendered the button off download_url alone, which 404'd on every empty run.

function renderReportPdfs(r) {

    if (!r.download_url || !(Number(r.pdf_count) > 0)) return '';

    const kb = r.zip_bytes ? ' (' + Math.round(Number(r.zip_bytes) / 1024) + ' KB)' : '';

    return actionLink(r.download_url, 'fa-download', 'Download ZIP' + kb, 'btn-success');

}



function renderFinancial(r) {

    const d = r.data || {};

    let html = miniTable(['Metric', 'Amount'], [

        ['Collections',   ghs(d.collections)],

        ['  of which online', ghs(d.online_payments)],

        ['  of which cash',   ghs(d.cash_payments)],

        ['Expenses',      ghs(d.expenses)],

        ['Net balance',   ghs(d.net_balance)],

    ]);

    if (Array.isArray(d.by_class) && d.by_class.length) {

        html += '<div class="fw-semibold mt-2 mb-1">Collections by class</div>'

              + miniTable(['Class', 'Collected'],

                  d.by_class.map(c => [c.class, ghs(c.collected)]));

    }

    if (Array.isArray(d.top_categories) && d.top_categories.length) {

        html += '<div class="fw-semibold mt-2 mb-1">Top expense categories</div>'

              + miniTable(['Category', 'Total'],

                  d.top_categories.map(c => [c.category, ghs(c.total)]));

    }

    const period = d.period ? `${d.period.from} to ${d.period.to}` : 'this period';

    return detailBox('Financial detail — ' + period, html);

}



function renderAtRisk(r) {

    const list = Array.isArray(r.at_risk_students) ? r.at_risk_students : [];

    if (!list.length) return '';

    const rows = list.slice(0, 25).map(s => [

        s.student_name || s.student_id || '?',

        s.class || '',

        (s.risk_level || '').toUpperCase(),

        s.avg_score === null || s.avg_score === undefined ? '—' : s.avg_score,

        s.fee_balance ? ghs(s.fee_balance) : '—',

        s.recommended_action || (Array.isArray(s.risk_factors) ? s.risk_factors.join(', ') : ''),

    ]);

    const more = list.length > 25 ? `<div class="text-muted mt-1">+ ${list.length - 25} more</div>` : '';

    return detailBox('At-risk students',

        miniTable(['Student', 'Class', 'Risk', 'Avg', 'Balance', 'Action'], rows) + more);

}



function renderConflicts(r) {

    const conflicts   = Array.isArray(r.conflicts) ? r.conflicts : [];

    const suggestions = Array.isArray(r.ai_suggestions) ? r.ai_suggestions : [];

    if (!conflicts.length && !suggestions.length) return '';

    let html = '';

    if (conflicts.length) {

        html += miniTable(['Day', 'Period', 'Conflict'],

            conflicts.slice(0, 25).map(c => [c.day || '', c.period || '', c.description || c.conflict_type || '']));

    }

    if (suggestions.length) {

        html += '<div class="fw-semibold mt-2 mb-1">Suggested fixes</div>'

              + suggestions.slice(0, 25).map(s =>

                  `<div class="mb-1">&bull; ${escHtml(String(s.suggested_fix || s.description || s))}</div>`

                ).join('');

    }

    return detailBox('Timetable detail', html);

}



function renderCanteenReport(r) {

    const sessions = Array.isArray(r.sessions) ? r.sessions : [];

    if (!sessions.length) return '';

    return detailBox('Sessions on ' + (r.date || 'today'),

        miniTable(['Session', 'Enrolled', 'Confirmed', 'Absent', 'Pending', 'Revenue'],

            sessions.map(s => [

                s.session_name, s.total_enrolled, s.confirmed, s.absent, s.pending, ghs(s.revenue),

            ])));

}



function appendDataCard(msgId, content) {

    const cards = document.getElementById('actions_' + msgId);

    if (!cards) return;

    cards.insertAdjacentHTML('beforeend',

        `<div class="action-card success" style="font-size:.8rem;white-space:pre-wrap">${escHtml(String(content))}</div>`

    );

    scrollToBottom();

}



function showSuggestions(suggestions) {

    const chips = document.getElementById('suggestionChips');

    chips.innerHTML = suggestions.map(s =>

        `<button onclick="quickAction(${JSON.stringify(String(s))})">${escHtml(String(s))}</button>`

    ).join('');

    chips.style.display = 'flex';

}



function clearSuggestions() {

    const chips = document.getElementById('suggestionChips');

    chips.innerHTML = '';

    chips.style.display = 'none';

}



function setProcessing(on) {

    const btn   = document.getElementById('sendBtn');

    const input = document.getElementById('userInput');

    btn.disabled   = on;

    input.disabled = on;

    btn.innerHTML  = on

        ? '<div class="spinner-border spinner-border-sm" style="width:16px;height:16px"></div>'

        : '<i class="fas fa-paper-plane"></i>';

}



function updateProviderLabel(provider) {

    if (!provider) return;

    const el = document.getElementById('providerLabel');

    if (el) el.textContent = 'Responded by: ' + provider;

    const badge = document.getElementById('providerBadge');

    if (!badge) return;

    const colors = { claude:'#7C3AED', groq:'#F97316', gemini:'#2563EB', openai:'#10B981' };

    const col = colors[provider] || '#6B7280';

    badge.style.color = col;

    const dot = badge.querySelector('.dot');

    if (dot) dot.style.background = col;

    badge.textContent = provider.charAt(0).toUpperCase() + provider.slice(1);

}



function clearChat() {

    if (!confirm('Clear this conversation and start a new thread?')) return;

    threadId = generateThreadId();

    localStorage.setItem('rbc_thread_id', threadId);

    document.getElementById('threadId').textContent = threadId.substring(0, 8) + '…';

    document.getElementById('chatMessages').innerHTML = '';

    document.getElementById('providerLabel').textContent = 'Cascade: Claude → Groq → Gemini → OpenAI';

    document.getElementById('providerBadge').textContent = 'Ready';

    document.getElementById('providerBadge').querySelector && (document.getElementById('providerBadge').innerHTML = '<span class="dot"></span> Ready');

    const chips = document.getElementById('suggestionChips');

    chips.innerHTML = `

        <button onclick="quickAction('How many students have outstanding fees?')">Outstanding fees summary</button>

        <button onclick="quickAction('Which students are at risk this term?')">At-risk students</button>

        <button onclick="quickAction('What happened in school this month?')">Monthly overview</button>`;

    chips.style.display = 'flex';

}



function exportChat() {

    const msgs = document.getElementById('chatMessages');

    const lines = [];

    msgs.querySelectorAll('.message').forEach(msg => {

        const isUser = msg.classList.contains('message-user');

        const bubble = msg.querySelector('.message-bubble');

        if (bubble) lines.push((isUser ? 'You' : 'RBC AI') + ': ' + bubble.innerText);

    });

    const blob = new Blob([lines.join('\n\n')], { type: 'text/plain' });

    const a = document.createElement('a'); a.href = URL.createObjectURL(blob);

    a.download = 'rbc-ai-chat-' + Date.now() + '.txt'; a.click();

}



function addToChat(html) {

    document.getElementById('chatMessages').insertAdjacentHTML('beforeend', html);

}

function scrollToBottom() {

    const el = document.getElementById('chatMessages');

    if (el) el.scrollTop = el.scrollHeight;

}

function autoResize(el) {

    el.style.height = 'auto';

    el.style.height = Math.min(el.scrollHeight, 150) + 'px';

}

function highlightInput() {

    const input = document.getElementById('userInput');

    input.classList.add('highlight');

    setTimeout(() => input.classList.remove('highlight'), 1200);

    input.focus();

}

function escHtml(str) {

    const d = document.createElement('div');

    d.appendChild(document.createTextNode(str));

    return d.innerHTML;

}



// ── Action Modals ────────────────────────────────────────────────────────────

<?php

// Build class options HTML once in PHP

$classOptionsHtml = '<option value="">All Classes</option>';

foreach ($modal_classes as $cls) {

    $classOptionsHtml .= '<option value="' . htmlspecialchars($cls) . '">' . htmlspecialchars($cls) . '</option>';

}

$classOptionsHtmlRequired = '<option value="">Select class…</option>';

foreach ($modal_classes as $cls) {

    $classOptionsHtmlRequired .= '<option value="' . htmlspecialchars($cls) . '">' . htmlspecialchars($cls) . '</option>';

}

$subjectOptionsHtml = '';

foreach ($modal_subjects as $sub) {

    $subjectOptionsHtml .= '<option value="' . htmlspecialchars($sub) . '">' . htmlspecialchars($sub) . '</option>';

}

$termOptions = '<option>First Term</option><option>Second Term</option><option>Third Term</option>';

?>



const modalForms = {

  fee_reminders: {

    title: 'Send Fee Reminders',

    html: `

      <div class="mb-3">

        <label class="form-label">Class (leave blank for all)</label>

        <select class="form-select" id="am_class"><?php echo $classOptionsHtml; ?></select>

      </div>

      <div class="mb-3">

        <label class="form-label">Minimum balance to notify (GHS)</label>

        <input type="number" class="form-control" id="am_balance" value="0" min="0">

      </div>`,

    action: 'send_fee_reminders',

    getParams() {

      return {

        class_name:  document.getElementById('am_class').value || null,

        min_balance: parseFloat(document.getElementById('am_balance').value) || 0

      };

    }

  },

  feeding_summary: {

    title: 'Weekly Feeding Summary',

    html: `

      <div class="mb-3">

        <label class="form-label">Week Start (Monday)</label>

        <input type="date" class="form-control" id="am_week_start">

      </div>

      <div class="mb-3">

        <label class="form-label">Week End (Friday)</label>

        <input type="date" class="form-control" id="am_week_end">

      </div>`,

    action: 'send_weekly_feeding_summary',

    getParams() {

      return {

        week_start: document.getElementById('am_week_start').value || null,

        week_end:   document.getElementById('am_week_end').value   || null

      };

    }

  },

  terminal_reports: {

    title: 'Generate Terminal Reports',

    html: `

      <div class="mb-3">

        <label class="form-label">Class *</label>

        <select class="form-select" id="am_class" required><?php echo $classOptionsHtmlRequired; ?></select>

      </div>

      <div class="mb-3">

        <label class="form-label">Term</label>

        <select class="form-select" id="am_term"><?php echo $termOptions; ?></select>

      </div>

      <div class="mb-3">

        <label class="form-label">Academic Year</label>

        <input type="text" class="form-control" id="am_year" value="<?php echo htmlspecialchars($acad_year); ?>">

      </div>`,

    action: 'generate_terminal_reports',

    getParams() {

      return {

        class_name:    document.getElementById('am_class').value,

        term:          document.getElementById('am_term').value,

        academic_year: document.getElementById('am_year').value

      };

    }

  },

  exam_paper: {

    title: 'Generate Exam Paper',

    html: `

      <div class="mb-3">

        <label class="form-label">Subject *</label>

        <select class="form-select" id="am_subject"><?php echo $subjectOptionsHtml; ?></select>

      </div>

      <div class="mb-3">

        <label class="form-label">Class *</label>

        <select class="form-select" id="am_class"><?php echo $classOptionsHtmlRequired; ?></select>

      </div>

      <div class="row g-2">

        <div class="col-4"><label class="form-label">MCQ</label>

          <input type="number" class="form-control" id="am_mcq" value="20" min="0"></div>

        <div class="col-4"><label class="form-label">Theory</label>

          <input type="number" class="form-control" id="am_theory" value="5" min="0"></div>

        <div class="col-4"><label class="form-label">Fill Blank</label>

          <input type="number" class="form-control" id="am_fill" value="5" min="0"></div>

      </div>`,

    action: 'generate_exam_paper',

    getParams() {

      return {

        subject_name:     document.getElementById('am_subject').value,

        class_name:       document.getElementById('am_class').value,

        mcq_count:        parseInt(document.getElementById('am_mcq').value, 10)    || 0,

        theory_count:     parseInt(document.getElementById('am_theory').value, 10) || 0,

        fill_blank_count: parseInt(document.getElementById('am_fill').value, 10)   || 0

      };

    }

  },

  notify_parents: {

    title: 'Notify Parents',

    html: `

      <div class="mb-3">

        <label class="form-label">Send to</label>

        <select class="form-select" id="am_target" onchange="document.getElementById('am_class_row').style.display=this.value==='class'?'block':'none'">

          <option value="all">All Parents</option>

          <option value="class">Specific Class</option>

        </select>

      </div>

      <div class="mb-3" id="am_class_row" style="display:none">

        <label class="form-label">Class</label>

        <select class="form-select" id="am_class"><?php echo $classOptionsHtml; ?></select>

      </div>

      <div class="mb-3">

        <label class="form-label">Title *</label>

        <input type="text" class="form-control" id="am_title" placeholder="e.g. School reopening notice">

      </div>

      <div class="mb-3">

        <label class="form-label">Message *</label>

        <textarea class="form-control" id="am_msg" rows="4" placeholder="Type your message here…"></textarea>

      </div>

      <div class="form-check">

        <input type="checkbox" class="form-check-input" id="am_sms" checked>

        <label class="form-check-label">Also send via SMS</label>

      </div>`,

    action: 'bulk_notify_parents',

    getParams() {

      const target = document.getElementById('am_target').value;

      return {

        target:     target,

        class_name: target === 'class' ? document.getElementById('am_class').value : null,

        title:      document.getElementById('am_title').value,

        message:    document.getElementById('am_msg').value,

        send_sms:   document.getElementById('am_sms').checked

      };

    }

  },

  report_pdfs: {

    title: 'Batch Generate Report PDFs',

    html: `

      <div class="mb-3">

        <label class="form-label">Class *</label>

        <select class="form-select" id="am_class"><?php echo $classOptionsHtmlRequired; ?></select>

      </div>

      <div class="mb-3">

        <label class="form-label">Term</label>

        <select class="form-select" id="am_term"><?php echo $termOptions; ?></select>

      </div>

      <div class="alert alert-info small mb-0">

        <i class="fas fa-info-circle me-1"></i>

        Generates PDF report cards for all students in the class and creates a ZIP download.

      </div>`,

    action: 'batch_generate_report_pdfs',

    getParams() {

      return {

        class_name: document.getElementById('am_class').value,

        term:       document.getElementById('am_term').value

      };

    }

  }

};



let _activeModalType = null;



function openActionModal(type) {

    const form = modalForms[type];

    if (!form) return;

    _activeModalType = type;

    document.getElementById('actionModalTitle').textContent = form.title;

    document.getElementById('actionModalBody').innerHTML    = form.html;

    new bootstrap.Modal(document.getElementById('actionModal')).show();

}



function submitActionModal() {

    const form = modalForms[_activeModalType];

    if (!form) return;

    bootstrap.Modal.getInstance(document.getElementById('actionModal'))?.hide();

    runAction(form.action, form.getParams(), form.title);

}



// ── Deterministic action invocation ──────────────────────────────────────────

// Posts the exact values the operator picked. No sentence-building, no model

// re-parsing them back into parameters.

function runAction(action, params, label, confirmed) {

    if (isProcessing) return;

    isProcessing = true; setProcessing(true);



    appendUserMessage(label || action);

    const msgId = appendAiMessage();

    showThinking(msgId);

    appendActionProgress(msgId, action, label || action);



    fetch(ACTION_URL, {

        method:  'POST',

        headers: { 'Content-Type': 'application/json' },

        body:    JSON.stringify({

            action: action, params: params,

            csrf_token: RBC_CSRF, confirm: !!confirmed

        })

    })

    .then(r => r.json().then(j => ({ status: r.status, body: j })))

    .then(({ status, body }) => {

        hideThinking(msgId);

        isProcessing = false; setProcessing(false);



        if (body && body.needs_confirmation) {

            updateAiMessage(msgId, 'Confirmation needed before this runs.');

            appendConfirmCard(msgId, {

                type: action, params: params,

                message: body.confirmation_message, label: label

            });

            return;

        }

        if (status === 401 || status === 403) {

            updateAiMessage(msgId, '⚠ ' + (body.error || 'Access denied.'), 'error');

            return;

        }

        if (body && body.valid_classes && !body.success) {

            updateAiMessage(msgId, '⚠ ' + body.error, 'error');

            updateActionProgress(msgId, action, false, body.error, body);

            return;

        }

        updateAiMessage(msgId, body.summary || (body.success ? 'Done.' : 'That did not work.'));

        updateActionProgress(msgId, action, !!body.success, body.summary || '', body.result || {});

    })

    .catch(err => {

        hideThinking(msgId);

        isProcessing = false; setProcessing(false);

        updateAiMessage(msgId, '⚠ Could not reach the server: ' + err.message, 'error');

    });

}



// Confirmation gate for actions that cost money or contact parents.

function appendConfirmCard(msgId, data) {

    const cards = document.getElementById('actions_' + msgId);

    if (!cards) return;

    const id = 'confirm_' + Math.random().toString(36).slice(2, 10);

    window['__pending_' + id] = data;

    cards.insertAdjacentHTML('beforeend',

        `<div class="action-card" id="${id}" style="border-left:3px solid #f0ad4e">

           <div class="action-status">

             <i class="fas fa-triangle-exclamation text-warning me-2"></i>

             <span>${escHtml(String(data.message || 'Please confirm this action.'))}</span>

           </div>

           <div class="mt-2 d-flex gap-2">

             <button class="btn btn-sm btn-warning" onclick="confirmPending('${id}')">

               <i class="fas fa-check me-1"></i>Yes, run it</button>

             <button class="btn btn-sm btn-outline-secondary" onclick="cancelPending('${id}')">Cancel</button>

           </div>

         </div>`);

    scrollToBottom();

}



function confirmPending(id) {

    const data = window['__pending_' + id];

    const card = document.getElementById(id);

    if (!data) return;

    delete window['__pending_' + id];

    if (card) card.remove();

    runAction(data.type, data.params || {}, data.label || data.type, true);

}



function cancelPending(id) {

    delete window['__pending_' + id];

    const card = document.getElementById(id);

    if (card) {

        card.className = 'action-card failed';

        card.innerHTML = '<div class="action-status"><i class="fas fa-ban me-2"></i><span>Cancelled.</span></div>';

    }

}



// ── DataTables + Schedule modal init ─────────────────────────────────────────

$(document).ready(function() {

    if ($('#tasksTable tbody tr').length > 1) {

        $('#tasksTable').DataTable({ pageLength: 15, order: [[0,'desc']], language: { emptyTable: 'No tasks yet' } });

    }

    if ($('#schedulesTable tbody tr').length > 1) {

        $('#schedulesTable').DataTable({ pageLength: 15, language: { emptyTable: 'No schedules yet' } });

    }

    // Edit schedule modal prefill

    $('.edit-sched-btn').on('click', function() {

        const d = $(this).data();

        $('#sched_id_field').val(d.id);

        $('#sched_task_type').val(d.task);

        $('#sched_description').val(d.desc);

        $('#sched_day').val(d.day);

        $('#sched_time').val(d.time);

        $('#sched_payload').val(d.payload);

        $('#schedModalTitle').html('<i class="fas fa-edit me-2"></i>Edit Schedule');

    });

    $('#modalAddSchedule').on('hidden.bs.modal', function() {

        $('#sched_id_field').val('0');

        $('#schedModalTitle').html('<i class="fas fa-clock me-2"></i>Add Schedule');

    });

});

</script>

</body>

</html>

