@extends('admin.layouts.app')

@section('title', $pageTitle ?? 'Upload IMT Montessori Certificate')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">
                        <i class="fas fa-upload"></i>
                        {{ $pageTitle ?? 'Upload IMT Montessori Certificate' }}
                    </h3>
                </div>
                <div class="card-body">
                    @if(session('success'))
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i>
                            {{ session('success') }}
                        </div>
                    @endif

                    @if(session('error'))
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i>
                            {{ session('error') }}
                        </div>
                    @endif

                    @if($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form action="{{ route('admin.certificates.store_imtmontessori') }}" method="POST" enctype="multipart/form-data" id="uploadForm">
                        @csrf

                        <div class="row">
                            <!-- Student Selection -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="student_id" class="form-label">
                                        <i class="fas fa-user"></i>
                                        Select Student *
                                    </label>
                                    <select name="student_id" id="student_id" class="form-control" required>
                                        <option value="">Choose a student...</option>
                                        @foreach($students as $student)
                                            <option value="{{ $student->id }}"
                                                    data-name="{{ $student->full_name }}"
                                                    data-email="{{ $student->email ?? '' }}">
                                                {{ $student->full_name }}
                                                @if($student->email) ({{ $student->email }}) @endif
                                            </option>
                                        @endforeach
                                    </select>
                                    <small class="form-text text-muted">Select the student who this certificate belongs to</small>
                                </div>
                            </div>

                            <!-- Certificate File Upload -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="certificate_file" class="form-label">
                                        <i class="fas fa-file-upload"></i>
                                        Certificate File *
                                    </label>
                                    <input type="file" name="certificate_file" id="certificate_file"
                                           class="form-control" accept=".jpg,.jpeg,.png,.pdf" required>
                                    <small class="form-text text-muted">
                                        Upload certificate image (JPG, PNG) or PDF file. Max size: 10MB
                                    </small>
                                </div>
                            </div>
                        </div>

                        <!-- File Preview -->
                        <div class="row mt-3" id="filePreview" style="display: none;">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h6 class="card-title">
                                            <i class="fas fa-eye"></i>
                                            File Preview
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <div id="previewContent"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Submit Buttons -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary btn-lg" id="uploadBtn">
                                    <i class="fas fa-upload"></i>
                                    Upload Certificate
                                </button>
                                <a href="{{ route('admin.certificates.imtmontessori') }}" class="btn btn-secondary btn-lg ml-2">
                                    <i class="fas fa-arrow-left"></i>
                                    Back to Certificates
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Success Modal -->
<div class="modal fade" id="successModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">
                    <i class="fas fa-check-circle"></i>
                    Certificate Uploaded Successfully!
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>The certificate has been uploaded and saved to the database.</p>
                <p><strong>Student:</strong> <span id="modalStudentName"></span></p>
                <p><strong>File:</strong> <span id="modalFileName"></span></p>
            </div>
            <div class="modal-footer">
                <a href="{{ route('admin.certificates.imtmontessori') }}" class="btn btn-primary">
                    View All Certificates
                </a>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Upload Another</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
.form-group {
    margin-bottom: 1.5rem;
}

.form-label {
    font-weight: 600;
    color: #495057;
}

.card {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    border: 1px solid rgba(0, 0, 0, 0.125);
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}

.btn-lg {
    padding: 0.75rem 1.5rem;
    font-size: 1.1rem;
}

#filePreview {
    background-color: #f8f9fa;
    border-radius: 0.375rem;
}

.preview-image {
    max-width: 100%;
    max-height: 300px;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
}

.preview-pdf {
    width: 100%;
    height: 400px;
    border: 1px solid #dee2e6;
    border-radius: 0.375rem;
}
</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    // File preview functionality
    $('#certificate_file').change(function() {
        const file = this.files[0];
        if (file) {
            const fileType = file.type;
            const fileName = file.name;
            const fileSize = (file.size / 1024 / 1024).toFixed(2); // Convert to MB

            let previewHtml = '';

            if (fileType.startsWith('image/')) {
                // Image preview
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewHtml = `
                        <div class="text-center">
                            <img src="${e.target.result}" class="preview-image" alt="Certificate Preview">
                            <div class="mt-2">
                                <strong>File:</strong> ${fileName}<br>
                                <strong>Size:</strong> ${fileSize} MB<br>
                                <strong>Type:</strong> ${fileType}
                            </div>
                        </div>
                    `;
                    $('#previewContent').html(previewHtml);
                    $('#filePreview').show();
                };
                reader.readAsDataURL(file);
            } else if (fileType === 'application/pdf') {
                // PDF preview
                previewHtml = `
                    <div class="text-center">
                        <div class="alert alert-info">
                            <i class="fas fa-file-pdf fa-3x text-danger mb-2"></i>
                            <h5>PDF Certificate</h5>
                            <strong>File:</strong> ${fileName}<br>
                            <strong>Size:</strong> ${fileSize} MB<br>
                            <strong>Type:</strong> ${fileType}
                        </div>
                    </div>
                `;
                $('#previewContent').html(previewHtml);
                $('#filePreview').show();
            }
        } else {
            $('#filePreview').hide();
        }
    });

    // Form validation
    $('#uploadForm').submit(function(e) {
        const studentId = $('#student_id').val();
        const file = $('#certificate_file')[0].files[0];

        if (!studentId) {
            e.preventDefault();
            alert('Please select a student.');
            return false;
        }

        if (!file) {
            e.preventDefault();
            alert('Please select a certificate file.');
            return false;
        }

        // Show loading state
        $('#uploadBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Uploading...');
    });

    // Show success message if redirected with success
    @if(session('success'))
        $('#modalStudentName').text('{{ session("success") }}');
        $('#modalFileName').text($('#certificate_file')[0].files[0]?.name || 'Certificate file');
        $('#successModal').modal('show');
    @endif
});
</script>
@endpush
