<?php
require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json; charset=utf-8');

if (empty($_SESSION['user_id'])) {
    echo json_encode(['success'=>false,'message'=>'Unauthorized']);
    exit;
}

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

$user_id = (int)$_SESSION['user_id'];
$day_no = max(1, min(30, (int)($input['day_no'] ?? 1)));
$mood = trim($input['mood'] ?? '');
$audio_track = trim($input['audio_track'] ?? '');
$duration_sec = max(0, (int)($input['duration_sec'] ?? 0));
$completed = !empty($input['completed']) ? 1 : 0;

try {
    $stmt = $pdo->prepare("
        INSERT INTO madhab_sessions 
        (user_id, day_no, mood, audio_track, duration_sec, completed)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$user_id, $day_no, $mood, $audio_track, $duration_sec, $completed]);
    echo json_encode(['success'=>true,'message'=>'Session saved']);
} catch (Throwable $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}