<?php
/**
 * StudyTrack Admin Bot API
 * File: /studytrack/api/admin-bot.php
 */

require_once '../includes/config.php';
header('Content-Type: application/json');

$secret = $_POST['secret'] ?? $_GET['secret'] ?? '';
if (!defined('BOT_SECRET') || $secret !== BOT_SECRET) {
    http_response_code(403);
    die(json_encode(['success'=>false,'message'=>'Unauthorized']));
}

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {

    case 'stats':
        echo json_encode(['success'=>true,'stats'=>[
            'total_users'    => (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn(),
            'verified'       => (int)$pdo->query("SELECT COUNT(*) FROM users WHERE is_verified=1")->fetchColumn(),
            'linked'         => (int)$pdo->query("SELECT COUNT(*) FROM users WHERE telegram_id IS NOT NULL")->fetchColumn(),
            'sessions'       => (int)$pdo->query("SELECT COUNT(*) FROM study_sessions")->fetchColumn(),
            'total_mins'     => (int)$pdo->query("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions")->fetchColumn(),
            'tasks'          => (int)$pdo->query("SELECT COUNT(*) FROM tasks WHERE status!='completed'")->fetchColumn(),
            'today_sessions' => (int)$pdo->query("SELECT COUNT(*) FROM study_sessions WHERE date=CURDATE()")->fetchColumn(),
        ]]);
        break;

    case 'users':
        $s = $pdo->query("SELECT id,name,email,is_verified,is_disabled,telegram_id,created_at FROM users ORDER BY created_at DESC LIMIT 50");
        echo json_encode(['success'=>true,'users'=>$s->fetchAll(PDO::FETCH_ASSOC)]);
        break;

    case 'linked_users':
        $s = $pdo->query("SELECT id,name,email,telegram_id FROM users WHERE telegram_id IS NOT NULL ORDER BY name");
        echo json_encode(['success'=>true,'users'=>$s->fetchAll(PDO::FETCH_ASSOC)]);
        break;

    case 'weekly_report':
        echo json_encode(['success'=>true,'report'=>[
            'active_users'    => (int)$pdo->query("SELECT COUNT(DISTINCT user_id) FROM study_sessions WHERE date>=DATE_SUB(CURDATE(),INTERVAL 7 DAY)")->fetchColumn(),
            'sessions'        => (int)$pdo->query("SELECT COUNT(*) FROM study_sessions WHERE date>=DATE_SUB(CURDATE(),INTERVAL 7 DAY)")->fetchColumn(),
            'total_mins'      => (int)$pdo->query("SELECT COALESCE(SUM(duration_minutes),0) FROM study_sessions WHERE date>=DATE_SUB(CURDATE(),INTERVAL 7 DAY)")->fetchColumn(),
            'completed_tasks' => (int)$pdo->query("SELECT COUNT(*) FROM tasks WHERE status='completed' AND updated_at>=DATE_SUB(NOW(),INTERVAL 7 DAY)")->fetchColumn(),
            'new_users'       => (int)$pdo->query("SELECT COUNT(*) FROM users WHERE created_at>=DATE_SUB(NOW(),INTERVAL 7 DAY)")->fetchColumn(),
        ]]);
        break;

    case 'add_announcement':
        $title    = htmlspecialchars($_POST['title']   ?? '', ENT_QUOTES);
        $content  = htmlspecialchars($_POST['content'] ?? '', ENT_QUOTES);
        $priority = in_array($_POST['priority']??'',['low','normal','high']) ? $_POST['priority'] : 'normal';
        if (!$title || !$content) { echo json_encode(['success'=>false,'message'=>'Missing fields']); break; }
        $pdo->prepare("INSERT INTO announcements (title,content,priority,is_active) VALUES (?,?,?,1)")->execute([$title,$content,$priority]);
        echo json_encode(['success'=>true]);
        break;

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