<?php
// teacher/manage_exams.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../config/database.php';

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'teacher') {
    header("Location: ../auth/login.php"); exit();
}

$teacher_id = (int)$_SESSION['user_id'];

// --- ACTIONS (Delete/Duplicate) ---
if (isset($_GET['delete_id'])) {
    $pdo->prepare("UPDATE exams SET is_deleted = 1 WHERE id = ? AND teacher_id = ?")
        ->execute([(int)$_GET['delete_id'], $teacher_id]);
    header("Location: manage_exams.php?msg=deleted"); exit();
}

if (isset($_GET['duplicate_id'])) {
    $old_id = (int)$_GET['duplicate_id'];
    $stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ? AND teacher_id = ?");
    $stmt->execute([$old_id, $teacher_id]);
    $exam = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($exam) {
        $sql = "INSERT INTO exams (exam_title, subject_id, class_id, duration, mark_per_question, teacher_id, status, is_deleted) 
                VALUES (?, ?, ?, ?, ?, ?, 0, 0)"; 
        $pdo->prepare($sql)->execute([$exam['exam_title']." (Copy)", $exam['subject_id'], $exam['class_id'], $exam['duration'], $exam['mark_per_question'], $teacher_id]);
        $new_id = $pdo->lastInsertId();

        $q_stmt = $pdo->prepare("SELECT * FROM questions WHERE exam_id = ?");
        $q_stmt->execute([$old_id]);
        foreach ($q_stmt->fetchAll(PDO::FETCH_ASSOC) as $q) {
            $pdo->prepare("INSERT INTO questions (exam_id, question_text, option_a, option_b, option_c, option_d, correct_option, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'draft')")
                ->execute([$new_id, $q['question_text'], $q['option_a'], $q['option_b'], $q['option_c'], $q['option_d'], $q['correct_option']]);
        }
        header("Location: manage_exams.php?msg=duplicated"); exit();
    }
}

// --- FETCH DATA ---
$exams_sql = "SELECT e.*, s.subject_name, c.class_name, 
              (SELECT COUNT(*) FROM questions WHERE exam_id = e.id) as q_count
              FROM exams e
              JOIN subjects s ON e.subject_id = s.id
              JOIN classes c ON e.class_id = c.id
              WHERE e.teacher_id = ? AND e.is_deleted = 0 ORDER BY e.id DESC";
$stmt = $pdo->prepare($exams_sql);
$stmt->execute([$teacher_id]);
$my_exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Quick Stats for Header
$total_exams = count($my_exams);
$pending_count = count(array_filter($my_exams, fn($ex) => $ex['status'] == 0));
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Question Bank | Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root { 
            --primary: #0f172a; --accent: #4f46e5; --bg: #f8fafc; 
            --glass: rgba(255, 255, 255, 0.8); --card-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.04);
            --pending: #f59e0b; --active: #10b981; --rejected: #ef4444;
        }
        
        * { box-sizing: border-box; transition: all 0.2s ease-in-out; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg); color: var(--primary); margin: 0; padding: 0; }
        
        /* Modern Sidebar-less Layout */
        .main-wrapper { max-width: 1280px; margin: 0 auto; padding: 40px 20px; }

        /* Stylish Top Bar */
        .glass-nav { 
            background: var(--glass); backdrop-filter: blur(10px); 
            display: flex; justify-content: space-between; align-items: center;
            padding: 15px 30px; border-radius: 20px; border: 1px solid #ffffff;
            box-shadow: var(--card-shadow); margin-bottom: 40px; position: sticky; top: 20px; z-index: 100;
        }

        /* Buttons */
        .btn { border-radius: 12px; font-weight: 700; font-size: 14px; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; padding: 12px 20px; cursor: pointer; border: none; }
        .btn-dash { background: #f1f5f9; color: #475569; }
        .btn-dash:hover { background: #e2e8f0; color: var(--primary); }
        .btn-primary { background: var(--accent); color: white; box-shadow: 0 10px 15px -3px rgba(79, 70, 229, 0.3); }
        .btn-primary:hover { background: #4338ca; transform: translateY(-2px); }

        /* Stats Section */
        .stats-grid { display: flex; gap: 20px; margin-bottom: 40px; }
        .stat-pill { background: white; padding: 10px 20px; border-radius: 15px; display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 14px; box-shadow: var(--card-shadow); border: 1px solid #f1f5f9; }
        .stat-pill i { color: var(--accent); }

        /* Card Grid */
        .card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); gap: 25px; }
        .exam-card { 
            background: white; border-radius: 24px; padding: 30px; 
            border: 1px solid #f1f5f9; position: relative; 
            box-shadow: var(--card-shadow); overflow: hidden;
        }
        .exam-card:hover { transform: translateY(-8px); box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.08); border-color: #e2e8f0; }

        /* Status & Decorative Elements */
        .status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
        .bg-pending { background: var(--pending); } .bg-active { background: var(--active); } .bg-rejected { background: var(--rejected); }
        
        .status-text { font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; display: flex; align-items: center; gap: 6px; }

        .subject-tag { margin-top: 15px; background: #eef2ff; color: #4338ca; padding: 4px 12px; border-radius: 8px; font-size: 11px; font-weight: 800; display: inline-block; }
        .exam-title { font-size: 20px; font-weight: 800; margin: 12px 0; color: #1e293b; height: 55px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }

        .meta-group { display: flex; gap: 20px; margin: 25px 0; padding: 15px 0; border-top: 1px solid #f8fafc; border-bottom: 1px solid #f8fafc; }
        .meta-item { display: flex; flex-direction: column; gap: 4px; }
        .meta-item span:first-child { font-size: 10px; color: #94a3b8; font-weight: 700; text-transform: uppercase; }
        .meta-item span:last-child { font-size: 14px; font-weight: 700; color: #334155; }

        /* Card Actions */
        .card-footer { display: flex; justify-content: space-between; align-items: center; }
        .action-circle { 
            width: 40px; height: 40px; border-radius: 50%; background: #f8fafc; 
            display: flex; align-items: center; justify-content: center; 
            text-decoration: none; color: #94a3b8; border: 1px solid #f1f5f9;
        }
        .action-circle:hover { background: #f1f5f9; color: var(--accent); border-color: #e2e8f0; }
        .action-circle.del:hover { color: var(--rejected); background: #fff1f2; }

        .btn-view { background: var(--primary); color: white; padding: 10px 20px; border-radius: 12px; font-size: 13px; font-weight: 700; text-decoration: none; }
        .btn-view:hover { opacity: 0.9; }

        @media (max-width: 600px) { .stats-grid { flex-direction: column; } .glass-nav { flex-direction: column; gap: 15px; } }
    </style>
</head>
<body>

<div class="main-wrapper">
    
    <nav class="glass-nav">
        <a href="dashboard.php" class="btn btn-dash">
            <i class="fa fa-th-large"></i> Dashboard
        </a>
        <div style="display: flex; gap: 10px;">
            <a href="create_exam.php" class="btn btn-primary">
                <i class="fa fa-plus-circle"></i> Create New Exam
            </a>
        </div>
    </nav>

    <div style="margin-bottom: 40px;">
        <h1 style="font-weight: 800; font-size: 32px; margin: 0;">Question Bank</h1>
        <p style="color: #64748b; margin-top: 5px;">Manage your curriculum and student assessments.</p>
        
        <div class="stats-grid" style="margin-top: 25px;">
            <div class="stat-pill"><i class="fa fa-folder"></i> Total: <?= $total_exams ?></div>
            <div class="stat-pill"><i class="fa fa-clock" style="color: var(--pending)"></i> Pending: <?= $pending_count ?></div>
            <div class="stat-pill"><i class="fa fa-check-circle" style="color: var(--active)"></i> Fully Vetted: <?= $total_exams - $pending_count ?></div>
        </div>
    </div>

    <div class="card-grid">
        <?php foreach ($my_exams as $exam): ?>
            <div class="exam-card">
                <div class="status-text">
                    <span class="status-dot bg-<?= $exam['status'] == 0 ? 'pending' : ($exam['status'] == 1 ? 'active' : 'rejected') ?>"></span>
                    <?= $exam['status'] == 0 ? 'Pending Approval' : ($exam['status'] == 1 ? 'Active' : 'Rejected') ?>
                </div>

                <div class="subject-tag"><?= htmlspecialchars($exam['subject_name']) ?></div>
                <div class="exam-title"><?= htmlspecialchars($exam['exam_title']) ?></div>
                
                <div class="meta-group">
                    <div class="meta-item"><span>Class</span><span><?= htmlspecialchars($exam['class_name']) ?></span></div>
                    <div class="meta-item"><span>Time</span><span><?= $exam['duration'] ?>m</span></div>
                    <div class="meta-item"><span>Items</span><span><?= $exam['q_count'] ?> Qs</span></div>
                </div>

                <div class="card-footer">
                    <div style="display: flex; gap: 10px;">
                        <a href="?duplicate_id=<?= $exam['id'] ?>" class="action-circle" title="Duplicate"><i class="fa fa-copy"></i></a>
                        <a href="?delete_id=<?= $exam['id'] ?>" class="action-circle del" title="Delete" onclick="return confirm('Archive this exam?')"><i class="fa fa-trash"></i></a>
                    </div>
                    <a href="add_questions_manual.php?exam_id=<?= $exam['id'] ?>" class="btn-view">
                        <?= $exam['status'] == 2 ? 'Fix Issues' : 'Edit Exam' ?>
                    </a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if(empty($my_exams)): ?>
        <div style="text-align: center; margin-top: 100px;">
            <img src="https://illustrations.popsy.co/gray/empty-folder.svg" style="width: 200px; opacity: 0.5;">
            <h3 style="color: #94a3b8;">The bank is empty. Start by creating a set!</h3>
        </div>
    <?php endif; ?>
</div>

</body>
</html>