<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

session_start();
$pdo = require_once __DIR__ . '/../../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];

function response($data, $status = 200) {
    http_response_code($status);
    echo json_encode($data);
    exit;
}

function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true);
}

function checkAuth() {
    if (empty($_SESSION['user_id'])) {
        response(['error' => 'Unauthorized'], 401);
    }
    return $_SESSION['user_id'];
}

if ($method === 'GET') {
    $userId = checkAuth();
    
    // Date range
    $period = $_GET['period'] ?? 'week'; // week, month, year
    
    if ($period === 'week') {
        $dateFrom = date('Y-m-d', strtotime('-7 days'));
    } elseif ($period === 'month') {
        $dateFrom = date('Y-m-d', strtotime('-30 days'));
    } else {
        $dateFrom = date('Y-m-d', strtotime('-365 days'));
    }
    
    // Day of week analysis
    $stmt = $pdo->prepare("
        SELECT 
            DAYNAME(start_time) as day_name,
            DAYOFWEEK(start_time) as day_num,
            SUM(duration) as total_duration,
            COUNT(*) as session_count
        FROM study_sessions
        WHERE user_id = ? AND start_time >= ?
        GROUP BY DAYNAME(start_time), DAYOFWEEK(start_time)
        ORDER BY day_num
    ");
    $stmt->execute([$userId, $dateFrom]);
    $dayAnalysis = $stmt->fetchAll();
    
    // Subject analysis
    $stmt = $pdo->prepare("
        SELECT 
            subject,
            SUM(duration) as total_duration,
            COUNT(*) as session_count,
            ROUND((SUM(duration) / (SELECT SUM(duration) FROM study_sessions WHERE user_id = ? AND start_time >= ?)) * 100, 1) as percentage
        FROM study_sessions
        WHERE user_id = ? AND start_time >= ?
        GROUP BY subject
        ORDER BY total_duration DESC
    ");
    $stmt->execute([$userId, $dateFrom, $userId, $dateFrom]);
    $subjectAnalysis = $stmt->fetchAll();
    
    // Time zone analysis (hourly)
    $stmt = $pdo->prepare("
        SELECT 
            HOUR(start_time) as hour,
            SUM(duration) as total_duration,
            COUNT(*) as session_count
        FROM study_sessions
        WHERE user_id = ? AND start_time >= ?
        GROUP BY HOUR(start_time)
        ORDER BY hour
    ");
    $stmt->execute([$userId, $dateFrom]);
    $timeZoneAnalysis = $stmt->fetchAll();
    
    response([
        'dayAnalysis' => $dayAnalysis,
        'subjectAnalysis' => $subjectAnalysis,
        'timeZoneAnalysis' => $timeZoneAnalysis
    ]);
}

else {
    response(['error' => 'Method not allowed'], 405);
}
?>
