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

$name  = $_SESSION['student_name'] ?? 'Student';
$roll  = $_SESSION['student_id'] ?? 'NA';
$class = $_SESSION['student_class'] ?? '';

$code = $_POST['code'] ?? '';

/* 🔥 TIME TRACKING */
$start_time = $_POST['start_time'] ?? round(microtime(true) * 1000);
$end_time = round(microtime(true) * 1000);
$time_taken = ($end_time - $start_time) / 1000; // seconds

$topic_id = $_POST['topic_id'] ?? 1;

if(strlen(trim($code)) < 20){
    die("❌ Write proper logic (too short)");
}

/* 🔥 SMART CHECK */
$passed = false;
$score = 0;

if($topic_id == 1){
    if(strpos($code, 'if') !== false && strpos($code, 'average') !== false){
        $passed = true;
        $score = 90;
    } else {
        $score = 40;
    }
}

/* 🔥 THINKING TYPE LOGIC */
if($time_taken < 30){
    $thinking_type = "⚡ Quick Thinker";
}
elseif($time_taken > 120){
    $thinking_type = "🧠 Deep Thinker";
}
else{
    $thinking_type = "🚶 Balanced Learner";
}

/* SAVE TO DB */
$status = $passed ? 'approved' : 'rejected';

$stmt = $pdo->prepare("
    INSERT INTO project_submissions
    (student_name, student_id, class, topic_id, score, status, thinking_type)
    VALUES (?,?,?,?,?,?,?)
");

$stmt->execute([$name, $roll, $class, $topic_id, $score, $status, $thinking_type]);

/* RESULT UI */
if($passed){
    echo "
    <div style='text-align:center;margin-top:100px'>
        <h2 style='color:#22c55e'>✅ Project Approved 🎉</h2>

        <h3 style='color:#facc15'>$thinking_type</h3>

        <p style='color:#94a3b8'>
        You solved this in ".round($time_taken)." seconds
        </p>

        <a href='/rs_lab/student/leaderboard.php'
        style='display:inline-block;margin-top:20px;padding:12px 30px;
        background:#facc15;color:#020617;border-radius:999px;
        text-decoration:none;font-weight:bold'>
        🏆 View Leaderboard
        </a>
    </div>
    ";
}else{
    echo "
    <div style='text-align:center;margin-top:100px'>
        <h2 style='color:#f87171'>❌ Improve your logic</h2>

        <h3 style='color:#38bdf8'>$thinking_type</h3>

        <p style='color:#94a3b8'>
        Try again. You spent ".round($time_taken)." seconds
        </p>
    </div>
    ";
}
?>