<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/teacher-auth.php';
require_once __DIR__ . '/../includes/teacher-course-context.php';
require_once __DIR__ . '/../includes/grade-engine.php';

$pdo = db();
requireTeacher();
$teacher = currentTeacher($pdo);
if (!$teacher) {
    teacherLogout();
    redirect('teacher/login.php');
}

$courses = getTeacherCourses($pdo, (int)$teacher['id']);
$courseId = (int)($_GET['course_id'] ?? $_POST['course_id'] ?? ($courses[0]['id'] ?? 0));
$course = $courseId > 0 && teacherOwnsCourse($pdo, (int)$teacher['id'], $courseId)
    ? safeFetch($pdo, 'SELECT * FROM core_courses WHERE id=? LIMIT 1', [$courseId])
    : null;
$error = '';
$success = flash('success') ?: '';

if (isPost()) {
    requireCsrf();
    $studentId = (int)($_POST['student_id'] ?? 0);
    $stars = (int)($_POST['stars'] ?? -1);
    $points = (float)($_POST['points'] ?? $stars);
    $note = trim((string)($_POST['note'] ?? $_POST['notes'] ?? ''));
    $date = trim((string)($_POST['participation_date'] ?? today()));
    if (!$course || $studentId <= 0 || $stars < 0 || $stars > 5 || $points < 0 || $points > 100 || !teacherCanAccessStudentCourse($pdo, (int)$teacher['id'], $studentId, $courseId)) {
        $error = 'Invalid student, course, or participation score.';
    } elseif (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        $error = 'Invalid participation date.';
    } else {
        try {
            $pdo->beginTransaction();
            $existing = safeFetch($pdo,
                'SELECT id FROM core_participation WHERE course_id=? AND student_id=? AND DATE(created_at)=? ORDER BY id DESC LIMIT 1',
                [$courseId, $studentId, $date]
            );
            if ($existing) {
                $stmt = $pdo->prepare('UPDATE core_participation SET stars=?, points=?, note=?, marked_by=? WHERE id=?');
                $stmt->execute([$stars, $points, $note !== '' ? $note : null, (int)$teacher['id'], (int)$existing['id']]);
                $recordId = (int)$existing['id'];
            } else {
                $stmt = $pdo->prepare('INSERT INTO core_participation (course_id,core_session_id,student_id,stars,points,note,marked_by,created_at) VALUES (?,NULL,?,?,?,?,?,?)');
                $stmt->execute([$courseId, $studentId, $stars, $points, $note !== '' ? $note : null, (int)$teacher['id'], $date . ' ' . date('H:i:s')]);
                $recordId = (int)$pdo->lastInsertId();
            }
            saveStudentGrade(
                $pdo,
                $studentId,
                $courseId,
                'participation',
                $recordId,
                'Participation — ' . $date,
                (float)$stars,
                5.0,
                0.0,
                $note !== '' ? $note : null,
                (int)$teacher['id'],
                null
            );
            $pdo->commit();
            logActivity($pdo, 'teacher', (int)$teacher['id'], 'Participation saved', "Student {$studentId}; course {$courseId}; stars {$stars}.");
            flash('success', 'Participation was saved and the student grade was recalculated.');
            redirect('teacher/participation.php?course_id=' . $courseId);
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            error_log('[SMI participation] ' . $e->getMessage());
            $error = APP_DEBUG ? $e->getMessage() : 'Participation could not be saved.';
        }
    }
}

$students = $course ? safeFetchAll($pdo,
    "SELECT s.id,s.full_name,s.student_code,s.final_level,
            p.stars AS today_stars,p.points AS today_points,p.note AS today_note
     FROM core_course_students cs
     INNER JOIN students s ON s.id=cs.student_id
     LEFT JOIN core_participation p ON p.id=(SELECT p2.id FROM core_participation p2 WHERE p2.course_id=cs.course_id AND p2.student_id=cs.student_id AND DATE(p2.created_at)=CURDATE() ORDER BY p2.id DESC LIMIT 1)
     WHERE cs.course_id=? AND cs.status IN ('active','completed')
     ORDER BY s.full_name",
    [$courseId]
) : [];
?>
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Participation · SMI</title>
<style>
:root{font-family:Inter,Arial,sans-serif;color:#0f172a;background:#f3f6fb}*{box-sizing:border-box}body{margin:0}.page{max-width:1400px;margin:auto;padding:32px}.top,.toolbar{display:flex;justify-content:space-between;align-items:center;gap:16px}.top h1{font-size:44px;margin:0}.top p{color:#64748b}.btn{display:inline-flex;border:0;border-radius:14px;padding:12px 16px;background:#2563eb;color:white;text-decoration:none;font-weight:800;cursor:pointer}.hero{margin:24px 0;background:linear-gradient(135deg,#f59e0b,#d97706);color:white;padding:30px;border-radius:28px}.toolbar{background:white;padding:18px;border-radius:22px;margin-bottom:20px;box-shadow:0 14px 40px rgba(15,23,42,.06)}select,input,textarea{border:1px solid #dbe3ef;border-radius:12px;padding:11px;font:inherit}.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(315px,1fr));gap:18px}.card{background:white;padding:20px;border-radius:24px;box-shadow:0 14px 40px rgba(15,23,42,.06)}.meta{color:#64748b;font-size:13px}.stars{display:flex;gap:5px;margin:12px 0}.stars label{cursor:pointer}.stars input{position:absolute;opacity:0}.stars span{font-size:28px;filter:grayscale(1);opacity:.45}.stars input:checked~span{filter:none;opacity:1}.stars label:has(input:checked) span{filter:none;opacity:1}.row{display:grid;grid-template-columns:1fr 110px;gap:8px}.card textarea{width:100%;min-height:70px;margin:9px 0}.alert{padding:14px 18px;border-radius:14px;margin:18px 0;font-weight:750}.ok{background:#dcfce7;color:#166534}.bad{background:#fee2e2;color:#991b1b}.today{font-size:12px;background:#fff7ed;color:#9a3412;padding:6px 9px;border-radius:999px}.empty{background:white;border-radius:24px;padding:42px;text-align:center;color:#64748b}@media(max-width:700px){.page{padding:18px}.top,.toolbar{align-items:flex-start;flex-direction:column}.top h1{font-size:34px}}
</style></head><body><main class="page">
<div class="top"><div><h1>Participation</h1><p>Record daily participation and synchronize it with the official course grade.</p></div><a class="btn" href="dashboard.php">Dashboard</a></div>
<section class="hero"><h2><?=e($course['title'] ?? 'Select a course')?></h2><p>One record per student per day. Saving again updates today’s record instead of creating duplicates.</p></section>
<?php if($success):?><div class="alert ok"><?=e($success)?></div><?php endif;?><?php if($error):?><div class="alert bad"><?=e($error)?></div><?php endif;?>
<form class="toolbar" method="get"><label>Course <select name="course_id" onchange="this.form.submit()"><?php foreach($courses as $c):?><option value="<?=$c['id']?>" <?=selected($courseId,$c['id'])?>><?=e($c['title'].' — '.$c['course_code'])?></option><?php endforeach;?></select></label><span class="today"><?=e(today())?></span></form>
<?php if($students):?><section class="grid"><?php foreach($students as $s):?><form class="card" method="post">
<?=csrfField()?><input type="hidden" name="course_id" value="<?=$courseId?>"><input type="hidden" name="student_id" value="<?=$s['id']?>"><input type="hidden" name="participation_date" value="<?=e(today())?>">
<h3><?=e($s['full_name'])?></h3><div class="meta"><?=e($s['student_code'])?> · <?=e($s['final_level'] ?: 'Level not set')?></div>
<div class="stars" aria-label="Stars"><?php for($i=1;$i<=5;$i++):?><label><input type="radio" name="stars" value="<?=$i?>" <?=checked((int)($s['today_stars']??0),$i)?> required><span>★</span></label><?php endfor;?></div>
<div class="row"><label>Points<input style="width:100%" type="number" name="points" min="0" max="100" step="0.5" value="<?=e($s['today_points'] ?? $s['today_stars'] ?? 0)?>"></label><div></div></div>
<textarea name="note" placeholder="Teacher note"><?=e($s['today_note'] ?? '')?></textarea><button class="btn" type="submit">Save participation</button>
</form><?php endforeach;?></section><?php else:?><div class="empty">No active students are available for this course.</div><?php endif;?>
</main></body></html>
