<?php
/**
 * StudyTrack Telegram Bot API Bridge
 * File: /studytrack/api/telegram-bot.php
 * 
 * මෙය StudyTrack website එකේ api/ folder එකට add කරන්න.
 * Telegram Bot commands handle කරන PHP API file.
 */

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

// Bot Token verify කරන්නෙ header via X-Bot-Secret
$secret = $_SERVER['HTTP_X_BOT_SECRET'] ?? '';
if ($secret !== BOT_SECRET) {
    http_response_code(403);
    die('Unauthorized');
}

header('Content-Type: application/json');

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$telegram_id = (int)($_POST['telegram_id'] ?? 0);

// ── User lookup by Telegram ID ────────────────────────────
function getUserByTelegramId($pdo, $telegram_id) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE telegram_id = ?");
    $stmt->execute([$telegram_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// ── Handlers ──────────────────────────────────────────────

switch ($action) {

    // Link කරන්න: /link <user_id> 
    case 'link_account':
        $user_id = (int)($_POST['user_id'] ?? 0);
        $stmt = $pdo->prepare("UPDATE users SET telegram_id = ? WHERE id = ?");
        $stmt->execute([$telegram_id, $user_id]);
        echo json_encode(['success' => true, 'message' => 'Account linked!']);
        break;

    // Today's study summary
    case 'today_summary':
        $user = getUserByTelegramId($pdo, $telegram_id);
        if (!$user) { echo json_encode(['success' => false, 'message' => 'not_linked']); break; }
        
        $stmt = $pdo->prepare("
            SELECT ss.duration_minutes, s.name as subject_name, ss.notes
            FROM study_sessions ss
            JOIN subjects s ON ss.subject_id = s.id
            WHERE ss.user_id = ? AND ss.date = CURDATE()
            ORDER BY ss.created_at DESC
        ");
        $stmt->execute([$user['id']]);
        $sessions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $total_mins = array_sum(array_column($sessions, 'duration_minutes'));
        $goal_mins = $user['study_goal_minutes'] ?? 120;
        
        echo json_encode([
            'success' => true,
            'name' => $user['name'],
            'sessions' => $sessions,
            'total_minutes' => $total_mins,
            'goal_minutes' => $goal_mins,
            'goal_met' => $total_mins >= $goal_mins
        ]);
        break;

    // Log a study session
    case 'log_session':
        $user = getUserByTelegramId($pdo, $telegram_id);
        if (!$user) { echo json_encode(['success' => false, 'message' => 'not_linked']); break; }
        
        $subject_name = sanitize($_POST['subject'] ?? '');
        $minutes = (int)($_POST['minutes'] ?? 0);
        $notes = sanitize($_POST['notes'] ?? '');
        
        // Subject find or create
        $stmt = $pdo->prepare("SELECT id FROM subjects WHERE user_id = ? AND LOWER(name) = LOWER(?)");
        $stmt->execute([$user['id'], $subject_name]);
        $subject = $stmt->fetch();
        
        if (!$subject) {
            $colors = ['#6366f1','#10b981','#f59e0b','#ef4444','#3b82f6','#8b5cf6'];
            $color = $colors[array_rand($colors)];
            $pdo->prepare("INSERT INTO subjects (user_id, name, color) VALUES (?, ?, ?)")
                ->execute([$user['id'], $subject_name, $color]);
            $subject_id = $pdo->lastInsertId();
        } else {
            $subject_id = $subject['id'];
        }
        
        $date = date('Y-m-d');
        $pdo->prepare("INSERT INTO study_sessions (user_id, subject_id, date, duration_minutes, notes) VALUES (?,?,?,?,?)")
            ->execute([$user['id'], $subject_id, $date, $minutes, $notes]);
        
        $pdo->prepare("INSERT INTO study_streaks (user_id, date, minutes_studied) VALUES (?,?,?)
                       ON DUPLICATE KEY UPDATE minutes_studied = minutes_studied + ?")
            ->execute([$user['id'], $date, $minutes, $minutes]);
        
        echo json_encode(['success' => true, 'subject' => $subject_name, 'minutes' => $minutes]);
        break;

    // Get tasks
    case 'get_tasks':
        $user = getUserByTelegramId($pdo, $telegram_id);
        if (!$user) { echo json_encode(['success' => false, 'message' => 'not_linked']); break; }
        
        $filter = $_POST['filter'] ?? 'pending'; // pending | today | all
        $where = match($filter) {
            'today' => "AND (t.due_date = CURDATE() OR t.due_date IS NULL) AND t.status != 'completed'",
            'all' => "AND t.status != 'completed'",
            default => "AND t.status = 'pending'"
        };
        
        $stmt = $pdo->prepare("
            SELECT t.*, s.name as subject_name
            FROM tasks t LEFT JOIN subjects s ON t.subject_id = s.id
            WHERE t.user_id = ? $where
            ORDER BY t.priority DESC, t.due_date ASC
            LIMIT 10
        ");
        $stmt->execute([$user['id']]);
        echo json_encode(['success' => true, 'tasks' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        break;

    // Add task
    case 'add_task':
        $user = getUserByTelegramId($pdo, $telegram_id);
        if (!$user) { echo json_encode(['success' => false, 'message' => 'not_linked']); break; }
        
        $title = sanitize($_POST['title'] ?? '');
        $priority = $_POST['priority'] ?? 'medium';
        $due_date = $_POST['due_date'] ?? null;
        
        $pdo->prepare("INSERT INTO tasks (user_id, title, priority, due_date) VALUES (?,?,?,?)")
            ->execute([$user['id'], $title, $priority, $due_date]);
        
        echo json_encode(['success' => true, 'task' => $title]);
        break;

    // Weekly stats
    case 'weekly_stats':
        $user = getUserByTelegramId($pdo, $telegram_id);
        if (!$user) { echo json_encode(['success' => false, 'message' => 'not_linked']); break; }
        
        $stmt = $pdo->prepare("
            SELECT s.name, SUM(ss.duration_minutes) as total_mins, COUNT(*) as sessions
            FROM study_sessions ss
            JOIN subjects s ON ss.subject_id = s.id
            WHERE ss.user_id = ? AND ss.date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
            GROUP BY s.id ORDER BY total_mins DESC
        ");
        $stmt->execute([$user['id']]);
        $by_subject = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $total = array_sum(array_column($by_subject, 'total_mins'));
        
        // Streak
        $streak_stmt = $pdo->prepare("
            SELECT COUNT(*) as streak FROM study_streaks
            WHERE user_id = ? AND date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
              AND minutes_studied > 0
        ");
        $streak_stmt->execute([$user['id']]);
        $streak = $streak_stmt->fetchColumn();
        
        echo json_encode([
            'success' => true,
            'total_minutes' => $total,
            'by_subject' => $by_subject,
            'days_studied' => $streak
        ]);
        break;

    // Upcoming marks / exams
    case 'get_marks':
        $user = getUserByTelegramId($pdo, $telegram_id);
        if (!$user) { echo json_encode(['success' => false, 'message' => 'not_linked']); break; }
        
        $stmt = $pdo->prepare("
            SELECT m.*, s.name as subject_name
            FROM marks m JOIN subjects s ON m.subject_id = s.id
            WHERE m.user_id = ?
            ORDER BY m.exam_date DESC LIMIT 10
        ");
        $stmt->execute([$user['id']]);
        echo json_encode(['success' => true, 'marks' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        break;

    // Get streak info
    case 'get_streak':
        $user = getUserByTelegramId($pdo, $telegram_id);
        if (!$user) { echo json_encode(['success' => false, 'message' => 'not_linked']); break; }
        
        // Calculate current streak
        $stmt = $pdo->prepare("
            SELECT date FROM study_streaks
            WHERE user_id = ? AND minutes_studied > 0
            ORDER BY date DESC
        ");
        $stmt->execute([$user['id']]);
        $dates = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        $streak = 0;
        $check = new DateTime();
        foreach ($dates as $d) {
            $dt = new DateTime($d);
            if ($dt->format('Y-m-d') === $check->format('Y-m-d')) {
                $streak++;
                $check->modify('-1 day');
            } else break;
        }
        
        echo json_encode(['success' => true, 'streak' => $streak, 'name' => $user['name']]);
        break;

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