<?php
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

if ($method === 'POST') {
    if (!isset($input['user_id']) || !isset($input['duration'])) {
        jsonResponse(['error' => 'Missing required fields'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("INSERT INTO sessions (user_id, title, description, duration, calories, points_left, points_right, satisfaction, session_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $input['user_id'],
        $input['title'] ?? null,
        $input['description'] ?? null,
        $input['duration'],
        $input['calories'] ?? null,
        $input['points_left'] ?? 0,
        $input['points_right'] ?? 0,
        $input['satisfaction'] ?? null,
        $input['session_date'] ?? date('Y-m-d H:i:s')
    ]);
    
    $sessionId = $pdo->lastInsertId();
    jsonResponse(['success' => true, 'session_id' => $sessionId], 201);
}

if ($method === 'GET') {
    if (!isset($_GET['user_id'])) {
        jsonResponse(['error' => 'User ID required'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT s.*, (SELECT COUNT(*) FROM session_likes WHERE session_id = s.id) as likes_count FROM sessions s WHERE s.user_id = ? ORDER BY s.session_date DESC");
    $stmt->execute([$_GET['user_id']]);
    $sessions = $stmt->fetchAll();
    
    jsonResponse(['success' => true, 'sessions' => $sessions]);
}
?>