<?php
session_start();
$projectRoot = dirname(__DIR__);
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

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

$teacher_id = $_SESSION['user_id'];

// 2. FETCH SYSTEM SETTINGS
$stmtSet = $pdo->query("SELECT * FROM system_settings WHERE id = 1");
$settings = $stmtSet->fetch();
$school_name     = $settings['school_name'] ?? "School Management System";
$current_session = $settings['active_session'] ?? "Not Set";
$current_term    = $settings['active_term'] ?? "Not Set";

// 3. FETCH TEACHER ALLOCATIONS WITH RESULT STATUS
$sql = "SELECT ts.id as assignment_id, c.class_name, s.subject_name, c.id as class_id, s.id as subject_id,
        (SELECT status FROM results 
         WHERE subject_id = s.id AND class_id = c.id 
         AND session = ? AND term = ? 
         LIMIT 1) as result_status
        FROM teacher_subjects ts
        JOIN classes c ON ts.class_id = c.id
        JOIN subjects s ON ts.subject_id = s.id
        WHERE ts.teacher_id = ?
        ORDER BY c.class_name ASC";
        
$stmt = $pdo->prepare($sql);
$stmt->execute([$current_session, $current_term, $teacher_id]);
$my_assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 4. CALCULATE SUMMARY STATS
$res_stats = ['pending' => 0, 'approved' => 0, 'rejected' => 0, 'not_started' => 0];
foreach($my_assignments as $asgn) {
    $st = $asgn['result_status'] ?? 'not_started';
    if (array_key_exists($st, $res_stats)) {
        $res_stats[$st]++;
    } else {
        $res_stats['not_started']++;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teacher Dashboard | <?= htmlspecialchars($school_name) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { 
            --sidebar-bg: #0f172a; 
            --accent: #3b82f6; 
            --bg-main: #f8fafc; 
            --card-bg: #ffffff; 
            --sidebar-width: 270px; 
            --danger: #ef4444; 
            --success: #10b981; 
            --warning: #f59e0b;
            --text-dark: #1e293b;
            --text-light: #64748b;
        }
        
        body { 
            font-family: 'Inter', system-ui, -apple-system, sans-serif; 
            background: var(--bg-main); 
            margin: 0; 
            display: flex; 
            color: var(--text-dark);
            min-height: 100vh;
        }
        
        /* --- Sidebar --- */
        .sidebar { 
            width: var(--sidebar-width); 
            height: 100vh; 
            background: var(--sidebar-bg); 
            color: white; 
            position: fixed; 
            z-index: 1000;
            display: flex;
            flex-direction: column;
            box-shadow: 4px 0 10px rgba(0,0,0,0.05);
        }

        .sidebar-brand { 
            padding: 40px 20px; 
            text-align: center; 
            border-bottom: 1px solid rgba(255,255,255,0.05);
        }

        .sidebar-logo { 
            width: 55px; height: 55px; 
            background: white; 
            border-radius: 14px; 
            padding: 6px; 
            margin-bottom: 15px; 
            object-fit: contain;
        }

        .sidebar-user { 
            padding: 20px; 
            margin: 20px;
            background: rgba(255,255,255,0.04);
            border-radius: 16px;
            text-align: center; 
        }

        .sidebar-user img { 
            width: 60px; height: 60px; 
            border-radius: 50%; 
            border: 2px solid var(--accent); 
            margin-bottom: 12px; 
            background: white;
        }

        .nav-links { list-style: none; padding: 0 15px; margin-top: 10px; }
        .nav-links li { margin-bottom: 5px; }
        .nav-links a { 
            display: flex; 
            align-items: center; 
            padding: 14px 18px; 
            color: #94a3b8; 
            text-decoration: none; 
            border-radius: 12px;
            transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1); 
        }

        .nav-links a i { width: 30px; font-size: 1.1rem; }
        .nav-links a:hover, .nav-links a.active { 
            background: var(--accent); 
            color: white; 
            box-shadow: 0 10px 15px -3px rgba(59, 130, 246, 0.3);
        }

        /* --- Main Content --- */
        .main { 
            margin-left: var(--sidebar-width); 
            padding: 40px 50px; 
            flex: 1; 
            min-width: 0; 
        }

        .header-flex { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            margin-bottom: 40px; 
        }

        .header-flex h1 { 
            margin: 0; 
            font-size: 1.8rem; 
            font-weight: 800; 
            letter-spacing: -0.025em; 
        }

        .session-badge { 
            background: var(--card-bg); 
            padding: 12px 24px; 
            border-radius: 14px; 
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); 
            border: 1px solid #e2e8f0;
            text-align: right;
        }

        /* --- Summary Cards --- */
        .summary-grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); 
            gap: 24px; 
            margin-bottom: 40px; 
        }

        .stat-card { 
            background: var(--card-bg); 
            padding: 24px; 
            border-radius: 20px; 
            display: flex; 
            align-items: center; 
            gap: 20px; 
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
            border: 1px solid #f1f5f9;
        }

        .stat-icon { 
            width: 56px; height: 56px; 
            border-radius: 16px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            font-size: 1.4rem; 
        }

        /* --- Grid & Assignment Cards --- */
        .grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); 
            gap: 28px; 
        }

        .assignment-card { 
            background: var(--card-bg); 
            border-radius: 24px; 
            overflow: hidden; 
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); 
            display: flex; 
            flex-direction: column; 
            border: 1px solid #f1f5f9;
            transition: all 0.3s ease;
        }

        .assignment-card:hover { 
            transform: translateY(-6px); 
            box-shadow: 0 20px 25px -5px rgba(0,0,0,0.08);
        }

        .card-top { 
            padding: 24px 24px 12px 24px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
        }

        .class-badge { 
            font-size: 0.75rem; 
            font-weight: 700; 
            color: var(--accent); 
            background: #eff6ff;
            padding: 4px 12px;
            border-radius: 8px;
            text-transform: uppercase; 
        }

        .status-pill { 
            padding: 6px 12px; 
            border-radius: 8px; 
            font-size: 0.7rem; 
            font-weight: 800; 
            letter-spacing: 0.05em;
        }
        .status-rejected { background: #fee2e2; color: #b91c1c; }
        .status-pending { background: #e0e7ff; color: #3730a3; }
        .status-approved { background: #dcfce7; color: #166534; }
        .status-not_started { background: #f1f5f9; color: #475569; }

        .card-body { padding: 0 24px 24px 24px; flex-grow: 1; }
        .card-body h3 { margin: 8px 0; font-size: 1.25rem; font-weight: 700; color: #0f172a; }

        .btn-enter { 
            margin: 0 24px 24px 24px;
            padding: 14px; 
            border-radius: 14px;
            text-decoration: none; 
            font-weight: 700; 
            font-size: 0.9rem;
            text-align: center;
            transition: 0.2s; 
            background: #f8fafc;
            color: var(--text-dark);
            border: 1px solid #e2e8f0;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-enter:hover { background: var(--accent); color: white; border-color: var(--accent); }
        .btn-rejected { background: var(--danger); color: white; border-color: var(--danger); }
        .btn-rejected:hover { background: #dc2626; }
        .btn-approved { background: #f8fafc; color: #94a3b8; pointer-events: none; border-style: dashed; }

        @media (max-width: 1024px) {
            .sidebar { transform: translateX(-100%); transition: 0.3s; }
            .sidebar.active { transform: translateX(0); }
            .main { margin-left: 0; padding: 30px; }
        }
    </style>
</head>
<body>

<div class="sidebar" id="sidebar">
    <div class="sidebar-brand">
        <img src="../assets/img/logo.png" class="sidebar-logo" onerror="this.src='https://ui-avatars.com/api/?name=<?= urlencode($school_name) ?>&background=3b82f6&color=fff'">
        <h2 style="font-size: 15px; margin: 0; font-weight: 800;"><?= htmlspecialchars($school_name) ?></h2>
    </div>
    <div class="sidebar-user">
        <img src="https://ui-avatars.com/api/?name=<?= urlencode($_SESSION['name']) ?>&background=3b82f6&color=fff">
        <p style="margin: 0; font-size: 10px; font-weight: 700; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em;">Instructor</p>
        <strong style="font-size: 16px; color: white;"><?= htmlspecialchars($_SESSION['name']) ?></strong>
    </div>
    <ul class="nav-links">
        <li><a href="dashboard.php" class="active"><i class="fa-solid fa-house-chimney"></i> Dashboard</a></li>
        <li><a href="manage_exams.php"><i class="fa-solid fa-file-signature"></i> Question Bank</a></li>
        <li style="margin-top: auto; padding-bottom: 20px;">
            <a href="../auth/logout.php" style="color:#fb7185;"><i class="fa-solid fa-right-from-bracket"></i> Logout</a>
        </li>
    </ul>
</div>

<div class="main">
    <div class="header-flex">
        <div>
            <h1>Overview</h1>
            <p style="color: var(--text-light); margin: 4px 0 0 0; font-size: 0.95rem;">Manage your assigned classes and result submissions.</p>
        </div>
        <div class="session-badge">
            <small style="color: var(--text-light); font-weight: 700; font-size: 9px; display: block; margin-bottom: 2px; text-transform: uppercase;">Current Academic Period</small>
            <strong style="color: var(--accent); font-size: 0.95rem;"><?= htmlspecialchars($current_session) ?> &bull; <?= htmlspecialchars($current_term) ?></strong>
        </div>
    </div>

    
    <div class="summary-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background: #fef2f2; color: var(--danger);"><i class="fa-solid fa-circle-exclamation"></i></div>
            <div><small style="color: var(--text-light); font-weight: 600; font-size: 0.85rem;">Rejected</small><h2 style="margin:0;"><?= $res_stats['rejected'] ?></h2></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background: #eff6ff; color: var(--accent);"><i class="fa-solid fa-clock-rotate-left"></i></div>
            <div><small style="color: var(--text-light); font-weight: 600; font-size: 0.85rem;">Pending Review</small><h2 style="margin:0;"><?= $res_stats['pending'] ?></h2></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background: #f0fdf4; color: var(--success);"><i class="fa-solid fa-circle-check"></i></div>
            <div><small style="color: var(--text-light); font-weight: 600; font-size: 0.85rem;">Approved</small><h2 style="margin:0;"><?= $res_stats['approved'] ?></h2></div>
        </div>
    </div>

    <div class="grid">
        <?php if(count($my_assignments) > 0): ?>
            <?php foreach($my_assignments as $row): 
                $status = $row['result_status'] ?? 'not_started';
                $status_label = str_replace('_', ' ', strtoupper($status));
                
                $btn_extra_class = "";
                if($status == 'rejected') $btn_extra_class = "btn-rejected";
                if($status == 'approved') $btn_extra_class = "btn-approved";
            ?>
            <div class="assignment-card" style="<?= ($status == 'rejected') ? 'border-top: 4px solid var(--danger);' : '' ?>">
                <div class="card-top">
                    <span class="class-badge"><?= htmlspecialchars($row['class_name']) ?></span>
                    <span class="status-pill status-<?= $status ?>"><?= $status_label ?></span>
                </div>
                <div class="card-body">
                    <h3><?= htmlspecialchars($row['subject_name']) ?></h3>
                    <?php if($status == 'rejected'): ?>
                        <div style="background: #fff1f2; padding: 12px; border-radius: 12px; border-left: 4px solid var(--danger); margin-top: 12px;">
                           <p style="font-size: 11px; color: #991b1b; margin: 0; font-weight: 600; line-height: 1.4;">
                               <i class="fa-solid fa-triangle-exclamation"></i> Action required. Admin requested corrections.
                           </p>
                        </div>
                    <?php endif; ?>
                </div>
                
                <a href="enter_scores.php?class_id=<?= $row['class_id'] ?>&subject_id=<?= $row['subject_id'] ?>&subject_name=<?= urlencode($row['subject_name']) ?>&session=<?= urlencode($current_session) ?>&term=<?= urlencode($current_term) ?>" 
                   class="btn-enter <?= $btn_extra_class ?>">
                    <?php if($status == 'approved'): ?>
                        <i class="fa-solid fa-lock"></i> Finalized
                    <?php elseif($status == 'rejected'): ?>
                        <i class="fa-solid fa-pen-to-square"></i> Fix & Re-submit
                    <?php else: ?>
                        <i class="fa-solid fa-arrow-right-to-bracket"></i> Manage Scores
                    <?php endif; ?>
                </a>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div style="grid-column: 1/-1; background: white; padding: 80px 20px; text-align: center; border-radius: 30px; border: 2px dashed #e2e8f0;">
                <i class="fa-solid fa-folder-open" style="font-size: 3rem; color: #cbd5e1; margin-bottom: 20px;"></i>
                <h3 style="color: #64748b; margin: 0;">No Subjects Assigned</h3>
                <p style="color: #94a3b8; margin-top: 8px;">Please contact the administrator for course allocation.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    // Auto-refresh logic (5 mins)
    setTimeout(() => window.location.reload(), 300000); 

    function toggleSidebar() { 
        document.getElementById('sidebar').classList.toggle('active'); 
    }
</script>
</body>
</html>