<?php
// auto_route_engine.php
// RS Learning Lab – Momentum-based Auto Routing Engine
// Decides next learning track automatically

session_start();

/* ===============================
   DB CONFIG
================================ */

require_once "db_config.php";


/* ===============================
   INPUT
================================ */
$roll_no   = $_GET['roll'] ?? $_SESSION['roll'] ?? null;
$name      = $_GET['name'] ?? $_SESSION['name'] ?? null;
$concept_id = $_GET['concept'] ?? 1;

if (!$roll_no || !$name) {
    die("Student context missing");
}

$_SESSION['roll'] = $roll_no;
$_SESSION['name'] = $name;

/* ===============================
   FETCH MOMENTUM
================================ */
$stmt = $pdo->prepare("
    SELECT momentum_state
    FROM learning_momentum
    WHERE roll_no = :roll
    LIMIT 1
");
$stmt->execute([':roll' => $roll_no]);
$data = $stmt->fetch();

$momentum_state = $data['momentum_state'] ?? "Building";

/* ===============================
   ROUTING RULE ENGINE
================================ */
switch ($momentum_state) {

    case "Applying":
        $next_track = "final_track.php";
        $reason = "You are ready to apply what you’ve learned calmly.";
        break;

    case "Stabilizing":
        $next_track = "reinforcement_track.php";
        $reason = "Let’s stabilize your understanding before final application.";
        break;

    case "Reset":
    case "Building":
    default:
        $next_track = "practice_track.php";
        $reason = "Practice builds confidence. Let’s continue calmly.";
        break;
}

/* ===============================
   AUTO REDIRECT
================================ */
header("Location: $next_track?roll=" . urlencode($roll_no) .
       "&name=" . urlencode($name) .
       "&concept=" . urlencode($concept_id));
exit;
