<?php
require_once(__DIR__ . "/../config/db.php");

$student_id = $_SESSION['student_id'];
$topic_id   = $_GET['topic_id'];
$class      = $_GET['class'];

/* CHECK COMPLETED TRACKS */
$stmt = $pdo->prepare("
    SELECT COUNT(*) as completed_tracks
    FROM student_progress
    WHERE student_id = ?
    AND topic_id = ?
    AND completed = 1
");

$stmt->execute([$student_id, $topic_id]);
$result = $stmt->fetch();

if ($result['completed_tracks'] == 3 && $class >= 11) {

    /* CHECK ALREADY UNLOCKED */
    $check = $pdo->prepare("
        SELECT * FROM project_unlock 
        WHERE student_id=? AND topic_id=?
    ");
    $check->execute([$student_id, $topic_id]);

    if ($check->rowCount() == 0) {

        /* INSERT UNLOCK */
        $insert = $pdo->prepare("
            INSERT INTO project_unlock 
            (student_id, topic_id, class, unlocked)
            VALUES (?, ?, ?, 1)
        ");
        $insert->execute([$student_id, $topic_id, $class]);
    }

    echo "unlocked";
} else {
    echo "locked";
}
?>