<?php
/**
 * Student Registration Page - TutorKita System
 * Updated: SweetAlert2 Success Message
 */

require_once 'db.php';

$portalName = 'TutorKita';
$portalTagline = 'Platform Pembelajaran Terbaik';
$portalLogo = '';
$portalFavicon = 'favicon.ico';
$themeColor = '#667eea';

try {
    $stmt = $pdo->query("SELECT portal_name, portal_tagline, theme_color, portal_logo, portal_favicon FROM admin LIMIT 1");
    $settings = $stmt->fetch();
    if ($settings) {
        $portalName = $settings['portal_name'] ?: $portalName;
        $portalTagline = $settings['portal_tagline'] ?: $portalTagline;
        $themeColor = $settings['theme_color'] ?: '#667eea';
        $portalLogo = $settings['portal_logo'] ?: '';
        $portalFavicon = $settings['portal_favicon'] ?: 'favicon.ico';
    }
} catch (Exception $e) {
}

$teacherId = isset($_GET['teacher_id']) ? (int) $_GET['teacher_id'] : 0;
?>
<!DOCTYPE html>
<html lang="ms">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daftar Pelajar - <?php echo htmlspecialchars($portalName); ?></title>
    <link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($portalFavicon); ?>">

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        /* Back Button Style */
        .back-btn {
            position: absolute;
            top: 15px;
            left: 15px;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 8px 16px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-size: 0.9rem;
            font-weight: 500;
            transition: all 0.3s ease;
            z-index: 10;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .back-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateX(-3px);
        }

        .back-btn:focus {
            outline: 2px solid white;
            outline-offset: 2px;
        }

        @media (max-width: 480px) {
            .back-btn {
                position: relative;
                top: 0;
                left: 0;
                margin-bottom: 15px;
                width: 100%;
                justify-content: center;
            }
        }

        :root {
            --primary-color:
                <?php echo $themeColor; ?>
            ;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .register-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 700px;
            width: 100%;
            margin: 0 auto;
            overflow: hidden;
            animation: slideUp 0.5s ease;
        }

        @keyframes slideUp {
            from {
                transform: translateY(30px);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .register-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .logo {
            font-size: 4rem;
            margin-bottom: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .logo img {
            max-width: 120px;
            height: auto;
            object-fit: contain;
            filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.2));
        }

        .register-header h1 {
            font-size: 1.8rem;
            margin-bottom: 5px;
        }

        .register-header p {
            opacity: 0.9;
        }

        .register-body {
            padding: 30px;
        }

        .form-section {
            margin-bottom: 25px;
        }

        .form-section-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid rgba(102, 126, 234, 0.2);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group label .required {
            color: #dc3545;
        }

        .form-control {
            width: 100%;
            padding: 14px 18px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15);
        }

        .form-select {
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23718096' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 15px center;
            padding-right: 45px;
        }

        .form-check {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .form-check:hover {
            background: rgba(102, 126, 234, 0.1);
        }

        .form-check-input {
            width: 20px;
            height: 20px;
            margin-right: 12px;
            cursor: pointer;
            accent-color: var(--primary-color);
        }

        .subjects-container {
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            padding: 15px 30px;
            font-size: 1.1rem;
            font-weight: 600;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color) 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }

        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .login-link {
            text-align: center;
            margin-top: 25px;
            padding-top: 25px;
            border-top: 1px solid #e0e0e0;
        }

        .login-link a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 600;
        }

        .login-link a:hover {
            text-decoration: underline;
        }

        .alert {
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: none;
        }

        .alert.error {
            background: #fee2e2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }

        .alert.success {
            background: #dcfce7;
            color: #16a34a;
            border: 1px solid #bbf7d0;
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .info-box {
            background: rgba(102, 126, 234, 0.1);
            border-left: 4px solid var(--primary-color);
            padding: 15px;
            border-radius: 0 10px 10px 0;
            margin-bottom: 20px;
        }

        .info-box p {
            margin: 0;
            color: #555;
            font-size: 0.9rem;
        }


        @media (max-width: 480px) {
            .register-container {
                border-radius: 15px;
            }

            .register-header {
                padding: 20px;
            }

            .logo {
                font-size: 3rem;
            }

            .register-body {
                padding: 20px;
            }
        }
    </style>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>
    <!-- Back Button to Login Page -->
    <a href="index.php" class="back-btn">
        ← Kembali
    </a>

    <div class="register-container">
        <div class="register-header">
            <div class="logo">
                <?php if (!empty($portalLogo)): ?>
                    <img src="<?php echo htmlspecialchars($portalLogo); ?>" alt="Logo">
                <?php else: ?>
                    📚
                <?php endif; ?>
            </div>
            <h1><?php echo htmlspecialchars($portalName); ?></h1>
            <p><?php echo htmlspecialchars($portalTagline); ?></p>
        </div>

        <div class="register-body">
            <div class="alert" id="alertMessage"></div>

            <div class="info-box">
                <p>📝 <strong>Pendaftaran Pelajar Baru</strong><br>Sila isi maklumat di bawah. Kata laluan akan
                    diberikan oleh guru selepas kelulusan.</p>
            </div>

            <form id="registerForm" onsubmit="handleRegister(event)">
                <?php if ($teacherId > 0): ?>
                    <input type="hidden" name="enrolled_by" value="<?php echo $teacherId; ?>">
                    <div class="alert alert-info py-2 mb-3" style="font-size: 0.85rem;">
                        👤 Pendaftaran ini akan dipantau oleh Guru ID: <?php echo $teacherId; ?>
                    </div>
                <?php endif; ?>
                <div class="form-section">
                    <h3 class="form-section-title">👤 Maklumat Peribadi</h3>
                    <div class="form-group">
                        <label class="form-label">Nama Penuh Pelajar <span class="required">*</span></label>
                        <input type="text" class="form-control" name="full_name" id="fullName" required
                            placeholder="cth: Ali Bin Abu">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Umur (5-25 tahun) <span class="required">*</span></label>
                        <input type="number" class="form-control" name="age" id="age" required min="5" max="25"
                            placeholder="cth: 12">
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="form-section-title">👨‍👩‍👧 Maklumat Penjaga</h3>
                    <div class="form-group">
                        <label class="form-label">Nama Ibu Bapa/Penjaga <span class="required">*</span></label>
                        <input type="text" class="form-control" name="parent_guardian_name" required
                            placeholder="cth: Abu Bin Said">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Nombor Telefon <span class="required">*</span></label>
                        <input type="tel" class="form-control" name="phone" required placeholder="cth: 012-3456789"
                            pattern="[\d\-\+\s]{10,}">
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="form-section-title">🎓 Maklumat Pendidikan</h3>
                    <div class="form-group">
                        <label class="form-label">Tahap Pendidikan <span class="required">*</span></label>
                        <select class="form-control form-select" name="education_level" id="educationLevel"
                            onchange="updateGradeLevel()" required>
                            <option value="">Pilih Tahap</option>
                            <option value="Sekolah Rendah">Sekolah Rendah</option>
                            <option value="Sekolah Menengah">Sekolah Menengah</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Tahun/Tingkatan <span class="required">*</span></label>
                        <select class="form-control form-select" name="grade_level" id="gradeLevel" required>
                            <option value="">Pilih Tahap Dahulu</option>
                        </select>
                    </div>
                </div>

                <div class="form-section">
                    <h3 class="form-section-title">📚 Subjek yang Diperlukan <span class="required">*</span></h3>
                    <p class="form-text" style="margin-bottom: 15px;">Pilih sekurang-kurangnya satu subjek:</p>
                    <div class="subjects-container" id="subjectsChecklist">
                        <p class="text-center">Memuatkan subjek...</p>
                    </div>
                    <div id="subjectError" class="form-text" style="color: #dc3545; display: none; margin-top: 10px;">
                        Sila pilih sekurang-kurangnya satu subjek</div>
                </div>

                <button type="submit" class="btn btn-primary" id="submitBtn">
                    📝 Daftar Sekarang
                </button>
            </form>

            <div class="login-link">
                <p>Sudah mempunyai akaun Pelajar? <a href="index.php">Log Masuk</a></p>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            loadSubjects();
        });

        async function loadSubjects() {
            try {
                var response = await fetch('api.php?action=get_subjects');
                var result = await response.json();
                var container = document.getElementById('subjectsChecklist');

                if (result.success && result.subjects.length > 0) {
                    var html = '';
                    for (var i = 0; i < result.subjects.length; i++) {
                        var subject = result.subjects[i];
                        html += '<label class="form-check">' +
                            '<input type="checkbox" class="form-check-input subject-checkbox" name="required_subjects[]" value="' + subject.subject_name + '" onchange="validateSubjects()">' +
                            '<span class="form-check-label">' + subject.subject_name + '</span>' +
                            '</label>';
                    }
                    container.innerHTML = html;
                } else {
                    container.innerHTML = '<p class="text-center text-muted">Tiada subjek tersedia</p>';
                }
            } catch (error) {
                document.getElementById('subjectsChecklist').innerHTML = '<p class="text-center text-danger">Ralat memuatkan subjek</p>';
            }
        }


        function updateGradeLevel() {
            var educationLevel = document.getElementById('educationLevel').value;
            var gradeLevel = document.getElementById('gradeLevel');
            var options = '<option value="">Pilih Tahun/Tingkatan</option>';
            if (educationLevel === 'Sekolah Rendah') {
                for (var i = 1; i <= 6; i++) { options += '<option value="Tahun ' + i + '">Tahun ' + i + '</option>'; }
            } else if (educationLevel === 'Sekolah Menengah') {
                for (var i = 1; i <= 5; i++) { options += '<option value="Tingkatan ' + i + '">Tingkatan ' + i + '</option>'; }
            }
            gradeLevel.innerHTML = options;
        }

        function validateSubjects() {
            var checkboxes = document.querySelectorAll('.subject-checkbox:checked');
            var errorMsg = document.getElementById('subjectError');
            var submitBtn = document.getElementById('submitBtn');
            if (checkboxes.length === 0) {
                errorMsg.style.display = 'block';
                submitBtn.disabled = true;
            } else {
                errorMsg.style.display = 'none';
                submitBtn.disabled = false;
            }
        }

        function showAlert(message, type) {
            var alertEl = document.getElementById('alertMessage');
            alertEl.className = 'alert ' + type;
            alertEl.textContent = message;
            alertEl.style.display = 'block';
            setTimeout(function () { alertEl.style.display = 'none'; }, 5000);
        }

        async function handleRegister(event) {
            event.preventDefault();

            var checkboxes = document.querySelectorAll('.subject-checkbox:checked');
            if (checkboxes.length === 0) {
                showAlert('Sila pilih sekurang-kurangnya satu subjek!', 'error');
                return;
            }

            var submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="loading-spinner"></span> Sedang Memproses...';

            var formData = new FormData(document.getElementById('registerForm'));
            formData.append('action', 'register_student_pending');

            try {
                var response = await fetch('api.php', {
                    method: 'POST',
                    body: formData
                });

                var text = await response.text();
                var result;
                try {
                    result = JSON.parse(text);
                } catch (e) {
                    console.error("Raw Response:", text);
                    Swal.fire('Ralat!', 'Respon pelayan tidak sah (Bukan JSON). Sila semak konsol.', 'error');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '📝 Daftar Sekarang';
                    return;
                }

                if (result.success) {
                    // --- MESEJ BERJAYA CANTIK (SWEETALERT2) ---
                    Swal.fire({
                        title: result.title || 'Tahniah! Pendaftaran Berjaya 🎉',
                        html: `
                            <div style="text-align:center">
                                <p style="color:#555; margin-bottom:15px;">${result.message}</p>
                                <div style="background: #f8f9fa; border: 2px dashed var(--primary-color); padding: 15px; border-radius: 12px; margin: 15px 0;">
                                    <small style="color: #888; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 1px;">Username Anda</small>
                                    <h2 style="color: var(--primary-color); margin: 5px 0 0 0; font-weight: 800;">${result.username}</h2>
                                </div>
                                <p style="font-size: 0.85rem; color: #dc3545; margin-top: 10px;">*Sila simpan username ini untuk rujukan.</p>
                            </div>
                        `,
                        icon: 'success',
                        confirmButtonText: 'Faham, Kembali ke Login',
                        confirmButtonColor: 'var(--primary-color)',
                        background: '#fff',
                        borderRadius: '15px',
                        allowOutsideClick: false
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = 'index.php';
                        }
                    });

                    document.getElementById('registerForm').reset();

                } else {
                    // Error Style
                    Swal.fire({
                        title: 'Ralat!',
                        text: result.message,
                        icon: 'error',
                        confirmButtonColor: '#dc3545',
                        borderRadius: '15px'
                    });
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '📝 Daftar Sekarang';
                }
            } catch (error) {
                Swal.fire('Ralat!', 'Masalah sambungan server.', 'error');
                submitBtn.disabled = false;
                submitBtn.innerHTML = '📝 Daftar Sekarang';
            }
        }
    </script>
</body>

</html>