<?php
// momentum_engine.php
// RS Learning Lab – Learning Momentum System (Phase-1)
// Unique Behaviour Signal Engine

/* ==================================
   DB CONFIG
================================== */
$db_host = "localhost";
$db_name = "rs_learning_lab";
$db_user = "root";
$db_pass = "";

try {
    $pdo = new PDO(
        "mysql:host=$db_host;dbname=$db_name;charset=utf8mb4",
        $db_user,
        $db_pass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    die("DB connection failed");
}

/* ==================================
   TABLE (RUN ONCE)
==================================
learning_momentum
- id
- roll_no
- momentum_score
- momentum_state
- updated_at
================================== */

/* ==================================
   INPUT (FROM TRACKS)
================================== */
$roll_no = $_POST['roll'] ?? null;
$action  = $_POST['action'] ?? null;
/*
Allowed actions:
practice_retry
practice_complete
reinforcement_complete
final_success
final_fail
*/

if (!$roll_no || !$action) {
    http_response_code(400);
    echo json_encode(["status"=>"error","message"=>"Invalid momentum input"]);
    exit;
}

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

$momentum_score = $data['momentum_score'] ?? 50; // neutral baseline

/* ==================================
   MOMENTUM RULE ENGINE
================================== */
switch ($action) {

    case "practice_retry":
        $momentum_score += 2;
        break;

    case "practice_complete":
        $momentum_score += 5;
        break;

    case "reinforcement_complete":
        $momentum_score += 4;
        break;

    case "final_success":
        $momentum_score += 10;
        break;

    case "final_fail":
        $momentum_score -= 8;
        break;
}

// Clamp score
$momentum_score = max(0, min(100, $momentum_score));

/* ==================================
   MAP SCORE → STATE
================================== */
if ($momentum_score >= 80) {
    $momentum_state = "Applying";
} elseif ($momentum_score >= 60) {
    $momentum_state = "Stabilizing";
} elseif ($momentum_score >= 40) {
    $momentum_state = "Building";
} else {
    $momentum_state = "Reset";
}

/* ==================================
   SAVE / UPDATE
================================== */
if ($data) {
    $stmt = $pdo->prepare("
        UPDATE learning_momentum
        SET momentum_score = :score,
            momentum_state = :state,
            updated_at = NOW()
        WHERE roll_no = :roll
    ");
} else {
    $stmt = $pdo->prepare("
        INSERT INTO learning_momentum
        (roll_no, momentum_score, momentum_state, updated_at)
        VALUES (:roll, :score, :state, NOW())
    ");
}

$stmt->execute([
    ':roll' => $roll_no,
    ':score' => $momentum_score,
    ':state' => $momentum_state
]);

/* ==================================
   OUTPUT
================================== */
echo json_encode([
    "status" => "success",
    "roll_no" => $roll_no,
    "momentum_score" => $momentum_score,
    "momentum_state" => $momentum_state
]);
exit;
