<?php
/**
 * StudyTrack Telegram Bot API
 * File: /studytrack/api/telegram-bot.php
 *
 * FIXED: Reads params from GET (URL query string) — bypasses mod_security POST blocking
 */

require_once '../includes/config.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// ── Read params from GET (sent via URL query string from bot) ─────────────────
$action      = trim($_GET['action']      ?? '');
$telegram_id = (int)($_GET['telegram_id'] ?? 0);

if (!$action || !$telegram_id) {
    echo json_encode([
        'success' => false,
        'message' => 'No action',
        'debug'   => ['get' => $_GET, 'post' => $_POST]
    ]);
    exit;
}

// ── Extra param helper (GET) ───────────────────────────────────────────────────
function p($key, $default = '') {
    return $_GET[$key] ?? $default;
}

// ── Auto-create telegram_id column if missing ─────────────────────────────────
try {
    if ($pdo->query("SHOW COLUMNS FROM users LIKE 'telegram_id'")->rowCount() === 0) {
        $pdo->exec("ALTER TABLE users ADD COLUMN telegram_id BIGINT DEFAULT NULL");
        try { $pdo->exec("ALTER TABLE users ADD INDEX idx_tgid (telegram_id)"); } catch(Exception $e) {}
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'DB error: ' . $e->getMessage()]);
    exit;
}

// ── User helpers ──────────────────────────────────────────────────────────────
function getUser($pdo, $tgid) {
    $s = $pdo->prepare("SELECT * FROM users WHERE telegram_id = ? LIMIT 1");
    $s->execute([$tgid]);
    return $s->fetch(PDO::FETCH_ASSOC);
}

function requireUser($pdo, $tgid) {
    $u = getUser($pdo, $tgid);
    if (!$u) { echo json_encode(['success' => false, 'message' => 'not_linked']); exit; }
    return $u;
}

// ══════════════════════════════════════════════════════════════════════════════
switch ($action) {

case 'is_linked':
    $u = getUser($pdo, $telegram_id);
    echo json_encode(['success' => (bool)$u, 'linked' => (bool)$u, 'name' => $u ? $u['name'] : null]);
    break;

case 'today_summary':
    $u = requireUser($pdo, $telegram_id); $uid = $u['id'];
    $s = $pdo->prepare("SELECT ss.duration_minutes, sub.name AS subject_name, ss.notes
        FROM study_sessions ss JOIN subjects sub ON ss.subject_id=sub.id
        WHERE ss.user_id=? AND ss.date=CURDATE() ORDER BY ss.created_at DESC");
    $s->execute([$uid]); $sessions = $s->fetchAll(PDO::FETCH_ASSOC);
    $total = array_sum(array_column($sessions, 'duration_minutes'));
    $goal  = (int)($u['study_goal_minutes'] ?? 120);
    echo json_encode(['success'=>true,'name'=>$u['name'],'sessions'=>$sessions,
        'total_minutes'=>$total,'goal_minutes'=>$goal,'goal_met'=>$total>=$goal]);
    break;

case 'get_subjects':
    $u = requireUser($pdo, $telegram_id);
    $s = $pdo->prepare("SELECT id, name, color FROM subjects WHERE user_id=? ORDER BY name");
    $s->execute([$u['id']]);
    echo json_encode(['success'=>true,'subjects'=>$s->fetchAll(PDO::FETCH_ASSOC)]);
    break;

case 'log_session':
    $u = requireUser($pdo, $telegram_id); $uid = $u['id'];
    $subName = sanitize(p('subject')); $minutes = (int)p('minutes',0); $notes = sanitize(p('notes'));
    if (!$subName || $minutes<=0) { echo json_encode(['success'=>false,'message'=>'Invalid input']); break; }
    $sq = $pdo->prepare("SELECT id FROM subjects WHERE user_id=? AND LOWER(name)=LOWER(?)");
    $sq->execute([$uid,$subName]); $sub=$sq->fetch();
    if (!$sub) {
        $colors=['#6366f1','#10b981','#f59e0b','#ef4444','#3b82f6','#8b5cf6'];
        $pdo->prepare("INSERT INTO subjects (user_id,name,color) VALUES (?,?,?)")
            ->execute([$uid,$subName,$colors[array_rand($colors)]]);
        $subId=(int)$pdo->lastInsertId();
    } else $subId=(int)$sub['id'];
    $date=date('Y-m-d');
    $pdo->prepare("INSERT INTO study_sessions (user_id,subject_id,date,duration_minutes,notes) VALUES (?,?,?,?,?)")
        ->execute([$uid,$subId,$date,$minutes,$notes]);
    $pdo->prepare("INSERT INTO study_streaks (user_id,date,minutes_studied) VALUES (?,?,?)
        ON DUPLICATE KEY UPDATE minutes_studied=minutes_studied+?")
        ->execute([$uid,$date,$minutes,$minutes]);
    echo json_encode(['success'=>true,'subject'=>$subName,'minutes'=>$minutes]);
    break;

case 'get_recent_sessions':
    $u = requireUser($pdo, $telegram_id);
    $s = $pdo->prepare("SELECT ss.id, ss.duration_minutes, ss.date, ss.notes, sub.name AS subject_name
        FROM study_sessions ss JOIN subjects sub ON ss.subject_id=sub.id
        WHERE ss.user_id=? ORDER BY ss.date DESC, ss.created_at DESC LIMIT 15");
    $s->execute([$u['id']]);
    echo json_encode(['success'=>true,'sessions'=>$s->fetchAll(PDO::FETCH_ASSOC)]);
    break;

case 'delete_session':
    $u = requireUser($pdo, $telegram_id);
    $pdo->prepare("DELETE FROM study_sessions WHERE id=? AND user_id=?")
        ->execute([(int)p('session_id',0), $u['id']]);
    echo json_encode(['success'=>true]);
    break;

case 'get_tasks':
    $u = requireUser($pdo, $telegram_id);
    $filter = p('filter','pending');
    $where  = match($filter) {
        'today' => "AND t.due_date=CURDATE() AND t.status!='completed'",
        'all'   => "AND t.status!='completed'",
        default => "AND t.status='pending'",
    };
    $s = $pdo->prepare("SELECT t.*, sub.name AS subject_name FROM tasks t
        LEFT JOIN subjects sub ON t.subject_id=sub.id WHERE t.user_id=? $where
        ORDER BY FIELD(t.priority,'high','medium','low'), t.due_date ASC LIMIT 10");
    $s->execute([$u['id']]);
    echo json_encode(['success'=>true,'tasks'=>$s->fetchAll(PDO::FETCH_ASSOC)]);
    break;

case 'add_task':
    $u = requireUser($pdo, $telegram_id);
    $title    = sanitize(p('title'));
    $priority = in_array(p('priority'),['high','medium','low']) ? p('priority') : 'medium';
    $due      = p('due_date') ?: null;
    if (!$title) { echo json_encode(['success'=>false,'message'=>'No title']); break; }
    $pdo->prepare("INSERT INTO tasks (user_id,title,priority,due_date) VALUES (?,?,?,?)")
        ->execute([$u['id'],$title,$priority,$due]);
    echo json_encode(['success'=>true,'task'=>$title]);
    break;

case 'complete_task':
    $u = requireUser($pdo, $telegram_id);
    $pdo->prepare("UPDATE tasks SET status='completed',updated_at=NOW() WHERE id=? AND user_id=?")
        ->execute([(int)p('task_id',0), $u['id']]);
    echo json_encode(['success'=>true]);
    break;

case 'delete_task':
    $u = requireUser($pdo, $telegram_id);
    $pdo->prepare("DELETE FROM tasks WHERE id=? AND user_id=?")->execute([(int)p('task_id',0), $u['id']]);
    echo json_encode(['success'=>true]);
    break;

case 'get_marks':
    $u = requireUser($pdo, $telegram_id);
    $s = $pdo->prepare("SELECT m.*, sub.name AS subject_name FROM marks m
        JOIN subjects sub ON m.subject_id=sub.id WHERE m.user_id=?
        ORDER BY m.exam_date DESC LIMIT 15");
    $s->execute([$u['id']]);
    echo json_encode(['success'=>true,'marks'=>$s->fetchAll(PDO::FETCH_ASSOC)]);
    break;

case 'add_mark':
    $u = requireUser($pdo, $telegram_id); $uid=$u['id'];
    $subId=(int)p('subject_id',0); $exam=sanitize(p('exam_name'));
    $obtained=(float)p('marks_obtained',-1); $total=(float)p('total_marks',0);
    $date=p('exam_date',date('Y-m-d')); $notes=sanitize(p('notes'));
    $chk=$pdo->prepare("SELECT id FROM subjects WHERE id=? AND user_id=?");
    $chk->execute([$subId,$uid]);
    if (!$chk->fetch()) { echo json_encode(['success'=>false,'message'=>'Invalid subject']); break; }
    if (!$exam||$obtained<0||$total<=0||$obtained>$total) {
        echo json_encode(['success'=>false,'message'=>'Invalid input']); break; }
    $pdo->prepare("INSERT INTO marks (user_id,subject_id,exam_name,marks_obtained,total_marks,exam_date,notes) VALUES (?,?,?,?,?,?,?)")
        ->execute([$uid,$subId,$exam,$obtained,$total,$date,$notes]);
    echo json_encode(['success'=>true]);
    break;

case 'delete_mark':
    $u = requireUser($pdo, $telegram_id);
    $pdo->prepare("DELETE FROM marks WHERE id=? AND user_id=?")->execute([(int)p('mark_id',0), $u['id']]);
    echo json_encode(['success'=>true]);
    break;

case 'get_goals':
    $u = requireUser($pdo, $telegram_id);
    $s = $pdo->prepare("SELECT g.*, sub.name AS subject_name FROM goals g
        LEFT JOIN subjects sub ON g.subject_id=sub.id WHERE g.user_id=?
        ORDER BY g.status ASC, g.created_at DESC");
    $s->execute([$u['id']]);
    echo json_encode(['success'=>true,'goals'=>$s->fetchAll(PDO::FETCH_ASSOC)]);
    break;

case 'add_goal':
    $u = requireUser($pdo, $telegram_id);
    $title=(string)sanitize(p('title')); $target=(float)p('target_value',0); $unit=sanitize(p('unit'));
    if (!$title||$target<=0) { echo json_encode(['success'=>false,'message'=>'Invalid input']); break; }
    $pdo->prepare("INSERT INTO goals (user_id,title,type,target_value,unit) VALUES (?,?,?,?,?)")
        ->execute([$u['id'],$title,'custom',$target,$unit]);
    echo json_encode(['success'=>true]);
    break;

case 'get_notifications':
    $u = requireUser($pdo, $telegram_id);
    $s = $pdo->prepare("SELECT * FROM notifications WHERE user_id=? OR user_id IS NULL
        ORDER BY is_read ASC, created_at DESC LIMIT 15");
    $s->execute([$u['id']]);
    echo json_encode(['success'=>true,'notifications'=>$s->fetchAll(PDO::FETCH_ASSOC)]);
    break;

case 'read_all_notifications':
    $u = requireUser($pdo, $telegram_id);
    $pdo->prepare("UPDATE notifications SET is_read=1 WHERE user_id=? OR user_id IS NULL")->execute([$u['id']]);
    echo json_encode(['success'=>true]);
    break;

case 'get_profile':
    $u = requireUser($pdo, $telegram_id); $uid=$u['id'];
    $sq=$pdo->prepare("SELECT COUNT(*),COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE user_id=?");
    $sq->execute([$uid]); [$ts,$tm]=$sq->fetch(PDO::FETCH_NUM);
    $ach=0;
    try {
        $aq=$pdo->prepare("SELECT COUNT(*) FROM user_achievements WHERE user_id=?");
        $aq->execute([$uid]); $ach=(int)$aq->fetchColumn();
    } catch(Exception $e){}
    echo json_encode(['success'=>true,'profile'=>[
        'name'=>$u['name'],'email'=>$u['email'],'is_verified'=>(bool)$u['is_verified'],
        'study_goal_minutes'=>(int)($u['study_goal_minutes']??120),'created_at'=>$u['created_at'],
        'total_sessions'=>(int)$ts,'total_mins'=>(int)$tm,'achievements'=>$ach,
    ]]);
    break;

case 'update_name':
    $u = requireUser($pdo, $telegram_id); $name=sanitize(p('name'));
    if (strlen($name)<2||strlen($name)>100) { echo json_encode(['success'=>false,'message'=>'Name must be 2-100 chars']); break; }
    $pdo->prepare("UPDATE users SET name=? WHERE id=?")->execute([$name,$u['id']]);
    echo json_encode(['success'=>true,'name'=>$name]);
    break;

case 'update_goal':
    $u = requireUser($pdo, $telegram_id); $goal=(int)p('goal_minutes',0);
    if ($goal<15||$goal>600) { echo json_encode(['success'=>false,'message'=>'Goal must be 15-600']); break; }
    $pdo->prepare("UPDATE users SET study_goal_minutes=? WHERE id=?")->execute([$goal,$u['id']]);
    echo json_encode(['success'=>true,'goal_minutes'=>$goal]);
    break;

case 'weekly_stats':
    $u = requireUser($pdo, $telegram_id); $uid=$u['id'];
    $s=$pdo->prepare("SELECT sub.name, SUM(ss.duration_minutes) AS total_mins, COUNT(*) AS sessions
        FROM study_sessions ss JOIN subjects sub ON ss.subject_id=sub.id
        WHERE ss.user_id=? AND ss.date>=DATE_SUB(CURDATE(),INTERVAL 7 DAY)
        GROUP BY sub.id ORDER BY total_mins DESC");
    $s->execute([$uid]); $by=$s->fetchAll(PDO::FETCH_ASSOC);
    $dk=$pdo->prepare("SELECT COUNT(*) FROM study_streaks WHERE user_id=?
        AND date>=DATE_SUB(CURDATE(),INTERVAL 7 DAY) AND minutes_studied>0");
    $dk->execute([$uid]);
    echo json_encode(['success'=>true,
        'total_minutes'=>(int)array_sum(array_column($by,'total_mins')),
        'by_subject'=>$by,'days_studied'=>(int)$dk->fetchColumn()]);
    break;

case 'get_streak':
    $u = requireUser($pdo, $telegram_id);
    $s=$pdo->prepare("SELECT date FROM study_streaks WHERE user_id=? AND minutes_studied>0 ORDER BY date DESC");
    $s->execute([$u['id']]); $dates=$s->fetchAll(PDO::FETCH_COLUMN);
    $streak=0; $check=new DateTime();
    foreach($dates as $d){
        if((new DateTime($d))->format('Y-m-d')===$check->format('Y-m-d')){$streak++;$check->modify('-1 day');}
        else break;
    }
    echo json_encode(['success'=>true,'streak'=>$streak,'name'=>$u['name']]);
    break;


case 'get_leaderboard':
    $u    = requireUser($pdo, $telegram_id);
    $uid  = $u['id'];
    $period = p('period', 'weekly');

    if ($period === 'daily') {
        $whereDate = "AND date = CURDATE()";
    } elseif ($period === 'monthly') {
        $whereDate = "AND date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
    } else {
        $whereDate = "AND date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
    }

    // Friends
    $fs = $pdo->prepare("
        SELECT u.id, u.name,
               COALESCE((SELECT SUM(duration_minutes) FROM study_sessions WHERE user_id=u.id $whereDate),0) AS period_mins,
               COALESCE((SELECT COUNT(*) FROM user_achievements WHERE user_id=u.id),0) AS badges
        FROM users u
        JOIN friend_requests fr ON (fr.sender_id=u.id OR fr.receiver_id=u.id)
        WHERE fr.status='accepted'
          AND ((fr.sender_id=? AND fr.receiver_id=u.id) OR (fr.receiver_id=? AND fr.sender_id=u.id))
    ");
    $fs->execute([$uid,$uid]);
    $friends = $fs->fetchAll(PDO::FETCH_ASSOC);

    // My stats
    $ms = $pdo->prepare("
        SELECT
            COALESCE((SELECT SUM(duration_minutes) FROM study_sessions WHERE user_id=? $whereDate),0) AS period_mins,
            COALESCE((SELECT COUNT(*) FROM user_achievements WHERE user_id=?),0) AS badges
    ");
    $ms->execute([$uid,$uid]);
    $my = $ms->fetch(PDO::FETCH_ASSOC);

    $board = [['id'=>$uid,'name'=>$u['name'].' ⭐','period_mins'=>(int)$my['period_mins'],'badges'=>(int)$my['badges'],'is_me'=>true]];
    foreach ($friends as $f) {
        $board[] = ['id'=>(int)$f['id'],'name'=>$f['name'],'period_mins'=>(int)$f['period_mins'],'badges'=>(int)$f['badges'],'is_me'=>false];
    }
    usort($board, fn($a,$b)=>$b['period_mins']-$a['period_mins']);

    // Rank of me
    $my_rank = 1;
    foreach ($board as $i => $row) { if ($row['is_me']) { $my_rank = $i+1; break; } }

    echo json_encode(['success'=>true,'board'=>$board,'period'=>$period,'my_rank'=>$my_rank,'total'=>count($board)]);
    break;

default:
    echo json_encode(['success'=>false,'message'=>"Unknown action: $action"]);
}