<?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'];
}

// Create study session
if ($method === 'POST') {
    $userId = checkAuth();
    $data = getJsonInput();
    
    if (empty($data['subject']) || empty($data['start_time']) || empty($data['end_time'])) {
        response(['error' => 'Missing required fields'], 400);
    }
    
    $startTime = strtotime($data['start_time']);
    $endTime = strtotime($data['end_time']);
    
    if ($startTime >= $endTime) {
        response(['error' => 'End time must be after start time'], 400);
    }
    
    $duration = intval(($endTime - $startTime) / 60); // Convert to minutes
    
    $stmt = $pdo->prepare('
        INSERT INTO study_sessions (user_id, subject, start_time, end_time, duration, memo)
        VALUES (?, ?, FROM_UNIXTIME(?), FROM_UNIXTIME(?), ?, ?)
    ');
    
    $stmt->execute([
        $userId,
        $data['subject'],
        $startTime,
        $endTime,
        $duration,
        $data['memo'] ?? ''
    ]);
    
    response([
        'success' => true,
        'id' => $pdo->lastInsertId(),
        'message' => 'Session recorded'
    ], 201);
}

// Get sessions
elseif ($method === 'GET') {
    $userId = checkAuth();
    
    $dateFrom = $_GET['from'] ?? date('Y-m-d', strtotime('-7 days'));
    $dateTo = $_GET['to'] ?? date('Y-m-d');
    
    $stmt = $pdo->prepare('
        SELECT id, subject, start_time, end_time, duration, memo, created_at
        FROM study_sessions
        WHERE user_id = ? AND DATE(start_time) BETWEEN ? AND ?
        ORDER BY start_time DESC
    ');
    $stmt->execute([$userId, $dateFrom, $dateTo]);
    $sessions = $stmt->fetchAll();
    
    response(['sessions' => $sessions]);
}

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