<?php

$appName = 'mondialisa';
session_name($appName);
session_start();
require_once 'config.inc.php';

header('Content-Type: application/json');

// 🔐 Sécurité session
$user_ref = $_SESSION['user']['ref'] ?? null;
if (!$user_ref) {
    http_response_code(401);
    echo json_encode(['error' => 'Not authenticated']);
    exit;
}

// 📥 Lecture JSON
$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['lesson_ref'], $data['progress'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid payload']);
    exit;
}

$lesson_ref = $data['lesson_ref'];
$lesson_progress = max(0, min(100, (int)$data['progress']));

try {
    $dbh->beginTransaction();

    // 1️⃣ UPDATE PROGRESS LEÇON
    $stmt = $dbh->prepare("SELECT COUNT(*) FROM mondialisa_formation_user_progress WHERE user_ref=? AND lesson_ref=?");
    $stmt->execute([$user_ref, $lesson_ref]);

    if ($stmt->fetchColumn()) {
        $stmt = $dbh->prepare("UPDATE mondialisa_formation_user_progress SET progress=? WHERE user_ref=? AND lesson_ref=?");
        $stmt->execute([$lesson_progress, $user_ref, $lesson_ref]);
    } else {
        $stmt = $dbh->prepare("INSERT INTO mondialisa_formation_user_progress (user_ref, lesson_ref, progress) VALUES (?,?,?)");
        $stmt->execute([$user_ref, $lesson_ref, $lesson_progress]);
    }

    // 2️⃣ RÉCUPÉRER MODULE & FORMATION
    $stmt = $dbh->prepare("SELECT module_ref FROM mondialisa_formation_lessons WHERE ref=?");
    $stmt->execute([$lesson_ref]);
    $module_ref = $stmt->fetchColumn();

    $formation_ref = null;
    if ($module_ref) {
        $stmt = $dbh->prepare("SELECT formation_ref FROM mondialisa_formation_modules WHERE ref=?");
        $stmt->execute([$module_ref]);
        $formation_ref = $stmt->fetchColumn();
    }

    // 3️⃣ CALCUL PROGRESS MODULE (moyenne des leçons du module)
    $module_progress = 0;
    if ($module_ref) {
        $stmt = $dbh->prepare("
            SELECT COALESCE(up.progress,0) as progress
            FROM mondialisa_formation_lessons l
            LEFT JOIN mondialisa_formation_user_progress up
              ON up.lesson_ref = l.ref AND up.user_ref = ?
            WHERE l.module_ref = ?
        ");
        $stmt->execute([$user_ref, $module_ref]);
        $lessons = $stmt->fetchAll(PDO::FETCH_COLUMN);

        $totalLessons = count($lessons);
        $sumProgress = array_sum($lessons);

        if ($totalLessons > 0) {
            $module_progress = (int) round($sumProgress / $totalLessons);
        }

        // Upsert module progress
        $stmt = $dbh->prepare("SELECT COUNT(*) FROM mondialisa_formation_user_progress WHERE user_ref=? AND module_ref=?");
        $stmt->execute([$user_ref, $module_ref]);
        if ($stmt->fetchColumn()) {
            $stmt = $dbh->prepare("UPDATE mondialisa_formation_user_progress SET progress=? WHERE user_ref=? AND module_ref=?");
            $stmt->execute([$module_progress, $user_ref, $module_ref]);
        } else {
            $stmt = $dbh->prepare("INSERT INTO mondialisa_formation_user_progress (user_ref,module_ref,progress) VALUES (?,?,?)");
            $stmt->execute([$user_ref, $module_ref, $module_progress]);
        }
    }

    // 4️⃣ CALCUL PROGRESS FORMATION (moyenne de toutes les leçons de tous les modules)
    $formation_progress = 0;
    if ($formation_ref) {
        $stmt = $dbh->prepare("
            SELECT COALESCE(up.progress,0) as progress
            FROM mondialisa_formation_lessons l
            LEFT JOIN mondialisa_formation_user_progress up
              ON up.lesson_ref = l.ref AND up.user_ref = ?
            JOIN mondialisa_formation_modules m ON l.module_ref = m.ref
            WHERE m.formation_ref = ?
        ");
        $stmt->execute([$user_ref, $formation_ref]);
        $lessons = $stmt->fetchAll(PDO::FETCH_COLUMN);

        $totalLessons = count($lessons);
        $sumProgress = array_sum($lessons);

        if ($totalLessons > 0) {
            $formation_progress = (int) round($sumProgress / $totalLessons);
        }

        // Upsert formation progress
        $stmt = $dbh->prepare("SELECT COUNT(*) FROM mondialisa_formation_user_progress WHERE user_ref=? AND formation_ref=?");
        $stmt->execute([$user_ref, $formation_ref]);
        if ($stmt->fetchColumn()) {
            $stmt = $dbh->prepare("UPDATE mondialisa_formation_user_progress SET progress=? WHERE user_ref=? AND formation_ref=?");
            $stmt->execute([$formation_progress, $user_ref, $formation_ref]);
        } else {
            $stmt = $dbh->prepare("INSERT INTO mondialisa_formation_user_progress (user_ref,formation_ref,progress) VALUES (?,?,?)");
            $stmt->execute([$user_ref, $formation_ref, $formation_progress]);
        }
    }

    $dbh->commit();

    echo json_encode([
        'success' => true,
        'lesson_progress' => $lesson_progress,
        'module_progress' => $module_progress,
        'formation_progress' => $formation_progress
    ]);

} catch(PDOException $e){
    $dbh->rollBack();
    error_log('learn_update_progress ERROR: '.$e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
}
