{% extends 'base.html' %}
{% load i18n static %}

{% block title %}{% trans "Student Registration" %}{% endblock %}

{% block content %}
<div class="container hero-section">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="glass-card p-4 p-md-5">
                <div class="text-center mb-5">
                    <h2 class="text-primary fw-bold">{% trans "Create Your Account" %}</h2>
                    <p class="text-muted">{% trans "Join our learning platform today" %}</p>
                </div>
                
                <form method="post" enctype="multipart/form-data" id="registrationForm" class="needs-validation">
                    {% csrf_token %}
                    
                    {% if form.errors %}
                    <div class="alert alert-danger mb-4">
                        <ul class="mb-0">
                        {% for field in form %}
                            {% for error in field.errors %}
                                <li>{{ field.label }}: {{ error }}</li>
                            {% endfor %}
                        {% endfor %}
                        {% for error in form.non_field_errors %}
                            <li>{{ error }}</li>
                        {% endfor %}
                        </ul>
                    </div>
                    {% endif %}

                    <!-- Section: Personal Info -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-body p-4">
                            <h5 class="card-title text-primary mb-3"><i class="fas fa-user-circle me-2"></i>{% trans "Personal Information" %}</h5>
                            
                            <div class="form-floating mb-3">
                                {{ form.full_name }}
                                <label for="{{ form.full_name.id_for_label }}">{% trans "Full Name" %}</label>
                            </div>
                            
                            <div class="form-floating mb-3">
                                {{ form.username }}
                                <label for="{{ form.username.id_for_label }}">{% trans "Username" %}</label>
                            </div>
                            
                            <div class="form-floating mb-3">
                                {{ form.email }}
                                <label for="{{ form.email.id_for_label }}">{% trans "Email Address" %}</label>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <div class="form-floating">
                                        {{ form.password }}
                                        <label for="{{ form.password.id_for_label }}">{% trans "Password" %}</label>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <div class="form-floating">
                                        {{ form.password_confirm }}
                                        <label for="{{ form.password_confirm.id_for_label }}">{% trans "Confirm Password" %}</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Section: Student Details -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-body p-4">
                            <h5 class="card-title text-primary mb-3"><i class="fas fa-id-card me-2"></i>{% trans "Student Profile" %}</h5>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <div class="form-floating">
                                        {{ form.mobile_number }}
                                        <label for="{{ form.mobile_number.id_for_label }}">{% trans "Mobile Number" %}</label>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <div class="form-floating">
                                        {{ form.governorate }}
                                        <label for="{{ form.governorate.id_for_label }}">{% trans "Governorate" %}</label>
                                    </div>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <div class="form-floating">
                                        {{ form.city }}
                                        <label for="{{ form.city.id_for_label }}">{% trans "City" %}</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Section: Education -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-body p-4">
                            <h5 class="card-title text-primary mb-3"><i class="fas fa-graduation-cap me-2"></i>{% trans "Education" %}</h5>
                            <div class="mb-3">
                                <label class="form-label text-muted small">{% trans "Select Classroom" %}</label>
                                {{ form.classroom }}
                            </div>

                            <div class="mb-3">
                                <label class="form-label text-muted small">{% trans "Select Subjects" %}</label>
                                <div id="subjects-container" class="border p-3 rounded bg-light" style="min-height: 100px;">
                                    <p class="text-muted text-center mt-3 small"><i class="fas fa-chalkboard me-1"></i> {% trans "Select a classroom first." %}</p>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center p-3 bg-primary bg-opacity-10 text-primary rounded">
                                <h5 class="m-0">{% trans "Total Amount:" %}</h5>
                                <h4 class="m-0 fw-bold"><span id="total-amount">0.00</span></h4>
                            </div>
                        </div>
                    </div>

                    <!-- Section: Photo -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-body p-4">
                            <h5 class="card-title text-primary mb-3"><i class="fas fa-camera me-2"></i>{% trans "Profile Picture" %}</h5>
                            <div class="row">
                                <div class="col-md-6 d-flex flex-column align-items-center mb-3 mb-md-0">
                                    <label class="mb-2 text-muted small">{% trans "Webcam Capture" %}</label>
                                    <div id="video-container" style="position: relative;" class="shadow-sm rounded overflow-hidden">
                                        <video id="video" width="240" height="180" autoplay style="background: #000;"></video>
                                        <button type="button" id="snap" class="btn btn-sm btn-light position-absolute bottom-0 start-50 translate-middle-x mb-2 rounded-pill px-3">
                                            <i class="fas fa-camera"></i> {% trans "Snap" %}
                                        </button>
                                    </div>
                                </div>
                                <div class="col-md-6 d-flex flex-column align-items-center">
                                    <label class="mb-2 text-muted small">{% trans "Preview" %}</label>
                                    <canvas id="canvas" width="240" height="180" style="display:none;"></canvas>
                                    <div id="preview-placeholder" class="bg-light rounded d-flex align-items-center justify-content-center text-muted small" style="width: 240px; height: 180px; border: 2px dashed #ddd;">
                                        {% trans "No photo" %}
                                    </div>
                                    <img id="photo-preview" width="240" height="180" class="rounded shadow-sm" style="display:none; border: 2px solid #4ECDC4;">
                                </div>
                            </div>
                            <div class="mt-4">
                                 <label class="form-label text-muted small">{% trans "Or upload file:" %}</label>
                                 {{ form.avatar }}
                            </div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary w-100 py-3 fs-5 fw-bold shadow-sm rounded-pill">
                        {% trans "Complete Registration" %} <i class="fas fa-check-circle ms-2"></i>
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 1. Classroom & Subjects Logic
    const classroomSelect = document.getElementById('id_classroom');
    const subjectsContainer = document.getElementById('subjects-container');
    const totalAmountSpan = document.getElementById('total-amount');

    classroomSelect.addEventListener('change', function() {
        const classroomId = this.value;
        if (!classroomId) {
            subjectsContainer.innerHTML = '<p class="text-muted text-center mt-3 small"><i class="fas fa-chalkboard me-1"></i> {% trans "Select a classroom first." %}</p>';
            updateTotal();
            return;
        }

        fetch(`{% url 'get_classroom_subjects' %}?classroom_id=${classroomId}`)
            .then(response => response.json())
            .then(data => {
                subjectsContainer.innerHTML = '';
                if (data.length === 0) {
                    subjectsContainer.innerHTML = '<p class="text-warning text-center small">{% trans "No subjects found for this classroom." %}</p>';
                } else {
                    data.forEach(subject => {
                        const price = parseFloat(subject.price) || 0;
                        const div = document.createElement('div');
                        div.className = 'form-check mb-2 bg-white p-2 rounded border';
                        div.innerHTML = `
                            <input class="form-check-input subject-checkbox" type="checkbox" name="subjects" value="${subject.id}" id="subject_${subject.id}" data-price="${price}" checked style="transform: scale(1.2); margin-top: 0.3rem;">
                            <label class="form-check-label d-flex justify-content-between w-100 ms-2" for="subject_${subject.id}">
                                <span class="fw-medium">${subject.name_en}</span>
                                <span class="badge bg-primary rounded-pill align-self-center">${price.toFixed(2)}</span>
                            </label>
                        `;
                        subjectsContainer.appendChild(div);
                    });
                    updateTotal();
                }
            })
            .catch(err => {
                console.error('Error fetching subjects:', err);
                subjectsContainer.innerHTML = '<p class="text-danger small">{% trans "Error loading subjects." %}</p>';
            });
    });

    subjectsContainer.addEventListener('change', function(e) {
        if (e.target.classList.contains('subject-checkbox')) {
            updateTotal();
        }
    });

    function updateTotal() {
        let total = 0;
        document.querySelectorAll('.subject-checkbox:checked').forEach(cb => {
            total += parseFloat(cb.dataset.price) || 0;
        });
        totalAmountSpan.textContent = total.toFixed(2);
    }

    // 2. Governorate & City Logic
    const governorateSelect = document.getElementById('id_governorate');
    const citySelect = document.getElementById('id_city');

    if (governorateSelect && citySelect) {
        governorateSelect.addEventListener('change', function() {
            const governorateId = this.value;
            citySelect.innerHTML = '<option value="">{% trans "Loading..." %}</option>';
            
            if (!governorateId) {
                citySelect.innerHTML = '<option value="">---------</option>';
                return;
            }

            fetch(`{% url 'get_cities_by_governorate' %}?governorate_id=${governorateId}`)
                .then(response => response.json())
                .then(data => {
                    citySelect.innerHTML = '<option value="">---------</option>';
                    const currentLang = "{{ LANGUAGE_CODE }}";
                    data.forEach(city => {
                        const option = document.createElement('option');
                        option.value = city.id;
                        option.textContent = currentLang === 'ar' ? city.name_ar : city.name_en;
                        citySelect.appendChild(option);
                    });
                })
                .catch(err => {
                    console.error('Error fetching cities:', err);
                    citySelect.innerHTML = '<option value="">{% trans "Error loading cities" %}</option>';
                });
        });
    }

    // 3. Webcam Logic
    const video = document.getElementById('video');
    const videoContainer = document.getElementById('video-container');
    const canvas = document.getElementById('canvas');
    const snap = document.getElementById('snap');
    const photoPreview = document.getElementById('photo-preview');
    const previewPlaceholder = document.getElementById('preview-placeholder');
    const avatarInput = document.getElementById('id_avatar');

    function showCameraError(message) {
        videoContainer.innerHTML = `
            <div class="alert alert-light p-2 small text-center text-muted" style="height: 180px; display: flex; flex-direction: column; justify-content: center; align-items: center;">
                <i class="fas fa-video-slash mb-2" style="font-size: 1.5rem;"></i>
                <div>${message}</div>
            </div>
        `;
    }

    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(function(stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function(err) {
                showCameraError("{% trans 'Camera access denied or unavailable.' %}");
            });
    } else {
        showCameraError("{% trans 'Browser does not support camera.' %}");
    }

    if (snap) {
        snap.addEventListener('click', function() {
            if (video.srcObject) {
                const context = canvas.getContext('2d');
                context.drawImage(video, 0, 0, 240, 180);
                canvas.toBlob(function(blob) {
                    const file = new File([blob], "webcam_capture.jpg", { type: "image/jpeg" });
                    const dataTransfer = new DataTransfer();
                    dataTransfer.items.add(file);
                    avatarInput.files = dataTransfer.files;
                    const url = URL.createObjectURL(blob);
                    photoPreview.src = url;
                    photoPreview.style.display = 'block';
                    previewPlaceholder.style.display = 'none';
                }, 'image/jpeg', 0.95);
            }
        });
    }
});
</script>
{% endblock %}
