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

{% block title %}
    {{ subject.name_ar }} | EduPlatform
{% endblock %}

{% block content %}
<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0">
                <li class="breadcrumb-item"><a href="{% url 'index' %}">الرئيسية</a></li>
                <li class="breadcrumb-item active" aria-current="page">
                    {{ subject.classroom.name_ar }}
                </li>
            </ol>
        </nav>
        {% if is_teacher %}
        <a href="{% url 'profile' %}" class="btn btn-outline-secondary rounded-pill">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-right me-2" viewBox="0 0 16 16">
              <path fill-rule="evenodd" d="M1 8a.5.5 0 0 1 .5-.5h11.793l-3.147-3.146a.5.5 0 0 1 .708-.708l4 4a.5.5 0 0 1 0 .708l-4 4a.5.5 0 0 1-.708-.708L13.293 8.5H1.5A.5.5 0 0 1 1 8z"/>
            </svg>
            العودة للوحة التحكم
        </a>
        {% endif %}
    </div>

    <div class="row g-5">
        <div class="col-lg-8">
            <div class="glass-card mb-4 overflow-hidden p-0">
                <div style="height: 300px; background: #f8f9fa; display: flex; align-items: center; justify-content: center; position: relative;">
                    {% if subject.image %}
                    <img src="{{ subject.image.url }}" class="img-fluid w-100 h-100 object-fit-cover" alt="{{ subject.name_en }}">
                    {% else %}
                    <span class="display-1" style="opacity: 0.1;">📚</span>
                    {% endif %}
                    <div class="position-absolute top-0 end-0 m-4">
                        <span class="badge bg-primary fs-6 px-3 py-2 shadow-sm">
                            {{ subject.classroom.name_ar }}
                        </span>
                    </div>
                </div>
                <div class="p-4 p-md-5">
                    <h1 class="fw-bold mb-4">
                        {{ subject.name_ar }}
                    </h1>
                    
                    {% for teacher in subject.teachers.all %}
                    <div class="d-flex align-items-center mb-3 p-3 rounded-3 bg-light">
                        <div class="avatar-placeholder me-3" style="width: 50px; height: 50px; background: var(--primary-color); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white;">
                            {{ teacher.user.username|first|upper }}
                        </div>
                        <div>
                            <p class="mb-0 text-muted small">المعلم</p>
                            <h6 class="fw-bold mb-0">{{ teacher }}</h6>
                        </div>
                    </div>
                    {% empty %}
                     <div class="d-flex align-items-center mb-3 p-3 rounded-3 bg-light">
                        <div>
                            <p class="mb-0 text-muted small">المعلم</p>
                            <h6 class="fw-bold mb-0">غير معين</h6>
                        </div>
                    </div>
                    {% endfor %}

                    {% if subject.get_youtube_id %}
                    <div class="mt-5 mb-5">
                        <div class="ratio ratio-16x9 rounded-4 overflow-hidden shadow-sm">
                            <iframe src="https://www.youtube-nocookie.com/embed/{{ subject.get_youtube_id }}?rel=0&playsinline=1" 
                                    title="YouTube video player" 
                                    frameborder="0" 
                                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
                                    referrerpolicy="strict-origin-when-cross-origin"
                                    allowfullscreen>
                            </iframe>
                        </div>
                    </div>
                    {% endif %}

                    <h4 class="fw-bold mb-3 mt-4">عن هذه المادة</h4>
                    <div class="lead text-muted mb-5">
                        {{ subject.description_ar|linebreaks }}
                    </div>
                    
                    <!-- Google Drive Link -->
                    {% if subject.google_drive_link %}
                    <div class="mb-5">
                        <a href="{{ subject.google_drive_link }}" target="_blank" class="btn btn-outline-success btn-lg w-100 p-4 rounded-4 d-flex align-items-center justify-content-between hover-shadow transition-all">
                            <div class="d-flex align-items-center">
                                <div class="me-3 display-6">📂</div>
                                <div class="text-start">
                                    <h5 class="fw-bold mb-1">مجلد المادة على Drive</h5>
                                    <p class="mb-0 small text-muted">الوصول للملفات والمستندات المشتركة</p>
                                </div>
                            </div>
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-box-arrow-up-right" viewBox="0 0 16 16">
                                <path fill-rule="evenodd" d="M8.636 3.5a.5.5 0 0 0-.5-.5H1.5A1.5 1.5 0 0 0 0 4.5v10A1.5 1.5 0 0 0 1.5 16h10a1.5 1.5 0 0 0 1.5-1.5V7.864a.5.5 0 0 0-1 0V14.5a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h6.636a.5.5 0 0 0 .5-.5z"/>
                                <path fill-rule="evenodd" d="M16 .5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0 0 1h3.793L6.146 9.146a.5.5 0 1 0 .708.708L15 1.707V5.5a.5.5 0 0 0 1 0v-5z"/>
                            </svg>
                        </a>
                    </div>
                    {% endif %}

                    <!-- Resources Section -->
                    <div class="mb-5">
                        <div class="d-flex align-items-center justify-content-between mb-4">
                            <div class="d-flex align-items-center">
                                <h4 class="fw-bold mb-0">مصادر الدورة</h4>
                                <span class="badge bg-light text-primary ms-3 border rounded-pill px-3">{{ subject.resources.count }}</span>
                            </div>
                            {% if is_teacher %}
                                <a href="{% url 'add_resource' subject.id %}" class="btn btn-success rounded-pill">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-plus-lg me-2" viewBox="0 0 16 16">
                                      <path fill-rule="evenodd" d="M8 2a.5.5 0 0 1 .5.5v5h5a.5.5 0 0 1 0 1h-5v5a.5.5 0 0 1-1 0v-5h-5a.5.5 0 0 1 0-1h5v-5A.5.5 0 0 1 8 2z"/>
                                    </svg>
                                    إضافة مصدر
                                </a>
                            {% endif %}
                        </div>

                        {% if subject.resources.all %}
                        <div class="list-group list-group-flush border rounded-4 overflow-hidden">
                            {% for resource in subject.resources.all %}
                            <div class="list-group-item p-3 d-flex align-items-center justify-content-between hover-bg-light transition-all">
                                <div class="d-flex align-items-center">
                                    <div class="me-3 p-2 rounded-3 
                                        {% if resource.resource_type == 'VIDEO' %}bg-danger-subtle text-danger
                                        {% elif resource.resource_type == 'FILE' %}bg-primary-subtle text-primary
                                        {% else %}bg-success-subtle text-success{% endif %}">
                                        {% if resource.resource_type == 'VIDEO' %}
                                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-play-circle-fill" viewBox="0 0 16 16">
                                              <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM6.79 5.093A.5.5 0 0 0 6 5.5v5a.5.5 0 0 0 .79.407l3.5-2.5a.5.5 0 0 0 0-.814l-3.5-2.5z"/>
                                            </svg>
                                        {% elif resource.resource_type == 'FILE' %}
                                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-file-earmark-text-fill" viewBox="0 0 16 16">
                                              <path d="M9.293 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.707A1 1 0 0 0 13.793 4L10 0.207A1.5 1.5 0 0 0 9.293 0zM9.5 3.5v-2l3 3h-2a1 1 0 0 1-1-1zM4.5 9a.5.5 0 0 1 0-1h7a.5.5 0 0 1 0 1h-7zM4 10.5a.5.5 0 0 1 .5-.5h7a.5.5 0 0 1 0 1h-7a.5.5 0 0 1-.5-.5zm.5 2.5a.5.5 0 0 1 0-1h4a.5.5 0 0 1 0 1h-4z"/>
                                            </svg>
                                        {% else %}
                                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-link-45deg" viewBox="0 0 16 16">
                                              <path d="M4.715 6.542 3.343 7.914a3 3 0 1 0 4.243 4.243l1.828-1.829A3 3 0 0 0 8.586 5.5L8 6.086a1.002 1.002 0 0 0-.154.199 2 2 0 0 1 .861 3.337L6.88 11.45a2 2 0 1 1-2.83-2.83l.793-.792a4.018 4.018 0 0 1-.128-1.287z"/>
                                              <path d="M6.586 4.672A3 3 0 0 0 7.414 9.5l.775-.776a2 2 0 0 1-.896-3.346L9.12 3.55a2 2 0 1 1 2.83 2.83l-.793.792c.112.42.155.855.128 1.287l1.372-1.372a3 3 0 1 0-4.243-4.243L6.586 4.672z"/>
                                            </svg>
                                        {% endif %}
                                    </div>
                                    <div>
                                        <h6 class="mb-0 fw-semibold">
                                            {{ resource.title_ar }}
                                        </h6>
                                        <small class="text-muted">
                                            {{ resource.get_resource_type_display }}
                                        </small>
                                    </div>
                                </div>
                                <div class="d-flex align-items-center gap-2">
                                    {% if is_teacher %}
                                        <a href="{% url 'edit_resource' resource.id %}" class="btn btn-sm btn-outline-secondary rounded-pill">تعديل</a>
                                        <a href="{% url 'delete_resource' resource.id %}" class="btn btn-sm btn-outline-danger rounded-pill">حذف</a>
                                    {% endif %}
                                    <button class="btn btn-sm btn-outline-primary rounded-pill px-3 view-resource-btn" 
                                            data-type="{{ resource.resource_type }}"
                                            data-title="{{ resource.title_ar }}"
                                            data-file-url="{% if resource.file %}{{ resource.file.url }}{% endif %}"
                                            data-view-url="{% url 'view_resource' resource.id %}"
                                            data-link="{% if resource.link %}{{ resource.link }}{% endif %}"
                                            data-youtube-id="{{ resource.get_youtube_id|default:'' }}">
                                        عرض
                                    </button>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        {% else %}
                        <div class="text-center p-5 bg-light rounded-4">
                            <div class="display-6 mb-3">📂</div>
                            <h6 class="text-muted">لا توجد مصادر متاحة بعد.</h6>
                            {% if is_teacher %}
                                <a href="{% url 'add_resource' subject.id %}" class="btn btn-primary rounded-pill mt-3">
                                    إضافة أول مصدر
                                </a>
                            {% endif %}
                        </div>
                        {% endif %}
                    </div>

                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="sticky-top" style="top: 2rem; z-index: 10;">
                <div class="glass-card shadow-lg border-primary border-top border-4">
                    <div class="p-4">
                        <h3 class="fw-bold text-primary mb-4">${{ subject.price }}</h3>
                        
                        <ul class="list-unstyled mb-4">
                            <li class="mb-3 d-flex align-items-center">
                                <span class="text-success me-2">✓</span> وصول كامل مدى الحياة
                            </li>
                            <li class="mb-3 d-flex align-items-center">
                                <span class="text-success me-2">✓</span> دخول من الهاتف والكمبيوتر
                            </li>
                            <li class="mb-3 d-flex align-items-center">
                                <span class="text-success me-2">✓</span> شهادة إتمام
                            </li>
                        </ul>

                        <button class="btn btn-primary btn-lg w-100 py-3 fw-bold mb-3 shadow-sm">
                            اشترك الآن
                        </button>
                        <p class="text-center text-muted small mb-0">
                            ضمان استرداد الأموال خلال 30 يوم
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Resource Modal -->
<div class="modal fade" id="resourceModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
    <div class="modal-content rounded-4 border-0 shadow-lg" style="height: 90vh;">
      <div class="modal-header border-0 pb-0">
        <h5 class="modal-title fw-bold" id="resourceModalTitle">المصدر</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body p-0" id="resourceModalBody" style="background-color: #f8f9fa;">
        <!-- Content injected via JS -->
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const resourceModal = new bootstrap.Modal(document.getElementById('resourceModal'));
    const modalTitle = document.getElementById('resourceModalTitle');
    const modalBody = document.getElementById('resourceModalBody');

    document.querySelectorAll('.view-resource-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const type = this.dataset.type;
            const title = this.dataset.title;
            const fileUrl = this.dataset.fileUrl;
            const viewUrl = this.dataset.viewUrl;
            const link = this.dataset.link;
            const youtubeId = this.dataset.youtubeId;

            modalTitle.textContent = title;
            modalBody.innerHTML = ''; // Clear previous content

            if (type === 'VIDEO' && youtubeId) {
                // Use youtube-nocookie.com and add referrerpolicy
                modalBody.innerHTML = `
                    <div class="ratio ratio-16x9 h-100">
                        <iframe src="https://www.youtube-nocookie.com/embed/${youtubeId}?autoplay=1&rel=0&playsinline=1" 
                                title="${title}" 
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" 
                                referrerpolicy="strict-origin-when-cross-origin"
                                allowfullscreen></iframe>
                    </div>
                `;
            } else if (type === 'FILE' && fileUrl) {
                // Check if it's an image or PDF for preview
                const ext = fileUrl.split('.').pop().toLowerCase();
                
                // Use viewUrl for fetching content (permission checked)
                const secureUrl = viewUrl;

                if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext)) {
                     modalBody.innerHTML = `
                        <div class="d-flex align-items-center justify-content-center h-100 p-4">
                            <img src="${secureUrl}" class="img-fluid rounded shadow" alt="${title}" style="max-height: 100%;">
                        </div>
                     `;
                } else if (ext === 'pdf') {
                     // Use iframe for better PDF embedding
                     modalBody.innerHTML = `
                        <div class="w-100 h-100" style="min-height: 80vh;">
                            <iframe src="${secureUrl}" style="width: 100%; height: 100%; border: none;">
                                <div class="d-flex flex-column align-items-center justify-content-center h-100 p-5 text-center">
                                    <p class="text-muted mb-4">متصفحك لا يدعم عرض ملفات PDF داخل الصفحة.</p>
                                    <a href="${secureUrl}" class="btn btn-primary rounded-pill px-5 py-3" download>
                                        <i class="bi bi-download me-2"></i> تحميل الملف
                                    </a>
                                </div>
                            </iframe>
                        </div>
                     `;
                } else {
                    // Other files: no preview, just download button
                    modalBody.innerHTML = `
                        <div class="d-flex flex-column align-items-center justify-content-center h-100">
                            <div class="mb-3 display-4">📄</div>
                            <p class="mb-3">لا يمكن معاينة هذا النوع من الملفات مباشرة.</p>
                            <a href="${secureUrl}" class="btn btn-primary rounded-pill px-4" download>
                                <i class="bi bi-download me-2"></i> تحميل الملف
                            </a>
                        </div>
                    `;
                }
                
            } else if (type === 'LINK' && link) {
                // Embed link in iframe
                modalBody.innerHTML = `
                    <div class="w-100 h-100">
                        <iframe src="${link}" title="${title}" style="width: 100%; height: 100%; border: none;" allowfullscreen sandbox="allow-scripts allow-same-origin allow-forms allow-popups"></iframe>
                    </div>
                `;
            }

            resourceModal.show();
        });
    });

    // Stop video when modal closes
    document.getElementById('resourceModal').addEventListener('hidden.bs.modal', function () {
        modalBody.innerHTML = '';
    });
});
</script>
{% endblock %}