<?php
require_once '../config/database.php';
require_once '../includes/auth_check.php';
require_once '../includes/functions.php';

header('Content-Type: text/html; charset=utf-8');

checkRole(['super_admin','school_admin','teacher']);
requirePermission('grades', 'view');

$schoolFilter  = currentSchoolId();
$trimestre     = (int)($_GET['trimestre']     ?? $_POST['trimestre']     ?? getActivePeriod());
$academic_year = trim($_GET['academic_year']  ?? $_POST['academic_year'] ?? getDefaultAcademicYear($pdo, currentSchoolId()));
$class_id      = (int)($_GET['class_id']      ?? $_POST['class_id']     ?? 0);
$subject_id    = (int)($_GET['subject_id']    ?? $_POST['subject_id']   ?? 0);
$error = $success = '';

// Session persistence
if (isset($_GET['set_session'])) {
    if (isset($_GET['trimestre'])) setActivePeriod((int)$_GET['trimestre']);
    if (isset($_GET['academic_year'])) $_SESSION['active_academic_year'] = $_GET['academic_year'] ?: null;
    if (isset($_GET['school_id'])) $_SESSION['active_school_filter'] = (int)$_GET['school_id'] ?: null;
    header('Location: grade_entry.php?class_id=' . $class_id . '&subject_id=' . $subject_id);
    exit;
}
$sessionYear   = $_SESSION['active_academic_year'] ?? $academic_year;
$sessionPeriod = getActivePeriod();
$sessionSchool = $_SESSION['active_school_filter'] ?? $schoolFilter;

if (!in_array($trimestre,[1,2,3])) $trimestre = 1;

// ── Bascule verrouillage période ──
if (isset($_GET['toggle_lock']) && $class_id && hasRole(['super_admin','school_admin'])) {
    verifyCsrf();
    $schoolId = $schoolFilter;
    if (!$schoolId) { $sc = $pdo->prepare("SELECT school_id FROM students WHERE class_id=? LIMIT 1"); $sc->execute([$class_id]); $schoolId = (int)$sc->fetchColumn(); }
    $newState = (int)$_GET['toggle_lock'];
    $pdo->prepare("UPDATE grading_periods SET is_open=?, updated_at=NOW() WHERE school_id=? AND academic_year=? AND period_type='trimestre' AND period_number=?")
        ->execute([$newState, $schoolId, $academic_year, $trimestre]);
    flashMessage('success', $newState ? 'Période débloquée.' : 'Période bloquée.');
    header('Location: grade_entry.php?class_id=' . $class_id . '&subject_id=' . $subject_id . '&trimestre=' . $trimestre . '&academic_year=' . urlencode($academic_year));
    exit;
}
if (isset($_GET['create_period']) && $class_id && hasRole(['super_admin','school_admin'])) {
    verifyCsrf();
    $schoolId = $schoolFilter;
    if (!$schoolId) { $sc = $pdo->prepare("SELECT school_id FROM students WHERE class_id=? LIMIT 1"); $sc->execute([$class_id]); $schoolId = (int)$sc->fetchColumn(); }
    $labels = [1 => '1er Trimestre', 2 => '2ème Trimestre', 3 => '3ème Trimestre'];
    $label = $labels[$trimestre] ?? "$trimestre" . 'e Trimestre';
    $start = date('Y-m-d', strtotime('-1 month'));
    $end   = date('Y-m-d', strtotime('+2 months'));
    $pdo->prepare("INSERT IGNORE INTO grading_periods (school_id,academic_year,period_type,period_number,label,start_date,end_date,is_open) VALUES(?,?,?,?,?,?,?,1)")
        ->execute([$schoolId, $academic_year, 'trimestre', $trimestre, $label, $start, $end]);
    flashMessage('success', 'Période créée et débloquée.');
    header('Location: grade_entry.php?class_id=' . $class_id . '&subject_id=' . $subject_id . '&trimestre=' . $trimestre . '&academic_year=' . urlencode($academic_year));
    exit;
}

// ── Teacher ──
$teacherId = null;
$teacherSubjJoin = '';
if (hasRole('teacher')) {
    $tidStmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id=?");
    $tidStmt->execute([$_SESSION['user_id']]);
    $teacherId = $tidStmt->fetchColumn();
    if ($teacherId) {
        $teacherSubjJoin = " LEFT JOIN teacher_assignments ta ON ta.subject_id=s.id AND ta.class_id=cs.class_id AND ta.teacher_id=" . (int)$teacherId;
    }
}

// ── Seuils décision conseil (par classe) ──
$COUNCIL_PASS = 14; $COUNCIL_ADMIT = 10; $COUNCIL_COUNCIL = 8; $COUNCIL_CLASS_NAME = '';
if ($class_id) {
    $cls = $pdo->prepare("SELECT name, pass_threshold, admit_threshold, council_threshold FROM classes WHERE id=?");
    $cls->execute([$class_id]); $cRow = $cls->fetch();
    if ($cRow) {
        $COUNCIL_PASS    = (float)($cRow['pass_threshold'] ?? 14);
        $COUNCIL_ADMIT   = (float)($cRow['admit_threshold'] ?? 10);
        $COUNCIL_COUNCIL = (float)($cRow['council_threshold'] ?? 8);
        $COUNCIL_CLASS_NAME = $cRow['name'];
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_thresholds']) && $class_id) {
    $pt = max(0, min(20, (float)($_POST['pass_threshold'] ?? 14)));
    $at = max(0, min(20, (float)($_POST['admit_threshold'] ?? 10)));
    $ct = max(0, min(20, (float)($_POST['council_threshold'] ?? 8)));
    $pdo->prepare("UPDATE classes SET pass_threshold=?, admit_threshold=?, council_threshold=? WHERE id=?")->execute([$pt, $at, $ct, $class_id]);
    $_SESSION['flash_toast'] = ['message' => 'Seuils mis à jour pour la classe.', 'type' => 'success'];
    header('Location: grade_entry.php?' . http_build_query(['class_id'=>$class_id,'subject_id'=>$subject_id,'trimestre'=>$trimestre,'academic_year'=>$academic_year]));
    exit;
}

// ── Export template CSV ──
if (isset($_GET['template']) && $class_id && $subject_id) {
    verifyCsrf();
    $st = $pdo->prepare("SELECT id, first_name, last_name, gender FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $st->execute([$class_id]); $students = $st->fetchAll();
    $sb = $pdo->prepare("SELECT code, name FROM subjects WHERE id=?");
    $sb->execute([$subject_id]); $subj = $sb->fetch();
    $code = $subj['code'] ?: $subj['name'];
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=template_' . $code . '_classe' . $class_id . '_T' . $trimestre . '.csv');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['N°', 'NOM & PRENOMS', 'SEXE', 'Interro', 'Devoir', 'Compo'], ';');
    $i = 1;
    foreach ($students as $s) {
        fputcsv($out, [$i++, $s['last_name'] . ' ' . $s['first_name'], $s['gender'] ?? '', '', '', ''], ';');
    }
    fclose($out);
    exit;
}

// ── Export CSV ──
if (isset($_GET['export']) && $class_id && $subject_id) {
    verifyCsrf();
    $st = $pdo->prepare("SELECT id, first_name, last_name, gender FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $st->execute([$class_id]); $students = $st->fetchAll();
    $sb = $pdo->prepare("SELECT code, name FROM subjects WHERE id=?");
    $sb->execute([$subject_id]); $subj = $sb->fetch();
    $code = $subj['code'] ?: $subj['name'];
    $gr = $pdo->prepare("SELECT * FROM grades WHERE class_id=? AND trimestre=? AND academic_year=? AND subject_id=?");
    $gr->execute([$class_id, $trimestre, $academic_year, $subject_id]);
    $grades = [];
    foreach ($gr->fetchAll() as $r) $grades[$r['student_id']] = $r;
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=' . $code . '_classe' . $class_id . '_T' . $trimestre . '_' . $academic_year . '.csv');
    echo "\xEF\xBB\xBF";
    $out = fopen('php://output', 'w');
    fputcsv($out, ['N°', 'NOM & PRENOMS', 'SEXE', 'Interro', 'Devoir', 'Compo'], ';');
    $i = 1;
    foreach ($students as $s) {
        $g = $grades[$s['id']] ?? [];
        fputcsv($out, [$i++, $s['last_name'] . ' ' . $s['first_name'], $s['gender'] ?? '', $g['note_interro'] ?? '', $g['note_devoir'] ?? '', $g['note_compo'] ?? ''], ';');
    }
    fclose($out);
    exit;
}

// ── Import CSV ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_grades']) && $class_id && $subject_id) {
    verifyCsrf();
    $classCheck = $pdo->prepare("SELECT id FROM classes WHERE id=?");
    $classCheck->execute([$class_id]);
    $classRow = $classCheck->fetch();
    if (!$classRow) { $_SESSION['flash_toast'] = ['message'=>'Classe invalide.','type'=>'error']; header('Location: grade_entry.php'); exit; }
    $schoolId = $schoolFilter;
    if (!$schoolId) {
        $st = $pdo->prepare("SELECT school_id FROM students WHERE class_id=? LIMIT 1");
        $st->execute([$class_id]);
        $schoolId = (int)$st->fetchColumn();
    }
    $periodCheck = checkGradingPeriod($pdo, $schoolId, $academic_year, $trimestre);
    if (!$periodCheck['allowed']) {
        $_SESSION['flash_toast'] = ['message' => 'Import bloqué : ' . $periodCheck['message'], 'type' => 'error'];
        header('Location: grade_entry.php?' . http_build_query(['class_id'=>$class_id,'subject_id'=>$subject_id,'trimestre'=>$trimestre,'academic_year'=>$academic_year])); exit;
    }
    $studentsList = $pdo->prepare("SELECT id, first_name, last_name FROM students WHERE class_id=? ORDER BY last_name, first_name");
    $studentsList->execute([$class_id]);
    $studentMap = [];
    foreach ($studentsList->fetchAll() as $s) $studentMap[strtolower($s['last_name'].' '.$s['first_name'])] = $s['id'];
    if (empty($_FILES['csv_file']['tmp_name'])) {
        $_SESSION['flash_toast'] = ['message' => 'Veuillez sélectionner un fichier CSV.', 'type' => 'error'];
    } else {
        $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
        $header = fgetcsv($handle, 0, ';');
        if (!$header || count($header) < 3) {
            $_SESSION['flash_toast'] = ['message' => 'Format CSV invalide. Utilisez le séparateur ";"', 'type' => 'error'];
        } else {
            $pdo->beginTransaction();
            try {
                $rowNum = 0; $imported = 0; $errs = [];
                while (($row = fgetcsv($handle, 0, ';')) !== false) {
                    $rowNum++;
                    if (count($row) < 3) continue;
                    list($num, $nom, $sexe, $interro, $devoir, $compo) = array_pad($row, 6, '');
                    $nom = trim($nom);
                    if (empty($nom)) continue;
                    $studentId = $studentMap[strtolower($nom)] ?? null;
                    if (!$studentId) { $errs[] = "Ligne $rowNum : '$nom' introuvable"; continue; }
                    $ni = $interro !== '' ? (float)str_replace(',', '.', $interro) : null;
                    $nd = $devoir !== '' ? (float)str_replace(',', '.', $devoir) : null;
                    $nc = $compo !== '' ? (float)str_replace(',', '.', $compo) : null;
                    if ($ni !== null && ($ni < 0 || $ni > 20)) { $errs[] = "Ligne $rowNum : interro invalide"; continue; }
                    if ($nd !== null && ($nd < 0 || $nd > 20)) { $errs[] = "Ligne $rowNum : devoir invalide"; continue; }
                    if ($nc !== null && ($nc < 0 || $nc > 20)) { $errs[] = "Ligne $rowNum : compo invalide"; continue; }
                    $pdo->prepare("INSERT INTO grades (student_id,subject_id,class_id,school_id,trimestre,academic_year,note_interro,note_devoir,note_compo) VALUES(?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE note_interro=VALUES(note_interro),note_devoir=VALUES(note_devoir),note_compo=VALUES(note_compo)")
                        ->execute([$studentId, $subject_id, $class_id, $schoolId, $trimestre, $academic_year, $ni, $nd, $nc]);
                    $imported++;
                }
                $pdo->commit();
                $msg = "$imported notes importées.";
                if (!empty($errs)) $msg .= ' ' . implode('. ', array_slice($errs, 0, 20));
                $_SESSION['flash_toast'] = ['message' => $msg, 'type' => 'success'];
            } catch (Exception $e) {
                $pdo->rollBack();
                $_SESSION['flash_toast'] = ['message' => 'Erreur import : ' . $e->getMessage(), 'type' => 'error'];
            }
        }
        fclose($handle);
    }
    header("Location: grade_entry.php?class_id=$class_id&subject_id=$subject_id&trimestre=$trimestre&academic_year=".urlencode($academic_year));
    exit;
}

// ── Sauvegarde des notes ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_grades'])) {
    verifyCsrf();
    $classCheck = $pdo->prepare("SELECT id FROM classes WHERE id=?");
    $classCheck->execute([$class_id]);
    $classRow = $classCheck->fetch();
    if (!$classRow) { flashMessage('error','Classe invalide.'); header('Location: grade_entry.php'); exit; }
    $schoolId = $schoolFilter;
    if (!$schoolId) {
        $st = $pdo->prepare("SELECT school_id FROM students WHERE class_id=? LIMIT 1");
        $st->execute([$class_id]);
        $schoolId = (int)$st->fetchColumn();
    }
    $periodCheck = checkGradingPeriod($pdo, $schoolId, $academic_year, $trimestre);
    if (!$periodCheck['allowed']) {
        flashMessage('error', 'Saisie bloquée : ' . $periodCheck['message']);
        header('Location: grade_entry.php?' . http_build_query(['class_id'=>$class_id,'subject_id'=>$subject_id,'trimestre'=>$trimestre,'academic_year'=>$academic_year])); exit;
    }
    $validStudents = $pdo->prepare("SELECT id FROM students WHERE class_id=?");
    $validStudents->execute([$class_id]);
    $validStudentIds = array_column($validStudents->fetchAll(), 'id');
    $rows  = $_POST['grades'] ?? [];
    $apprs = $_POST['apprs']  ?? [];
    $saved = 0; $errors = [];
    $pdo->beginTransaction();
    $stmtInsert = $pdo->prepare("INSERT INTO grades (student_id,subject_id,class_id,school_id,trimestre,academic_year,note_interro,note_devoir,note_compo,appreciation) VALUES(?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE note_interro=VALUES(note_interro),note_devoir=VALUES(note_devoir),note_compo=VALUES(note_compo),appreciation=VALUES(appreciation)");
    $stmtUpdateMoy = $pdo->prepare("UPDATE grades SET moy_classe=? WHERE class_id=? AND subject_id=? AND trimestre=? AND academic_year=?");
    try {
        foreach ($rows as $student_id => $subjects) {
            $student_id = (int)$student_id;
            if (!in_array($student_id, $validStudentIds, true)) continue;
            foreach ($subjects as $subj_id => $notes) {
                $subj_id = (int)$subj_id;
                $ni = $notes['interro'] !== '' ? (float)$notes['interro'] : null;
                $nd = $notes['devoir']  !== '' ? (float)$notes['devoir']  : null;
                $nc = $notes['compo']   !== '' ? (float)$notes['compo']   : null;
                if (($ni !== null && ($ni < 0 || $ni > 20)) || ($nd !== null && ($nd < 0 || $nd > 20)) || ($nc !== null && ($nc < 0 || $nc > 20))) continue;
                $ap = trim($apprs[$student_id][$subj_id] ?? '');
                $ap = $ap ?: autoAppreciation(calcMoyMatiere($ni, $nd, $nc));
                $stmtInsert->execute([$student_id, $subj_id, $class_id, $schoolId, $trimestre, $academic_year, $ni, $nd, $nc, $ap]);
                $saved++;
            }
        }
        // moy_classe
        $subjMoys = []; $subjCnts = [];
        foreach ($rows as $student_id => $subjects) {
            foreach ($subjects as $subj_id => $notes) {
                $m = calcMoyMatiere(
                    $notes['interro'] !== '' ? (float)$notes['interro'] : null,
                    $notes['devoir']  !== '' ? (float)$notes['devoir']  : null,
                    $notes['compo']   !== '' ? (float)$notes['compo']   : null
                );
                if ($m !== null) { $subjMoys[$subj_id] = ($subjMoys[$subj_id] ?? 0) + $m; $subjCnts[$subj_id] = ($subjCnts[$subj_id] ?? 0) + 1; }
            }
        }
        foreach ($subjMoys as $subj_id => $sum) {
            $stmtUpdateMoy->execute([round($sum / $subjCnts[$subj_id], 2), $class_id, $subj_id, $trimestre, $academic_year]);
        }
        $pdo->commit();
        $msg = "$saved notes enregistrées.";
        if (!empty($errors)) $msg .= ' ' . implode('. ', $errors);
        $_SESSION['flash_toast'] = ['message' => $msg, 'type' => 'success'];
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['flash_toast'] = ['message' => 'Erreur : ' . $e->getMessage(), 'type' => 'error'];
    }
    header("Location: grade_entry.php?class_id=$class_id&subject_id=$subject_id&trimestre=$trimestre&academic_year=".urlencode($academic_year));
    exit;
}

// ── Charger données ──
$selectedSchool = $schoolFilter ?? (int)($_GET['school_id'] ?? $sessionSchool);
if ($schoolFilter) {
    $classes = $pdo->prepare("SELECT DISTINCT c.id, c.name FROM classes c JOIN class_subjects cs ON cs.class_id=c.id WHERE cs.school_id=? ORDER BY " . getClassSortSQL('c'));
    $classes->execute([$schoolFilter]);
    $classes = $classes->fetchAll();
    if ($class_id) {
        $sbSt = $pdo->prepare("
            SELECT DISTINCT s.id, s.name, s.code,
                   COALESCE(sg.name,'Autres') AS group_name,
                   COALESCE(cs.coefficient,1) AS coefficient
            FROM class_subjects cs
            JOIN subjects s ON cs.subject_id=s.id
            LEFT JOIN subject_groups sg ON s.group_id=sg.id
            $teacherSubjJoin
            WHERE cs.class_id=? AND cs.school_id=?
            ORDER BY COALESCE(sg.sort_order,99), s.name");
        $sbSt->execute([$class_id, $schoolFilter]);
        $subjects = $sbSt->fetchAll();
    } else { $subjects = []; }
} else {
    if ($selectedSchool) {
        $classes = $pdo->prepare("SELECT DISTINCT c.id, c.name FROM classes c JOIN class_subjects cs ON cs.class_id=c.id WHERE cs.school_id=? ORDER BY " . getClassSortSQL('c'));
        $classes->execute([$selectedSchool]);
        $classes = $classes->fetchAll();
    } else {
        $classes = $pdo->query("SELECT DISTINCT c.id, c.name FROM classes c JOIN class_subjects cs ON cs.class_id=c.id ORDER BY " . getClassSortSQL('c'))->fetchAll();
    }
    if ($class_id) {
        $sbSt = $pdo->prepare("
            SELECT DISTINCT s.id, s.name, s.code,
                   COALESCE(sg.name,'Autres') AS group_name,
                   COALESCE(cs.coefficient,1) AS coefficient
            FROM class_subjects cs
            JOIN subjects s ON cs.subject_id=s.id
            LEFT JOIN subject_groups sg ON s.group_id=sg.id
            $teacherSubjJoin
            WHERE cs.class_id=? AND cs.school_id=?
            ORDER BY COALESCE(sg.sort_order,99), s.name");
        $sbSt->execute([$class_id, $selectedSchool]);
        $subjects = $sbSt->fetchAll();
    } else { $subjects = []; }
}

if ($subject_id && !empty($subjects)) {
    $filtered = array_values(array_filter($subjects, fn($s) => (int)$s['id'] === $subject_id));
    $subjects = $filtered;
}

$students = $class_id ? $pdo->prepare("SELECT id,first_name,last_name FROM students WHERE class_id=? ORDER BY last_name, first_name") : null;
if ($students) { $students->execute([$class_id]); $students=$students->fetchAll(); } else $students=[];

$existingGrades = [];
if ($class_id && $trimestre && $academic_year) {
    $gr = $pdo->prepare("SELECT * FROM grades WHERE class_id=? AND trimestre=? AND academic_year=? AND subject_id=?");
    $gr->execute([$class_id, $trimestre, $academic_year, $subject_id]);
    foreach ($gr->fetchAll() as $row) $existingGrades[$row['student_id']] = $row;
}

// Récupérer toutes les matières de la classe pour le sélecteur
$allClassSubjects = $class_id ? $pdo->prepare("SELECT DISTINCT s.id, s.name, s.code FROM class_subjects cs JOIN subjects s ON cs.subject_id=s.id $teacherSubjJoin WHERE cs.class_id=? AND cs.school_id=? ORDER BY s.name") : null;
if ($allClassSubjects) { $allClassSubjects->execute([$class_id, $selectedSchool]); $allClassSubjects=$allClassSubjects->fetchAll(); } else $allClassSubjects=[];

$schoolsList = $pdo->query("SELECT id,name FROM schools ORDER BY name")->fetchAll();
$years = $pdo->prepare("SELECT DISTINCT year FROM academic_years WHERE school_id=? ORDER BY year DESC");
$years->execute([$schoolFilter ?: 0]);
$years = $years->fetchAll(PDO::FETCH_COLUMN);
if (empty($years)) $years = $pdo->query("SELECT DISTINCT year FROM academic_years ORDER BY year DESC")->fetchAll(PDO::FETCH_COLUMN);
if (empty($years)) $years = [];
$years = array_unique(array_merge($years, [date('Y').'-'.(date('Y')+1)]));

$__flash = $_SESSION['flash_toast'] ?? null;
unset($_SESSION['flash_toast']);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Saisie par classe - Nukunu Mofiala</title>
<link rel="stylesheet" href="../assets/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root { --primary: #1F4E79; --accent: #2E75B6; --light: #D6E4F0; }
.prog-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:1.5rem; flex-wrap:wrap; gap:1rem; }
.prog-header h1 { font-family:Georgia,serif; color:var(--primary); font-size:1.6rem; }
.prog-header p { color:#666; font-size:.9rem; }
.filters-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:1.25rem 1.5rem; margin-bottom:1.5rem; }
.filters-row { display:flex; gap:1.25rem; align-items:flex-end; flex-wrap:wrap; }
.filter-group { display:flex; flex-direction:column; gap:6px; flex:1; min-width:150px; }
.filter-group label { font-weight:600; color:var(--primary); font-size:.8rem; }
.filter-group select { padding:.55rem .75rem; border:1px solid #D1D5DB; border-radius:6px; font-size:.85rem; background:white; cursor:pointer; }
.filter-group select:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(46,117,182,0.15); }
.table-card { background:white; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,0.06); overflow:hidden; margin-bottom:1.5rem; }
.table-card .tc-header { padding:1rem 1.5rem; border-bottom:1px solid #E5E7EB; display:flex; justify-content:space-between; align-items:center; }
.table-card .tc-title { font-family:Georgia,serif; color:var(--primary); font-size:1.05rem; }
.prog-table { width:100%; border-collapse:collapse; }
.prog-table thead { background:var(--primary); color:white; }
.prog-table th { padding:.6rem .8rem; text-align:left; font-weight:600; font-size:.74rem; text-transform:uppercase; letter-spacing:.4px; white-space:nowrap; }
.prog-table td { padding:.55rem .8rem; border-bottom:1px solid #E5E7EB; font-size:.82rem; vertical-align:middle; }
.prog-table tbody tr:hover { background:#F9FAFB; }
.grade-input { width:56px; padding:.3rem .3rem; border:1px solid #D1D5DB; border-radius:4px; text-align:center; font-size:.82rem; }
.grade-input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 2px rgba(46,117,182,0.12); }
.appr-select { padding:.25rem .35rem; border:1px solid #D1D5DB; border-radius:4px; font-size:.75rem; background:white; }
.btn { display:inline-flex; align-items:center; gap:6px; padding:.5rem 1.1rem; border:none; border-radius:6px; font-size:.82rem; font-weight:600; cursor:pointer; transition:all .2s; text-decoration:none; }
.btn-primary { background:var(--primary); color:white; }
.btn-primary:hover { background:#163a5c; }
.btn-light { background:#E5E7EB; color:#374151; }
.btn-light:hover { background:#D1D5DB; }
.btn-success { background:#10B981; color:white; }
.btn-success:hover { background:#059669; }
.btn-warning { background:#F59E0B; color:white; }
.toast-container { position:fixed; bottom:30px; right:30px; z-index:2000; display:flex; flex-direction:column; gap:10px; }
.toast { background:white; padding:12px 18px; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.15); display:flex; align-items:center; gap:10px; animation:slideIn .3s ease; border-left:4px solid var(--primary); font-size:.9rem; }
.toast-success { border-left-color:#10B981; }
.toast-error { border-left-color:#EF4444; }
@keyframes slideIn { from{transform:translateX(100%);opacity:0;} to{transform:translateX(0);opacity:1;} }
.modal-overlay { display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.4); z-index:1500; align-items:center; justify-content:center; }
.modal-overlay.open { display:flex; }
.modal-box { background:white; border-radius:12px; padding:2rem; width:90%; max-width:480px; max-height:90vh; overflow-y:auto; box-shadow:0 10px 40px rgba(0,0,0,0.2); }
.modal-box h2 { font-family:Georgia,serif; color:var(--primary); font-size:1.15rem; margin-bottom:1.25rem; display:flex; align-items:center; gap:.5rem; }
.modal-box .modal-actions { display:flex; gap:.75rem; margin-top:1.25rem; justify-content:flex-end; }
.empty-state { text-align:center; padding:3rem 1rem; color:#9CA3AF; }
.subject-nav { display:flex; gap:.35rem; flex-wrap:wrap; align-items:center; }
.subject-nav a { padding:.3rem .65rem; border-radius:20px; font-size:.76rem; text-decoration:none; font-weight:600; transition:all .15s; }
@media (max-width:768px) {
  .prog-header { flex-direction:column; align-items:flex-start; }
  .filters-row { flex-direction:column; }
  .filter-group { min-width:100%; }
  .modal-box { padding:1.25rem; }
}
</style>
</head>
<body>
<div class="dashboard">
    <?php include '../includes/sidebar.php'; ?>
    <div class="main-content">
        <?php $pageTitle = '<i class="fas fa-pen-alt"></i> Saisie par classe'; include '../includes/topbar.php'; ?>

        <?php if ($__flash): ?>
        <script>document.addEventListener('DOMContentLoaded',function(){showToast(<?= json_encode($__flash['message']) ?>,<?= json_encode($__flash['type']) ?>);});</script>
        <?php endif; ?>

        <!-- ═══ Header ═══ -->
        <div class="prog-header">
            <div>
                <h1><i class="fas fa-pen-alt" style="color:var(--primary);"></i> Saisie par classe</h1>
                <p>Saisissez les notes pour une classe et une matière spécifiques</p>
            </div>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
                <?php if ($class_id && $subject_id): ?>
                <a href="?class_id=<?= $class_id ?>&subject_id=<?= $subject_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>&export=1&csrf_token=<?= csrfToken() ?>" class="btn btn-success" style="font-size:.76rem;padding:.4rem .9rem;">
                    <i class="fas fa-download"></i> Export CSV
                </a>
                <button onclick="openImportModal()" class="btn btn-warning" style="font-size:.76rem;padding:.4rem .9rem;color:white;">
                    <i class="fas fa-upload"></i> Import CSV
                </button>
                <?php endif; ?>
            </div>
        </div>

        <!-- ═══ Filtres ═══ -->
        <form method="GET" class="filters-card" id="filterForm">
            <div class="filters-row">
                <?php if (!$schoolFilter): ?>
                <div class="filter-group">
                    <label><i class="fas fa-school"></i> École</label>
                    <select name="school_id" onchange="this.form.submit()">
                        <option value="">-- Toutes --</option>
                        <?php foreach ($schoolsList as $sc): ?>
                        <option value="<?= $sc['id'] ?>" <?= (($_GET['school_id']??$sessionSchool)==$sc['id'])?'selected':'' ?>><?= e($sc['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="filter-group">
                    <label><i class="fas fa-calendar"></i> Année scolaire</label>
                    <select name="academic_year" onchange="this.form.submit()">
                        <?php foreach ($years as $y): ?>
                        <option value="<?= e($y) ?>" <?= $y===$academic_year?'selected':'' ?>><?= e($y) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-layer-group"></i> Période</label>
                    <select name="trimestre" onchange="this.form.submit()">
                        <option value="1" <?= $trimestre==1?'selected':'' ?>>1er Trimestre</option>
                        <option value="2" <?= $trimestre==2?'selected':'' ?>>2ème Trimestre</option>
                        <option value="3" <?= $trimestre==3?'selected':'' ?>>3ème Trimestre</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label><i class="fas fa-users"></i> Classe <span style="color:red;">*</span></label>
                    <select name="class_id" required onchange="this.form.submit()">
                        <option value="">-- Choisir --</option>
                        <?php foreach ($classes as $cl): ?>
                        <option value="<?= $cl['id'] ?>" <?= $cl['id']==$class_id?'selected':'' ?>>
                            <?= e($cl['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php if ($class_id && !empty($subjects)): ?>
                <div class="filter-group">
                    <label><i class="fas fa-book"></i> Matière <span style="color:red;">*</span></label>
                    <select name="subject_id" onchange="this.form.submit()">
                        <option value="">-- Choisir --</option>
                        <?php foreach ($subjects as $sb): ?>
                        <option value="<?= $sb['id'] ?>" <?= $subject_id===$sb['id']?'selected':'' ?>>
                            <?= e($sb['code']?:$sb['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <?php if ($class_id): ?>
                <a href="bulletin.php?class_id=<?= $class_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>" class="btn btn-light" style="padding:.5rem 1rem;text-decoration:none;font-size:.78rem;">
                    <i class="fas fa-file-alt"></i> Bulletins
                </a>
                <?php endif; ?>
            </div>
        </form>

        <?php if (!$class_id): ?>
        <div class="table-card">
            <div class="empty-state">
                <i class="fas fa-hand-pointer" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">Sélectionnez une classe et une matière.</p>
            </div>
        </div>
        <?php elseif (empty($subjects)): ?>
        <div class="table-card">
            <div class="empty-state">
                <i class="fas fa-exclamation-triangle" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p>Aucune matière assignée à cette classe.</p>
                <a href="subjects.php?action=class_subjects&filter_class=<?= $class_id ?>" class="btn btn-primary" style="margin-top:1rem;">Assigner des matières</a>
            </div>
        </div>
        <?php elseif (!$subject_id): ?>
        <div class="table-card">
            <div class="empty-state">
                <i class="fas fa-hand-pointer" style="font-size:2.5rem;display:block;margin-bottom:.75rem;color:#CBD5E1;"></i>
                <p style="font-size:1.05rem;">Sélectionnez une matière dans le filtre.</p>
            </div>
        </div>
        <?php else:
            $schoolId = $schoolFilter;
            if (!$schoolId) { $sc = $pdo->prepare("SELECT school_id FROM students WHERE class_id=? LIMIT 1"); $sc->execute([$class_id]); $schoolId = (int)$sc->fetchColumn(); }
            $periodCheck = checkGradingPeriod($pdo, $schoolId, $academic_year, $trimestre);
            $currentSubj = $subjects[0] ?? null;
        ?>
        <!-- ═══ Periode info ═══ -->
        <?php $qs = 'class_id=' . $class_id . '&subject_id=' . $subject_id . '&trimestre=' . $trimestre . '&academic_year=' . urlencode($academic_year); ?>
        <div style="display:flex;align-items:center;gap:.75rem;padding:.55rem 1rem;margin-bottom:1rem;font-size:.8rem;border-radius:8px;flex-wrap:wrap;<?= $periodCheck['allowed']?'background:#F0FFF4;border:1px solid #C6F6D5;':'background:#FFF5F5;border:1px solid #FED7D7;' ?>">
            <i class="fas fa-<?= $periodCheck['allowed']?'check-circle':'exclamation-circle' ?>" style="color:<?= $periodCheck['allowed']?'#38A169':'#E53E3E' ?>;"></i>
            <span style="flex:1;">
                <?php if ($periodCheck['period']): ?>
                <strong><?= e($periodCheck['period']['label']) ?></strong> — du <?= formatDate($periodCheck['period']['start_date']) ?> au <?= formatDate($periodCheck['period']['end_date']) ?>
                <?php else: ?>
                <span style="color:#856404;">Aucune période définie — saisie libre.</span>
                <?php endif; ?>
            </span>
            <span style="font-weight:600;color:<?= $periodCheck['allowed']?'#22543D':'#9B2C2C' ?>;">
                <i class="fas fa-<?= $periodCheck['allowed']?'lock-open':'lock' ?>"></i>
                <?= $periodCheck['allowed']?'Saisie autorisée':'Saisie fermée' ?>
            </span>
            <?php if (hasRole(['super_admin','school_admin'])): ?>
            <span style="display:flex;gap:6px;">
                <?php if ($periodCheck['period']): ?>
                <a href="?<?= $qs ?>&toggle_lock=<?= $periodCheck['allowed']?0:1 ?>&csrf=<?= $_SESSION['csrf_token'] ?>"
                   style="padding:4px 12px;border-radius:6px;font-size:.75rem;font-weight:600;text-decoration:none;display:inline-flex;align-items:center;gap:4px;<?= $periodCheck['allowed']?'background:#FED7D7;color:#C53030;':'background:#C6F6D5;color:#22543D;' ?>">
                    <i class="fas fa-<?= $periodCheck['allowed']?'lock':'lock-open' ?>"></i>
                    <?= $periodCheck['allowed']?'Bloquer':'Débloquer' ?>
                </a>
                <?php else: ?>
                <a href="?<?= $qs ?>&create_period=1&csrf=<?= $_SESSION['csrf_token'] ?>"
                   style="padding:4px 12px;border-radius:6px;font-size:.75rem;font-weight:600;text-decoration:none;display:inline-flex;align-items:center;gap:4px;background:#C6F6D5;color:#22543D;">
                    <i class="fas fa-plus-circle"></i> Créer période
                </a>
                <?php endif; ?>
                <a href="grading_periods.php" style="padding:4px 10px;border-radius:6px;font-size:.75rem;text-decoration:none;color:#4B5563;background:#E5E7EB;display:inline-flex;align-items:center;gap:4px;">
                    <i class="fas fa-cog"></i> Gérer
                </a>
            </span>
            <?php endif; ?>
        </div>

        <!-- ═══ Navigation mati�?res ═══ -->
        <div style="background:white;border-radius:8px;box-shadow:0 1px 4px rgba(0,0,0,0.06);padding:.5rem .85rem;margin-bottom:1rem;border-left:4px solid var(--accent);">
            <div class="subject-nav">
                <span style="font-weight:600;font-size:.8rem;color:#4B5563;margin-right:.5rem;"><i class="fas fa-book"></i> Matières :</span>
                <?php foreach ($allClassSubjects as $ns): ?>
                <a href="?class_id=<?= $class_id ?>&subject_id=<?= $ns['id'] ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>"
                   style="background:<?= (int)$ns['id']===$subject_id?'var(--primary)':'#E5E7EB' ?>;color:<?= (int)$ns['id']===$subject_id?'white':'#374151' ?>;">
                    <?= e($ns['code']?:$ns['name']) ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ═══ Tableau des notes ═══ -->
        <form method="POST" id="gradesForm">
            <?= csrfField() ?>
            <input type="hidden" name="save_grades" value="1">
            <input type="hidden" name="trimestre" value="<?= $trimestre ?>">
            <input type="hidden" name="academic_year" value="<?= e($academic_year) ?>">
            <input type="hidden" name="class_id" value="<?= $class_id ?>">

            <div class="table-card">
                <div class="tc-header">
                    <div class="tc-title">
                        <span style="display:inline-block;padding:.2rem .6rem;border-radius:6px;background:var(--primary);color:white;font-size:.82rem;font-weight:700;margin-right:.4rem;">
                            <?= e(($currentSubj['code']??'')?:($currentSubj['name']??'')) ?>
                        </span>
                        <?= e($currentSubj['name']??'') ?>
                        <small style="font-weight:400;color:#718096;"> ×<?= number_format($currentSubj['coefficient']??1,1) ?></small>
                    </div>
                    <button type="submit" class="btn btn-primary" style="padding:.45rem 1.25rem;"><i class="fas fa-save"></i> Enregistrer</button>
                </div>
                <div style="overflow-x:auto;">
                <table class="prog-table">
                    <thead>
                        <tr>
                            <th style="width:32px;text-align:center;">N°</th>
                            <th style="min-width:170px;">Élève</th>
                            <th style="text-align:center;width:80px;">Interro <small>(×1)</small></th>
                            <th style="text-align:center;width:80px;">Devoir <small>(×2)</small></th>
                            <th style="text-align:center;width:80px;">Compo <small>(×3)</small></th>
                            <th style="text-align:center;width:56px;">Moy.</th>
                            <th style="min-width:130px;">Appréciation</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $i=1; foreach ($students as $st):
                            $g = $existingGrades[$st['id']] ?? [];
                            $ni = $g['note_interro']??null; $nd = $g['note_devoir']??null; $nc = $g['note_compo']??null;
                            $moy = calcMoyMatiere($ni, $nd, $nc);
                            $autoAp = autoAppreciation($moy);
                            if ($moy===null) { $abg='#E2E8F0'; $afg='#A0AEC0'; }
                            elseif ($moy>=18) { $abg='#805AD5'; $afg='white'; }
                            elseif ($moy>=16) { $abg='#2B6CB0'; $afg='white'; }
                            elseif ($moy>=14) { $abg='#38A169'; $afg='white'; }
                            elseif ($moy>=12) { $abg='#D69E2E'; $afg='white'; }
                            elseif ($moy>=10) { $abg='#ED8936'; $afg='white'; }
                            elseif ($moy>=6) { $abg='#E53E3E'; $afg='white'; }
                            else { $abg='#9B2C2C'; $afg='white'; }
                        ?>
                        <tr>
                            <td style="text-align:center;color:#718096;"><?= $i++ ?></td>
                            <td><?= e($st['last_name'].' '.$st['first_name']) ?></td>
                            <td><input type="number" name="grades[<?= $st['id'] ?>][<?= $subject_id ?>][interro]" value="<?= e($ni??'') ?>" min="0" max="20" step="0.25" class="grade-input"></td>
                            <td><input type="number" name="grades[<?= $st['id'] ?>][<?= $subject_id ?>][devoir]" value="<?= e($nd??'') ?>" min="0" max="20" step="0.25" class="grade-input"></td>
                            <td><input type="number" name="grades[<?= $st['id'] ?>][<?= $subject_id ?>][compo]" value="<?= e($nc??'') ?>" min="0" max="20" step="0.25" class="grade-input"></td>
                            <td style="text-align:center;font-weight:600;color:<?= $moy!==null?($moy>=10?'#22543D':'#C53030'):'#A0AEC0' ?>;"><?= $moy!==null?e($moy):'—' ?></td>
                            <td>
                                <div style="display:flex;gap:.3rem;align-items:center;">
                                    <span style="display:inline-block;padding:.1rem .4rem;border-radius:4px;font-size:.68rem;font-weight:700;white-space:nowrap;background:<?= $abg ?>;color:<?= $afg ?>;"><?= $autoAp?:'—' ?></span>
                                    <select name="apprs[<?= $st['id'] ?>][<?= $subject_id ?>]" class="appr-select" style="flex:1;min-width:80px;">
                                        <option value="">Auto</option>
                                        <?php foreach(['Excellent','Très Bien','Bien','Assez Bien','Passable','A Peine Passable','Insuffisant','Très Insuffisant','Blâme'] as $ap): ?>
                                        <option value="<?= $ap ?>" <?= (!empty($g['appreciation'])&&$g['appreciation']===$ap)?'selected':'' ?>><?= $ap ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($students)): ?>
                        <tr><td colspan="7" style="text-align:center;color:#9CA3AF;padding:1.5rem;">Aucun élève dans cette classe.</td></tr>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr style="background:#FFFFF0;font-weight:600;">
                            <td></td>
                            <td><em>Moy. Classe <small>(auto)</small></em></td>
                            <?php
                            $mcVal = '';
                            foreach ($existingGrades as $eg) {
                                if (isset($eg['moy_classe']) && $eg['moy_classe']!==null) { $mcVal = $eg['moy_classe']; break; }
                            }
                            ?>
                            <td colspan="3" style="text-align:center;color:#2D3748;"><?= $mcVal!==''?e($mcVal):'—' ?></td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                </table>
                </div>
            </div>

            <div style="text-align:right;margin-top:1rem;">
                <button type="submit" class="btn btn-primary" style="padding:.7rem 2.25rem;font-size:.95rem;"><i class="fas fa-save"></i> Enregistrer</button>
            </div>
        </form>
        <?php endif; ?>
    </div>
</div>

<!-- ═══ Modal Import CSV ═══ -->
<div class="modal-overlay" id="importModal">
    <div class="modal-box">
        <h2><i class="fas fa-upload"></i> Importer des notes (CSV)</h2>
        <form method="POST" enctype="multipart/form-data">
            <?= csrfField() ?>
            <input type="hidden" name="import_grades" value="1">
            <input type="hidden" name="class_id" value="<?= $class_id ?>">
            <input type="hidden" name="trimestre" value="<?= $trimestre ?>">
            <input type="hidden" name="academic_year" value="<?= e($academic_year) ?>">
            <div style="background:#EBF8FF;border:1px solid #BEE3F8;border-radius:8px;padding:1rem;margin-bottom:1.25rem;font-size:.8rem;">
                <strong><i class="fas fa-info-circle"></i> Format attendu (;)</strong><br>
                <?php if ($subject_id): ?>
                <code style="font-size:.72rem;">N°;NOM & PRENOMS;SEXE;Interro;Devoir;Compo</code><br>
                <small>Notes entre 0 et 20.</small>
                <?php else: ?>
                <div style="color:#E53E3E;font-weight:600;">Sélectionnez d'abord une matière.</div>
                <?php endif; ?>
                <br>
                <a href="?class_id=<?= $class_id ?>&subject_id=<?= $subject_id ?>&trimestre=<?= $trimestre ?>&academic_year=<?= urlencode($academic_year) ?>&template=1&csrf_token=<?= csrfToken() ?>" style="display:inline-flex;align-items:center;gap:.35rem;margin-top:.3rem;color:#2563EB;font-size:.78rem;"><i class="fas fa-download"></i> Télécharger le modèle</a>
            </div>
            <div style="margin-bottom:1rem;">
                <label style="font-weight:600;font-size:.8rem;color:var(--primary);">Fichier CSV <span style="color:red;">*</span></label>
                <input type="file" name="csv_file" accept=".csv" required style="width:100%;padding:.5rem;border:1px solid #D1D5DB;border-radius:6px;">
            </div>
            <div class="modal-actions">
                <button type="button" class="btn btn-light" onclick="closeImportModal()">Annuler</button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-upload"></i> Importer</button>
            </div>
        </form>
    </div>
</div>

<!-- ═══ Toast Container ═══ -->
<div class="toast-container" id="toastContainer"></div>

<script>
function openImportModal(){document.getElementById('importModal').classList.add('open');}
function closeImportModal(){document.getElementById('importModal').classList.remove('open');}
document.getElementById('importModal')?.addEventListener('click',function(e){if(e.target===this)closeImportModal();});
function calcMoy(ni,nd,nc){if(ni===''&&nd===''&&nc==='')return null;var a=ni!==''?parseFloat(ni):null;var b=nd!==''?parseFloat(nd):null;var c=nc!==''?parseFloat(nc):null;if(a!==null&&b!==null&&c!==null)return(a*1+b*2+c*3)/6;if(a!==null&&b!==null)return(a+b)/2;if(a!==null&&c!==null)return(a+c)/2;if(b!==null&&c!==null)return(b+c)/2;if(a!==null)return a;if(b!==null)return b;return c;}
function autoAp(moy){if(moy===null||moy===undefined)return '';if(moy>=18)return'Excellent';if(moy>=16)return'Très Bien';if(moy>=14)return'Bien';if(moy>=12)return'Assez Bien';if(moy>=10)return'Passable';if(moy>=9)return'A Peine Passable';if(moy>=6)return'Insuffisant';if(moy>=3)return'Très Insuffisant';return'Blâme';}
function apColor(moy){if(moy===null||moy===undefined)return{bg:'#E2E8F0',fg:'#A0AEC0'};if(moy>=18)return{bg:'#805AD5',fg:'white'};if(moy>=16)return{bg:'#2B6CB0',fg:'white'};if(moy>=14)return{bg:'#38A169',fg:'white'};if(moy>=12)return{bg:'#D69E2E',fg:'white'};if(moy>=10)return{bg:'#ED8936',fg:'white'};if(moy>=6)return{bg:'#E53E3E',fg:'white'};return{bg:'#9B2C2C',fg:'white'};}
function recalc(){document.querySelectorAll('.prog-table tbody tr').forEach(function(r){var inp=r.querySelectorAll('.grade-input');if(inp.length<3)return;var m=calcMoy(inp[0].value,inp[1].value,inp[2].value);var ms=r.querySelector('td:nth-child(6)');if(ms){ms.textContent=m!==null?m.toFixed(2):'—';ms.style.color=m!==null?(m>=10?'#22543D':'#C53030'):'#A0AEC0';}var ab=r.querySelector('td:nth-child(7) span');if(ab){var a=autoAp(m);ab.textContent=a||'—';var c=apColor(m);ab.style.background=c.bg;ab.style.color=c.fg;}});}
document.querySelectorAll('.grade-input').forEach(function(i){i.addEventListener('input',function(){var len=this.value.length||1;this.style.width=Math.max(5,Math.min(8,len+3))+'ch';recalc();});});
function showToast(msg,type){var c=document.getElementById('toastContainer');var t=document.createElement('div');t.className='toast toast-'+(type==='success'?'success':'error');t.innerHTML='<span>'+(type==='success'?'&#x2705;':'&#x274C;')+'</span><span>'+msg+'</span>';c.appendChild(t);setTimeout(function(){t.remove();},4000);}
</script>
</body>
</html>
