<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
requireLogin();
$uid = $_SESSION['user_id'];
$currentUser = getCurrentUser();
$userIsPro = isProUser($currentUser);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    // ── Server-side AI proxy: keeps GROQ_API_KEY off the client and enforces quota ──
    if ($action === 'ai_chat') {
        $quota = checkAiQuota($uid, $currentUser);
        if (!$quota['allowed']) {
            jsonResponse(['success' => false, 'quota_exceeded' => true, 'message' => "Daily free AI limit reached ({$quota['limit']}/day). Upgrade to Pro for unlimited access."]);
        }
        $msgsJson = $_POST['messages'] ?? '[]';
        $messages = json_decode($msgsJson, true);
        if (!is_array($messages) || empty($messages)) {
            jsonResponse(['success' => false, 'message' => 'No messages provided.']);
        }
        try {
            $reply = callGroqServer($messages, 1024, 0.7);
            logAiUsage($uid, 'ai_tips_chat');
            $quota2 = checkAiQuota($uid, $currentUser);
            jsonResponse(['success' => true, 'reply' => $reply, 'quota' => $quota2]);
        } catch (Exception $e) {
            jsonResponse(['success' => false, 'message' => $e->getMessage()]);
        }
    }
    if ($action === 'ai_generate_tips') {
        $quota = checkAiQuota($uid, $currentUser);
        if (!$quota['allowed']) {
            jsonResponse(['success' => false, 'quota_exceeded' => true, 'message' => "Daily free AI limit reached ({$quota['limit']}/day). Upgrade to Pro for unlimited access."]);
        }
        $sys = sanitize($_POST['sys'] ?? 'Expert study coach for Sri Lankan A/L students.');
        $usr = $_POST['usr'] ?? '';
        if (!$usr) jsonResponse(['success' => false, 'message' => 'No prompt provided.']);
        try {
            $reply = callGroqServer([
                ['role' => 'system', 'content' => $sys],
                ['role' => 'user', 'content' => $usr],
            ], 800, 0.7);
            logAiUsage($uid, 'ai_tips_generate');
            $quota2 = checkAiQuota($uid, $currentUser);
            jsonResponse(['success' => true, 'reply' => $reply, 'quota' => $quota2]);
        } catch (Exception $e) {
            jsonResponse(['success' => false, 'message' => $e->getMessage()]);
        }
    }

    if ($action === 'delete_tip') { $pdo->prepare("DELETE FROM ai_tips_log WHERE id=? AND user_id=?")->execute([(int)$_POST['id'],$uid]); jsonResponse(['success'=>true]); }
    if ($action === 'clear_tips') { $pdo->prepare("DELETE FROM ai_tips_log WHERE user_id=?")->execute([$uid]); jsonResponse(['success'=>true]); }
    if ($action === 'get_context') {
        $q=$pdo->prepare("SELECT COALESCE(SUM(duration_minutes),0)/60 FROM study_sessions WHERE user_id=? AND date>=DATE_SUB(CURDATE(),INTERVAL 7 DAY)");$q->execute([$uid]);$wh=round($q->fetchColumn(),1);
        $q=$pdo->prepare("SELECT COALESCE(AVG(marks_obtained/total_marks*100),0) FROM marks WHERE user_id=?");$q->execute([$uid]);$am=round($q->fetchColumn(),1);
        $q=$pdo->prepare("SELECT name FROM subjects WHERE user_id=? ORDER BY name");$q->execute([$uid]);$subs=implode(', ',$q->fetchAll(PDO::FETCH_COLUMN));
        $q=$pdo->prepare("SELECT COUNT(*) FROM tasks WHERE user_id=? AND status='pending'");$q->execute([$uid]);$pt=(int)$q->fetchColumn();
        jsonResponse(['success'=>true,'weekHours'=>$wh,'avgMark'=>$am,'subjects'=>$subs,'pendingTasks'=>$pt]);
    }
    if ($action === 'save_tip') {
        $t=substr(sanitize($_POST['tip_text']??''),0,5000);$tp=sanitize($_POST['topic']??'general');
        if($t)$pdo->prepare("INSERT INTO ai_tips_log (user_id,tip_text,context_type) VALUES (?,?,?)")->execute([$uid,$t,$tp]);
        jsonResponse(['success'=>true]);
    }
}

$pastTipsQ=$pdo->prepare("SELECT * FROM ai_tips_log WHERE user_id=? ORDER BY created_at DESC LIMIT 10");
$pastTipsQ->execute([$uid]);$pastTips=$pastTipsQ->fetchAll();
$subjectsQ=$pdo->prepare("SELECT id,name FROM subjects WHERE user_id=? ORDER BY name");
$subjectsQ->execute([$uid]);$subjects=$subjectsQ->fetchAll();
$userInitial=strtoupper(substr($_SESSION['user_name']??'U',0,1));

require_once 'includes/header.php';
renderHeader('AI Tips','ai-tips');
?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800;900&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap');
:root{--df:'Outfit',sans-serif;--db:'Plus Jakarta Sans',sans-serif;}
.at-wrap{max-width:1120px;padding-bottom:60px;font-family:var(--db);}
.at-hd{margin-bottom:26px;}
.at-hd-title{font-family:var(--df);font-size:26px;font-weight:800;color:var(--text-primary);letter-spacing:-.4px;}
.at-hd-sub{font-size:13px;color:var(--text-muted);margin-top:4px;}
/* Stats */
.at-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:22px;}
@media(max-width:600px){.at-stats{grid-template-columns:1fr;}}
.at-stat{background:var(--bg-card);border:1px solid var(--border);border-radius:16px;padding:18px 20px;position:relative;overflow:hidden;animation:atup .4s ease both;}
.at-stat::after{content:'';position:absolute;width:70px;height:70px;border-radius:50%;top:-15px;right:-15px;pointer-events:none;}
.at-s1::after{background:rgba(99,102,241,.14);} .at-s2::after{background:rgba(16,185,129,.12);} .at-s3::after{background:rgba(245,158,11,.12);}
.at-stat-v{font-family:var(--df);font-size:28px;font-weight:800;color:var(--text-primary);line-height:1;}
.at-stat-l{font-size:12px;color:var(--text-muted);margin-top:5px;}
/* Grid */
.at-grid{display:grid;grid-template-columns:320px 1fr;gap:16px;align-items:start;}
@media(max-width:880px){.at-grid{grid-template-columns:1fr;}}
/* Card */
.at-card{background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:22px;animation:atup .5s .08s ease both;}
.at-ct{font-family:var(--df);font-size:14px;font-weight:700;color:var(--text-primary);margin-bottom:14px;}
/* Topics */
.at-topics{display:flex;flex-direction:column;gap:7px;margin-bottom:16px;}
.at-topic{display:flex;align-items:center;gap:11px;padding:12px 14px;border-radius:12px;background:var(--bg-secondary);border:1px solid var(--border);cursor:pointer;transition:all .18s;font-size:13px;font-weight:600;color:var(--text-secondary);}
.at-topic:hover{border-color:rgba(99,102,241,.35);color:var(--text-primary);background:rgba(99,102,241,.05);}
.at-topic.active{background:linear-gradient(135deg,rgba(99,102,241,.16),rgba(168,85,247,.10));border-color:rgba(99,102,241,.4);color:var(--text-primary);}
.at-ticon{width:32px;height:32px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:15px;flex-shrink:0;}
/* Controls */
.at-sel{width:100%;background:var(--bg-secondary);border:1px solid var(--border);border-radius:10px;padding:9px 13px;font-family:var(--db);font-size:13px;color:var(--text-primary);margin-bottom:12px;outline:none;transition:border-color .18s;}
.at-sel:focus{border-color:rgba(99,102,241,.5);}
.at-lang{display:flex;background:var(--bg-secondary);border-radius:10px;padding:3px;gap:3px;margin-bottom:14px;}
.at-lb{flex:1;padding:8px;border-radius:7px;border:none;cursor:pointer;font-family:var(--db);font-size:12px;font-weight:700;background:transparent;color:var(--text-muted);transition:all .16s;}
.at-lb.active{background:var(--bg-card);color:var(--text-primary);box-shadow:0 1px 4px rgba(0,0,0,.2);}
.at-gbtn{width:100%;padding:13px;border-radius:12px;border:none;cursor:pointer;background:linear-gradient(135deg,#6366f1,#a855f7);color:#fff;font-family:var(--db);font-size:13px;font-weight:700;display:flex;align-items:center;justify-content:center;gap:8px;transition:all .2s;box-shadow:0 4px 18px rgba(99,102,241,.3);}
.at-gbtn:hover{transform:translateY(-2px);box-shadow:0 8px 26px rgba(99,102,241,.42);} .at-gbtn:disabled{opacity:.6;cursor:not-allowed;transform:none;}
/* Chat */
.at-chat{display:flex;flex-direction:column;height:530px;background:var(--bg-card);border:1px solid var(--border);border-radius:20px;overflow:hidden;animation:atup .5s .12s ease both;}
.at-chd{padding:16px 18px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;flex-shrink:0;}
.at-chd-l{display:flex;align-items:center;gap:10px;}
.at-bav{width:36px;height:36px;border-radius:11px;background:linear-gradient(135deg,#6366f1,#a855f7);display:flex;align-items:center;justify-content:center;font-size:18px;}
.at-btitle{font-family:var(--df);font-size:14px;font-weight:700;color:var(--text-primary);}
.at-online{display:flex;align-items:center;gap:5px;font-size:11px;color:#10b981;font-weight:600;}
.at-online::before{content:'';width:6px;height:6px;border-radius:50%;background:#10b981;animation:pulse 2s infinite;}
.at-msgs{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;scroll-behavior:smooth;}
.at-msgs::-webkit-scrollbar{width:3px;} .at-msgs::-webkit-scrollbar-thumb{background:var(--border-light);border-radius:99px;}
.msg{display:flex;gap:9px;align-items:flex-end;} .msg.user{flex-direction:row-reverse;}
.msg-av{width:29px;height:29px;border-radius:8px;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;}
.msg.bot .msg-av{background:linear-gradient(135deg,#6366f1,#a855f7);font-size:15px;} .msg.user .msg-av{background:linear-gradient(135deg,#06b6d4,#6366f1);color:#fff;font-size:11px;}
.msg-bubble{max-width:78%;padding:10px 14px;border-radius:14px;font-size:13px;line-height:1.65;color:var(--text-primary);white-space:pre-wrap;word-break:break-word;}
.msg.bot .msg-bubble{background:var(--bg-secondary);border:1px solid var(--border);border-bottom-left-radius:4px;}
.msg.user .msg-bubble{background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;border-bottom-right-radius:4px;}
.tdot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--text-muted);margin:0 2px;animation:tdot .9s ease-in-out infinite;}
.tdot:nth-child(2){animation-delay:.15s;} .tdot:nth-child(3){animation-delay:.3s;}
.at-suggs{display:flex;gap:6px;flex-wrap:wrap;padding:0 16px 12px;flex-shrink:0;}
.at-sg{padding:5px 12px;border-radius:99px;border:1px solid rgba(99,102,241,.3);background:rgba(99,102,241,.06);font-size:11px;font-weight:600;color:var(--accent);cursor:pointer;transition:all .16s;white-space:nowrap;}
.at-sg:hover{background:rgba(99,102,241,.15);border-color:rgba(99,102,241,.5);}
.at-ci{padding:12px 14px;border-top:1px solid var(--border);display:flex;gap:9px;align-items:flex-end;flex-shrink:0;}
.at-inp{flex:1;background:var(--bg-secondary);border:1px solid var(--border);border-radius:12px;padding:9px 13px;font-family:var(--db);font-size:13px;color:var(--text-primary);outline:none;resize:none;max-height:90px;transition:border-color .18s;line-height:1.5;}
.at-inp:focus{border-color:rgba(99,102,241,.5);} .at-inp::placeholder{color:var(--text-muted);}
.at-send{width:38px;height:38px;border-radius:11px;border:none;cursor:pointer;flex-shrink:0;background:linear-gradient(135deg,#6366f1,#a855f7);display:flex;align-items:center;justify-content:center;transition:all .2s;}
.at-send:hover{transform:scale(1.08);box-shadow:0 4px 14px rgba(99,102,241,.4);} .at-send:disabled{opacity:.5;cursor:not-allowed;transform:none;}
/* Result */
.at-result{background:var(--bg-card);border:1px solid rgba(99,102,241,.22);border-radius:18px;padding:20px;margin-top:14px;display:none;background:linear-gradient(145deg,var(--bg-card),rgba(99,102,241,.03));}
.at-rh{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;}
.at-rt{font-family:var(--df);font-size:14px;font-weight:700;color:var(--text-primary);}
.at-cbtn{padding:5px 12px;border-radius:8px;border:1px solid rgba(99,102,241,.3);background:rgba(99,102,241,.08);font-size:12px;font-weight:700;color:var(--accent);cursor:pointer;transition:all .16s;}
.at-cbtn:hover{background:rgba(99,102,241,.18);}
.at-rbody{font-size:13.5px;line-height:1.8;color:var(--text-secondary);white-space:pre-wrap;}
/* Past tips */
.at-past{margin-top:16px;animation:atup .5s .18s ease both;}
.at-ptitle{font-family:var(--df);font-size:14px;font-weight:700;color:var(--text-primary);display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;}
.at-pi{background:var(--bg-card);border:1px solid var(--border);border-radius:13px;overflow:hidden;margin-bottom:9px;transition:border-color .2s;}
.at-pi:hover{border-color:var(--border-light);}
.at-ph{display:flex;align-items:center;justify-content:space-between;padding:12px 15px;cursor:pointer;background:var(--bg-secondary);}
.at-phl{display:flex;align-items:center;gap:9px;}
.at-ptag{padding:3px 9px;border-radius:99px;font-size:11px;font-weight:700;background:rgba(99,102,241,.12);color:var(--accent);}
.at-pdate{font-size:11px;color:var(--text-muted);}
.at-pb{display:none;padding:14px;font-size:13px;color:var(--text-secondary);line-height:1.7;white-space:pre-wrap;}
.at-dbtn{width:26px;height:26px;border-radius:7px;border:none;cursor:pointer;background:rgba(239,68,68,.1);color:#ef4444;display:flex;align-items:center;justify-content:center;transition:all .16s;flex-shrink:0;}
.at-dbtn:hover{background:rgba(239,68,68,.2);}
.at-clrbtn{padding:5px 12px;border-radius:8px;border:1px solid rgba(239,68,68,.3);background:rgba(239,68,68,.08);font-size:12px;font-weight:700;color:#ef4444;cursor:pointer;transition:all .16s;}
.at-clrbtn:hover{background:rgba(239,68,68,.18);}
.at-sp{width:15px;height:15px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite;}
@keyframes spin{to{transform:rotate(360deg);}}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}
@keyframes tdot{0%,100%{transform:translateY(0)}50%{transform:translateY(-5px)}}
@keyframes atup{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
/* Daily tip popup */
.at-dov{position:fixed;inset:0;background:rgba(8,8,16,.6);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);display:flex;align-items:center;justify-content:center;z-index:9999;padding:20px;opacity:0;pointer-events:none;transition:opacity .25s ease;}
.at-dov.show{opacity:1;pointer-events:auto;}
.at-dmodal{width:100%;max-width:420px;background:linear-gradient(160deg,var(--bg-card),rgba(99,102,241,.06));border:1px solid rgba(99,102,241,.28);border-radius:22px;padding:0;overflow:hidden;box-shadow:0 24px 70px rgba(0,0,0,.45);transform:translateY(18px) scale(.96);opacity:0;transition:all .32s cubic-bezier(.2,.9,.25,1.1);}
.at-dov.show .at-dmodal{transform:translateY(0) scale(1);opacity:1;}
.at-dhead{position:relative;padding:26px 26px 18px;background:linear-gradient(135deg,rgba(99,102,241,.18),rgba(168,85,247,.1));text-align:center;}
.at-dclose{position:absolute;top:14px;right:14px;width:28px;height:28px;border-radius:9px;border:none;background:rgba(255,255,255,.08);color:var(--text-secondary);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .16s;}
.at-dclose:hover{background:rgba(255,255,255,.16);color:var(--text-primary);}
.at-dicon{width:56px;height:56px;margin:0 auto 12px;border-radius:16px;background:linear-gradient(135deg,#6366f1,#a855f7);display:flex;align-items:center;justify-content:center;font-size:26px;box-shadow:0 8px 22px rgba(99,102,241,.4);animation:atbob 2.4s ease-in-out infinite;}
@keyframes atbob{0%,100%{transform:translateY(0)}50%{transform:translateY(-6px)}}
.at-dtitle{font-family:var(--df);font-size:17px;font-weight:800;color:var(--text-primary);letter-spacing:-.2px;}
.at-dsub{font-size:12px;color:var(--text-muted);margin-top:4px;}
.at-dbody{padding:20px 26px 26px;}
.at-dtext{font-size:13.5px;line-height:1.8;color:var(--text-secondary);white-space:pre-wrap;min-height:60px;}
.at-dload{display:flex;align-items:center;gap:10px;color:var(--text-muted);font-size:13px;padding:14px 0;}
.at-dactions{display:flex;gap:10px;margin-top:20px;}
.at-dbtn2{flex:1;padding:12px;border-radius:12px;border:none;cursor:pointer;font-family:var(--db);font-size:13px;font-weight:700;transition:all .18s;}
.at-dgo{background:linear-gradient(135deg,#6366f1,#a855f7);color:#fff;box-shadow:0 4px 16px rgba(99,102,241,.32);}
.at-dgo:hover{transform:translateY(-1px);box-shadow:0 8px 22px rgba(99,102,241,.42);}
.at-dsk{background:var(--bg-secondary);border:1px solid var(--border);color:var(--text-secondary);}
.at-dsk:hover{color:var(--text-primary);}
/* Quota-limit popup */
.at-qov{position:fixed;inset:0;background:rgba(8,8,16,.6);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);display:flex;align-items:center;justify-content:center;z-index:9999;padding:20px;opacity:0;pointer-events:none;transition:opacity .25s ease;}
.at-qov.show{opacity:1;pointer-events:auto;}
.at-qmodal{width:100%;max-width:400px;background:linear-gradient(160deg,var(--bg-card),rgba(245,158,11,.06));border:1px solid rgba(245,158,11,.28);border-radius:22px;overflow:hidden;box-shadow:0 24px 70px rgba(0,0,0,.45);transform:translateY(18px) scale(.96);opacity:0;transition:all .32s cubic-bezier(.2,.9,.25,1.1);}
.at-qov.show .at-qmodal{transform:translateY(0) scale(1);opacity:1;}
.at-qhead{padding:28px 26px 16px;background:linear-gradient(135deg,rgba(245,158,11,.18),rgba(249,115,22,.1));text-align:center;}
.at-qicon{width:56px;height:56px;margin:0 auto 12px;border-radius:16px;background:linear-gradient(135deg,#f59e0b,#f97316);display:flex;align-items:center;justify-content:center;font-size:26px;box-shadow:0 8px 22px rgba(245,158,11,.4);}
.at-qtitle{font-family:var(--df);font-size:17px;font-weight:800;color:var(--text-primary);letter-spacing:-.2px;}
.at-qbody{padding:18px 26px 26px;text-align:center;}
.at-qtext{font-size:13.5px;line-height:1.7;color:var(--text-secondary);}
.at-qactions{display:flex;gap:10px;margin-top:22px;}
.at-qbtn{flex:1;padding:12px;border-radius:12px;border:none;cursor:pointer;font-family:var(--db);font-size:13px;font-weight:700;transition:all .18s;}
.at-qgo{background:linear-gradient(135deg,#f59e0b,#f97316);color:#fff;box-shadow:0 4px 16px rgba(245,158,11,.32);}
.at-qgo:hover{transform:translateY(-1px);box-shadow:0 8px 22px rgba(245,158,11,.42);}
.at-qsk{background:var(--bg-secondary);border:1px solid var(--border);color:var(--text-secondary);}
.at-qsk:hover{color:var(--text-primary);}
</style>

<!-- Daily tip popup -->
<div class="at-dov" id="dailyOv">
  <div class="at-dmodal">
    <div class="at-dhead">
      <button class="at-dclose" onclick="closeDaily()" aria-label="Close">
        <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
      <div class="at-dicon">✨</div>
      <div class="at-dtitle">Your Daily Tip</div>
      <div class="at-dsub" id="dailyDate"></div>
    </div>
    <div class="at-dbody">
      <div class="at-dload" id="dailyLoad"><div class="at-sp"></div> Generating your tip…</div>
      <div class="at-dtext" id="dailyText" style="display:none;"></div>
      <div class="at-dactions">
        <button class="at-dbtn2 at-dsk" onclick="closeDaily()">Maybe later</button>
        <button class="at-dbtn2 at-dgo" onclick="closeDaily()">Got it 🎯</button>
      </div>
    </div>
  </div>
</div>

<!-- Quota-limit popup -->
<div class="at-qov" id="quotaOv">
  <div class="at-qmodal">
    <div class="at-qhead">
      <div class="at-qicon">🔒</div>
      <div class="at-qtitle">Daily Limit Reached</div>
    </div>
    <div class="at-qbody">
      <div class="at-qtext" id="quotaMsg">Daily free AI limit reached.</div>
      <div class="at-qactions">
        <button class="at-qbtn at-qsk" onclick="closeQuota()">Maybe later</button>
        <button class="at-qbtn at-qgo" onclick="goUpgrade()">⚡ Upgrade to Pro</button>
      </div>
    </div>
  </div>
</div>

<div class="at-wrap">
<div class="at-hd">
  <div class="at-hd-title">✨ AI Study Assistant</div>
  <div class="at-hd-sub">Personalized tips &amp; chat powered by AI — for A/L students</div>
</div>

<?php $quotaInit = checkAiQuota($uid, $currentUser); ?>
<?php if (!$userIsPro): ?>
<div id="quotaBanner" style="display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;background:linear-gradient(135deg,rgba(245,158,11,.12),rgba(245,158,11,.04));border:1px solid rgba(245,158,11,.28);border-radius:14px;padding:13px 18px;margin-bottom:20px;font-size:13px;">
  <span style="color:var(--text-secondary);">🔒 Free plan: <b id="quotaText"><?= $quotaInit['used'] ?>/<?= $quotaInit['limit'] ?></b> AI requests used today</span>
  <a href="<?= SITE_URL ?>/upgrade" style="background:linear-gradient(135deg,#f59e0b,#f97316);color:#fff;font-weight:700;padding:8px 16px;border-radius:9px;text-decoration:none;white-space:nowrap;">⚡ Upgrade to Pro</a>
</div>
<?php else: ?>
<div style="display:inline-flex;align-items:center;gap:8px;background:linear-gradient(135deg,rgba(16,185,129,.14),rgba(16,185,129,.05));border:1px solid rgba(16,185,129,.3);color:#10b981;font-weight:700;font-size:12.5px;padding:7px 14px;border-radius:999px;margin-bottom:18px;">✨ Pro — Unlimited AI access</div>
<?php endif; ?>

<div class="at-stats">
  <div class="at-stat at-s1"><div class="at-stat-v" id="sH">—</div><div class="at-stat-l">Study hours this week</div></div>
  <div class="at-stat at-s2"><div class="at-stat-v" id="sM">—</div><div class="at-stat-l">Average marks</div></div>
  <div class="at-stat at-s3"><div class="at-stat-v" id="sT">—</div><div class="at-stat-l">Pending tasks</div></div>
</div>

<div class="at-grid">
  <!-- Left: Tips -->
  <div>
    <div class="at-card">
      <div class="at-ct">💡 Generate Tips</div>
      <div class="at-topics">
        <?php $tps=[['general','📚','General Tips','rgba(99,102,241,.12)'],['motivation','🔥','Motivation','rgba(239,68,68,.12)'],['schedule','📅','Study Schedule','rgba(6,182,212,.12)'],['exam','📝','Exam Strategies','rgba(245,158,11,.12)'],['weak','💪','Weak Subjects','rgba(16,185,129,.12)']]; foreach($tps as $i=>[$id,$ico,$lbl,$bg]): ?>
        <div class="at-topic <?=$i===0?'active':''?>" data-topic="<?=$id?>" onclick="selTopic(this)">
          <div class="at-ticon" style="background:<?=$bg?>"><?=$ico?></div><span><?=$lbl?></span>
        </div>
        <?php endforeach; ?>
      </div>
      <?php if($subjects): ?>
      <select class="at-sel" id="tipSub"><option value="">All subjects</option><?php foreach($subjects as $s): ?><option value="<?=htmlspecialchars($s['name'])?>"><?=htmlspecialchars($s['name'])?></option><?php endforeach; ?></select>
      <?php endif; ?>
      <div class="at-lang">
        <button class="at-lb active" id="lEn" onclick="setLang('en')">🇬🇧 English</button>
        <button class="at-lb" id="lSi" onclick="setLang('si')">🇱🇰 සිංහල</button>
      </div>
      <button class="at-gbtn" id="genBtn" onclick="getTips()">
        <svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.3" viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>Generate Tips
      </button>
    </div>

    <div class="at-result" id="tipsResult">
      <div class="at-rh"><div class="at-rt">✨ Your Tips</div><button class="at-cbtn" onclick="copyTips()">Copy</button></div>
      <div class="at-rbody" id="tipsContent"></div>
    </div>

    <?php if($pastTips): ?>
    <div class="at-past" id="pastCard">
      <div class="at-ptitle"><span>📂 Previous Tips</span><button class="at-clrbtn" onclick="clearAll()">Clear All</button></div>
      <div id="pastList">
        <?php foreach($pastTips as $t): ?>
        <div class="at-pi" id="tip-<?=$t['id']?>">
          <div class="at-ph" onclick="togTip(this)">
            <div class="at-phl"><span class="at-ptag"><?=ucfirst($t['context_type'])?></span><span class="at-pdate"><?=date('M j, g:ia',strtotime($t['created_at']))?></span></div>
            <button class="at-dbtn" onclick="event.stopPropagation();delTip(<?=$t['id']?>)"><svg width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/></svg></button>
          </div>
          <div class="at-pb"><?=htmlspecialchars($t['tip_text'])?></div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>

  <!-- Right: Chat -->
  <div class="at-chat">
    <div class="at-chd">
      <div class="at-chd-l">
        <div class="at-bav">🤖</div>
        <div><div class="at-btitle">StudyBot</div><div class="at-online">Online</div></div>
      </div>
      <button class="at-cbtn" onclick="clearChat()">Clear</button>
    </div>
    <div class="at-msgs" id="chatMsgs"></div>
    <div class="at-suggs">
      <span class="at-sg" onclick="sndSugg(this)">How to study better?</span>
      <span class="at-sg" onclick="sndSugg(this)">Exam tips</span>
      <span class="at-sg" onclick="sndSugg(this)">Motivation boost</span>
      <span class="at-sg" onclick="sndSugg(this)">Daily schedule help</span>
    </div>
    <div class="at-ci">
      <textarea class="at-inp" id="chatInp" rows="1" placeholder="Ask anything… / ඕනෑ දෙයක් අහන්න…" oninput="autoR(this)" onkeydown="chatKey(event)"></textarea>
      <button class="at-send" id="sendBtn" onclick="sendMsg()"><svg width="15" height="15" fill="none" stroke="white" stroke-width="2.5" viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg></button>
    </div>
  </div>
</div>
</div>

<script>
const U_INIT=<?=json_encode($userInitial)?>;
const IS_PRO=<?=json_encode($userIsPro)?>;
let hist=[],typing=false,ctx=null,topic='general',lang='en';

function updateQuotaUI(q){
  if(IS_PRO||!q)return;
  const t=document.getElementById('quotaText');if(t)t.textContent=q.used+'/'+q.limit;
}
function quotaBlocked(msg){
  document.getElementById('quotaMsg').textContent=msg||'Daily free AI limit reached.';
  document.getElementById('quotaOv').classList.add('show');
}
function closeQuota(){document.getElementById('quotaOv').classList.remove('show');}
function goUpgrade(){location.href='<?= SITE_URL ?>/upgrade';}
document.getElementById('quotaOv').addEventListener('click',e=>{if(e.target.id==='quotaOv')closeQuota();});

async function loadCtx(){
  try{const fd=new FormData();fd.append('action','get_context');const r=await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});const d=await r.json();if(d.success){ctx=d;document.getElementById('sH').textContent=d.weekHours+'h';document.getElementById('sM').textContent=d.avgMark+'%';document.getElementById('sT').textContent=d.pendingTasks;}}catch(e){}
}
loadCtx();
appendMsg('bot','👋 Hi! I\'m StudyBot!\n\nAsk me anything about studying, exam tips, or time management.\n\nYou can chat in English or Sinhala (සිංහල) 🇱🇰');

/* ── Daily tip popup: shows once per day per user ── */
const DAILY_UID=<?=json_encode($uid)?>;
function todayStr(){const d=new Date();return d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0');}
function dailyKey(){return 'dailyTipShown_'+DAILY_UID+'_'+todayStr();}
function openDaily(){document.getElementById('dailyOv').classList.add('show');}
function closeDaily(){document.getElementById('dailyOv').classList.remove('show');localStorage.setItem(dailyKey(),'1');}

async function showDailyTip(){
  if(localStorage.getItem(dailyKey()))return; // already shown today
  document.getElementById('dailyDate').textContent=new Date().toLocaleDateString(undefined,{weekday:'long',month:'long',day:'numeric'});
  openDaily();
  try{
    await new Promise(r=>setTimeout(r,300)); // let context load
    const wh=ctx?.weekHours??0,am=ctx?.avgMark??0,subs=ctx?.subjects||'',pt=ctx?.pendingTasks??0;
    const c=`Student: ${wh}h studied this week, ${am}% average marks, ${pt} pending tasks.`+(subs?` Subjects: ${subs}.`:'');
    const prompt=`Give ONE short, warm, motivating daily study tip (2-3 sentences max) for an A/L student in Sri Lanka, personalized using this data: ${c} Keep it punchy and encouraging, no numbering, no headers.`;
    const tip=await groq([{role:'system',content:'Expert, friendly study coach for Sri Lankan A/L students.'},{role:'user',content:prompt}]);
    document.getElementById('dailyLoad').style.display='none';
    const dt=document.getElementById('dailyText');dt.textContent=tip;dt.style.display='block';
    const fd=new FormData();fd.append('action','save_tip');fd.append('tip_text',tip);fd.append('topic','daily');
    fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
  }catch(e){
    closeDaily();
    if(e.message!=='QUOTA'){
      document.getElementById('dailyLoad').style.display='none';
    }
  }
}
document.getElementById('dailyOv').addEventListener('click',e=>{if(e.target.id==='dailyOv')closeDaily();});
showDailyTip();

function sysPrompt(){const wh=ctx?.weekHours??'?',am=ctx?.avgMark??'?',subs=ctx?.subjects||'Not set',pt=ctx?.pendingTasks??'?';return `You are StudyBot for Sri Lankan A/L students. Student data: ${wh}h study/week, ${am}% avg, ${pt} pending tasks, subjects: ${subs}. LANGUAGE RULE: Match the language the student writes in. Sinhala/Singlish → reply in Sinhala script. English → English only. Never mix.`;}

async function groq(msgs){
  const fd=new FormData();fd.append('action','ai_chat');fd.append('messages',JSON.stringify(msgs));
  const r=await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
  const d=await r.json();
  if(d.quota_exceeded){quotaBlocked(d.message);throw new Error('QUOTA');}
  if(!d.success)throw new Error(d.message||'API error');
  updateQuotaUI(d.quota);
  return d.reply||'No response.';
}

function scrollBot(){const el=document.getElementById('chatMsgs');el.scrollTop=el.scrollHeight;}
function autoR(el){el.style.height='auto';el.style.height=Math.min(el.scrollHeight,90)+'px';}
function chatKey(e){if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();sendMsg();}}
function sndSugg(el){document.getElementById('chatInp').value=el.textContent.trim();sendMsg();}
function togTip(el){const b=el.nextElementSibling;b.style.display=b.style.display==='none'?'block':'none';}

function appendMsg(role,text){
  const c=document.getElementById('chatMsgs');
  const d=document.createElement('div');d.className='msg '+role;
  const av=document.createElement('div');av.className='msg-av';av.textContent=role==='bot'?'🤖':U_INIT;
  const b=document.createElement('div');b.className='msg-bubble';b.textContent=text;
  d.appendChild(av);d.appendChild(b);c.appendChild(d);scrollBot();
}
function showTyp(){
  const c=document.getElementById('chatMsgs');
  const d=document.createElement('div');d.className='msg bot';d.id='typInd';
  const av=document.createElement('div');av.className='msg-av';av.textContent='🤖';
  const b=document.createElement('div');b.className='msg-bubble';
  b.innerHTML='<span class="tdot"></span><span class="tdot"></span><span class="tdot"></span>';
  d.appendChild(av);d.appendChild(b);c.appendChild(d);scrollBot();
}
function rmTyp(){const el=document.getElementById('typInd');if(el)el.remove();}

async function sendMsg(){
  if(typing)return;
  const inp=document.getElementById('chatInp');const msg=inp.value.trim();if(!msg)return;
  inp.value='';inp.style.height='auto';
  document.getElementById('sendBtn').disabled=true;typing=true;
  appendMsg('user',msg);hist.push({role:'user',content:msg});showTyp();
  try{const msgs=[{role:'system',content:sysPrompt()},...hist.slice(-10)];const reply=await groq(msgs);rmTyp();appendMsg('bot',reply);hist.push({role:'assistant',content:reply});}
  catch(e){rmTyp();if(e.message!=='QUOTA')appendMsg('bot','⚠️ '+(e.message||'Error. Try again.'));}
  typing=false;document.getElementById('sendBtn').disabled=false;document.getElementById('chatInp').focus();
}

function clearChat(){hist=[];document.getElementById('chatMsgs').innerHTML='';appendMsg('bot','👋 Cleared! / Clear කළා! Ask anything.');}

function selTopic(el){document.querySelectorAll('.at-topic').forEach(b=>b.classList.remove('active'));el.classList.add('active');topic=el.dataset.topic;}
function setLang(l){lang=l;document.getElementById('lEn').classList.toggle('active',l==='en');document.getElementById('lSi').classList.toggle('active',l==='si');}

async function getTips(){
  const btn=document.getElementById('genBtn');const sub=document.getElementById('tipSub')?.value||'';
  btn.disabled=true;btn.innerHTML='<div class="at-sp"></div> Generating…';
  document.getElementById('tipsResult').style.display='none';
  const wh=ctx?.weekHours??0,am=ctx?.avgMark??0,subs=ctx?.subjects||'',pt=ctx?.pendingTasks??0;
  const c=`Student: ${wh}h/week, ${am}% avg, ${pt} tasks.`+(subs?` Subjects: ${subs}.`:'')+(sub?` Focus: ${sub}.`:'');
  const ln=lang==='si'?'Reply ONLY in Sinhala script. No English.':'Reply ONLY in English.';
  const ps={general:`${ln}\n\nGive 5 practical personalized study tips for A/L student. Numbered.\n\n${c}`,motivation:`${ln}\n\nEncouraging message + 3 actionable steps today.\n\n${c}`,schedule:`${ln}\n\nOptimal daily schedule for A/L student in Sri Lanka. Time blocks, breaks, rotation.\n\n${c}`,exam:`${ln}\n\n5 evidence-based exam prep strategies for A/L Sri Lanka.\n\n${c}`,weak:`${ln}\n\nStrategies to improve least-studied subjects. Spaced repetition, active recall.\n\n${c}`};
  try{
    const tips=await groq([{role:'system',content:'Expert study coach for Sri Lankan A/L students.'},{role:'user',content:ps[topic]||ps.general}]);
    document.getElementById('tipsContent').textContent=tips;
    document.getElementById('tipsResult').style.display='block';
    document.getElementById('tipsResult').scrollIntoView({behavior:'smooth',block:'nearest'});
    const fd=new FormData();fd.append('action','save_tip');fd.append('tip_text',tips);fd.append('topic',topic);
    fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:fd});
  }catch(e){if(e.message!=='QUOTA')alert('⚠️ '+(e.message||'Failed.'));}
  btn.disabled=false;btn.innerHTML='<svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.3" viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>Generate Tips';
}

function copyTips(){navigator.clipboard.writeText(document.getElementById('tipsContent').textContent);const b=event.target;b.textContent='Copied!';setTimeout(()=>b.textContent='Copy',2000);}

async function delTip(id){
  if(!(await stConfirm('Remove?')))return;
  const r=await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:new URLSearchParams({action:'delete_tip',id})});
  const d=await r.json();if(d.success){const el=document.getElementById('tip-'+id);el.style.opacity='0';el.style.transition='opacity .3s';setTimeout(()=>{el.remove();if(!document.getElementById('pastList')?.children.length)document.getElementById('pastCard')?.remove();},300);}
}
async function clearAll(){
  if(!(await stConfirm('Clear all tips?')))return;
  const r=await fetch(location.href,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:new URLSearchParams({action:'clear_tips'})});
  const d=await r.json();if(d.success){const c=document.getElementById('pastCard');if(c){c.style.opacity='0';c.style.transition='opacity .3s';setTimeout(()=>c.remove(),300);}}
}
</script>
<?php require_once 'includes/footer.php'; renderFooter(); ?>
