<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, 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'];
}

// Get dashboard stats
if ($method === 'GET') {
    $userId = checkAuth();
    
    // Last 7 days
    $stmt = $pdo->prepare("
        SELECT 
            DATE(start_time) as date,
            SUM(duration) as total_duration
        FROM study_sessions
        WHERE user_id = ? AND start_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        GROUP BY DATE(start_time)
        ORDER BY date DESC
    ");
    $stmt->execute([$userId]);
    $last7Days = $stmt->fetchAll();
    
    // Weekly average
    $stmt = $pdo->prepare("
        SELECT 
            COALESCE(SUM(duration), 0) as total_duration,
            COUNT(DISTINCT DATE(start_time)) as days_count
        FROM study_sessions
        WHERE user_id = ? AND start_time >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    ");
    $stmt->execute([$userId]);
    $weeklyStats = $stmt->fetch();
    
    // Monthly stats
    $stmt = $pdo->prepare("
        SELECT 
            DATE_FORMAT(DATE(start_time), '%Y-%m') as month,
            SUM(duration) as total_duration
        FROM study_sessions
        WHERE user_id = ?
        GROUP BY DATE_FORMAT(DATE(start_time), '%Y-%m')
        ORDER BY month DESC
        LIMIT 12
    ");
    $stmt->execute([$userId]);
    $monthlyStats = $stmt->fetchAll();
    
    // Current goals
    $stmt = $pdo->prepare("SELECT weekday_goal, holiday_goal FROM goals WHERE user_id = ?");
    $stmt->execute([$userId]);
    $goals = $stmt->fetch();
    
    // Calculate today's goal
    $dayOfWeek = date('N'); // 1=Monday, 7=Sunday
    $todayGoal = ($dayOfWeek >= 6) ? $goals['holiday_goal'] : $goals['weekday_goal'];
    
    $stmt = $pdo->prepare("
        SELECT COALESCE(SUM(duration), 0) as today_duration
        FROM study_sessions
        WHERE user_id = ? AND DATE(start_time) = CURDATE()
    ");
    $stmt->execute([$userId]);
    $todayStats = $stmt->fetch();
    
    response([
        'last7Days' => $last7Days,
        'weeklyAverage' => round(($weeklyStats['days_count'] > 0) ? $weeklyStats['total_duration'] / $weeklyStats['days_count'] : 0),
        'monthlyStats' => $monthlyStats,
        'todayGoal' => $todayGoal,
        'todayDuration' => $todayStats['today_duration'],
        'todayProgress' => round(($todayGoal > 0) ? ($todayStats['today_duration'] / $todayGoal) * 100 : 0)
    ]);
}

else {
    response(['error' => 'Not found'], 404);
}
?>
