<?php
/**
 * IBVTE College - Result & Marks Management
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

$collegePage = 'results';
Auth()->requireRole(['college']);

$db = DB();
$user = Auth()->getUser();
$flash = getFlashMessage();

// Handle Practical Marks Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_marks') {
    $studentId = intval($_POST['student_id'] ?? 0);
    $practicalMarks = floatval($_POST['practical_marks'] ?? 0);
    
    // Check if student belongs to this college
    $student = $db->fetchOne("SELECT id FROM students WHERE id = ? AND institution_id = ?", [$studentId, $user['id']]);
    
    if ($student) {
        $max_marks = 100;
        $percentage = ($practicalMarks / $max_marks) * 100;
        $division = 'fail';
        
        if ($percentage >= 60) {
            $division = 'first';
        } elseif ($percentage >= 45) {
            $division = 'second';
        } elseif ($percentage >= 30) {
            $division = 'third';
        }

        $db->update('students', [
            'marks_obtained' => $practicalMarks,
            'total_marks' => $max_marks,
            'percentage' => $percentage,
            'division' => $division
        ], ['id' => $studentId]);
        
        redirectWithMessage('results.php', 'Practical marks saved and division calculated successfully.', 'success');
    }
}

// Fetch Students for Result Management
// Only students with 'active' status can have marks entered
$students = $db->fetchAll("
    SELECT s.*, c.course_name, c.course_code 
    FROM students s 
    JOIN courses c ON s.course_id = c.id 
    WHERE s.institution_id = ? 
    ORDER BY s.full_name ASC
", [$user['id']]);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Results & Marks - College Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        /* ── College Sidebar ─────────────────────────── */
        :root { --primary:#3b0b7c; --secondary:#6c4ab6; }
        .college-sidebar {
            width: 250px;
            background: white;
            min-height: 100vh;
            position: fixed;
            top: 0; left: 0;
            display: flex;
            flex-direction: column;
            box-shadow: 3px 0 15px rgba(59,11,124,0.08);
            z-index: 1040;
            transition: transform .3s;
        }
        .sidebar-brand {
            padding: 28px 20px 20px;
            text-align: center;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
        }
        .sidebar-logo {
            width: 68px; height: 68px;
            border-radius: 50%;
            border: 3px solid rgba(255,255,255,.35);
            object-fit: cover;
            margin-bottom: 12px;
        }
        .sidebar-college-name {
            color: white;
            font-weight: 700;
            font-size: .9rem;
            line-height: 1.3;
        }
        .sidebar-code {
            color: rgba(255,255,255,.65);
            font-size: .75rem;
            margin-top: 4px;
        }
        .sidebar-nav {
            flex: 1;
            padding: 16px 12px;
            overflow-y: auto;
        }
        .sidebar-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 11px 16px;
            border-radius: 10px;
            color: #555;
            text-decoration: none;
            font-size: .9rem;
            font-weight: 500;
            margin-bottom: 4px;
            transition: background .2s, color .2s, transform .15s;
        }
        .sidebar-link:hover {
            background: #f0ebf8;
            color: var(--primary);
            transform: translateX(3px);
        }
        .sidebar-link.active {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white !important;
            box-shadow: 0 4px 12px rgba(59,11,124,.25);
        }
        .sidebar-icon { width: 18px; text-align: center; flex-shrink: 0; font-size: .95rem; }
        .sidebar-footer { padding: 12px; border-top: 1px solid #f0f0f0; }
        .sidebar-logout { color: #dc3545 !important; }
        .sidebar-logout:hover { background: #fff0f0; color: #dc3545 !important; }
        .college-main { margin-left: 250px; padding: 30px; min-height: 100vh; background: #f8f9fa; }
        @media (max-width: 768px) {
            .college-sidebar { transform: translateX(-100%); }
            .college-sidebar.open { transform: translateX(0); }
            .college-main { margin-left: 0; padding: 20px 15px; }
            .mobile-menu-btn { display: flex !important; }
        }

        :root { --primary: #3b0b7c; --secondary: #6c4ab6; }
        body { background: #f8f9fa; font-family: 'Inter', sans-serif; }
        .sidebar { width: 250px; background: white; min-height: 100vh; position: fixed; box-shadow: 2px 0 10px rgba(0,0,0,0.05); }
        .main-content { margin-left: 250px; padding: 30px; }
        .nav-link-item { padding: 12px 25px; display: block; color: #555; text-decoration: none; transition: 0.3s; margin: 4px 15px; border-radius: 10px; }
        .nav-link-item:hover, .nav-link-item.active { background: var(--primary); color: white; }
        .card-custom { border-radius: 15px; border: none; box-shadow: 0 5px 20px rgba(0,0,0,0.05); }
    </style>
</head>
<body>

<?php include __DIR__ . '/../includes/college_sidebar.php'; ?>
<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Exam & Result Management</h3>
    </div>

    <?php if ($flash): ?>
        <div class="alert alert-<?= $flash['type'] ?> border-0 shadow-sm"><?= $flash['message'] ?></div>
    <?php endif; ?>

    <div class="card card-custom p-4">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="bg-light">
                    <tr>
                        <th>Student Name</th>
                        <th>Course</th>
                        <th>Reg. No</th>
                        <th>Marks Obtained</th>
                        <th>Division</th>
                        <th>Result Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($students)): ?>
                        <tr><td colspan="7" class="text-center py-5">No students found</td></tr>
                    <?php else: ?>
                        <?php foreach ($students as $s): ?>
                        <tr>
                            <td>
                                <div class="fw-bold"><?= htmlspecialchars($s['full_name']) ?></div>
                                <div class="small text-muted">Roll: <?= htmlspecialchars($s['roll_number'] ?: 'N/A') ?></div>
                            </td>
                            <td>
                                <div class="small fw-bold"><?= htmlspecialchars($s['course_code']) ?></div>
                                <div class="extra-small text-muted text-truncate" style="max-width: 150px;"><?= htmlspecialchars($s['course_name']) ?></div>
                            </td>
                            <td class="small"><?= htmlspecialchars($s['registration_number'] ?: 'PENDING') ?></td>
                            <td>
                                <div class="fw-bold text-primary"><?= $s['marks_obtained'] ?: '0.00' ?> / <?= $s['total_marks'] ?: '100' ?></div>
                            </td>
                            <td>
                                <span class="badge bg-light text-dark border"><?= $s['division'] ?: 'N/A' ?></span>
                            </td>
                            <td>
                                <?php if ($s['result_declared']): ?>
                                    <span class="badge bg-success">Declared</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Pending</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#marksModal<?= $s['id'] ?>">
                                    <i class="fas fa-edit"></i> Marks
                                </button>
                            </td>
                        </tr>

                        <!-- Marks Modal -->
                        <div class="modal fade" id="marksModal<?= $s['id'] ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content border-0 shadow rounded-4">
                                    <div class="modal-header border-bottom py-3">
                                        <h5 class="modal-title fw-bold">Enter Practical Marks</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <form method="POST">
                                        <div class="modal-body p-4">
                                            <input type="hidden" name="action" value="save_marks">
                                            <input type="hidden" name="student_id" value="<?= $s['id'] ?>">
                                            
                                            <div class="mb-3">
                                                <label class="fw-bold small mb-2">Student Name</label>
                                                <input type="text" class="form-control bg-light" value="<?= htmlspecialchars($s['full_name']) ?>" readonly>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="fw-bold small mb-2">Practical Marks Obtained (Max 100)</label>
                                                <input type="number" name="practical_marks" class="form-control" value="<?= $s['marks_obtained'] ?>" step="0.1" max="100" required>
                                            </div>
                                        </div>
                                        <div class="modal-footer border-0">
                                            <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                            <button type="submit" class="btn btn-primary px-4 fw-bold">Save Marks</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
function toggleSidebar() {
    const sb = document.getElementById('collegeSidebar');
    const ov = document.getElementById('sidebarOverlay');
    sb.classList.toggle('open');
    ov.classList.toggle('d-none');
}
// On mobile, show menu button
if (window.innerWidth < 768) {
    document.getElementById('mobileMenuBtn').style.display = 'flex';
}
window.addEventListener('resize', function() {
    const btn = document.getElementById('mobileMenuBtn');
    if (btn) btn.style.display = window.innerWidth < 768 ? 'flex' : 'none';
});
</script>

</body>
</html>
