@extends('layouts.app')

@section('title', 'Generate Certificate')
@section('page_header', 'Issue New Student Certificate')

@section('content')
<div class="max-w-4xl mx-auto space-y-6" x-data="certificateForm()">

    <!-- Form Header -->
    <div class="flex items-center justify-between bg-white p-6 rounded-3xl border border-slate-200/80 shadow-sm">
        <div>
            <h2 class="text-xl font-extrabold text-slate-900">Generate Student Certificate</h2>
            <p class="text-xs text-slate-500">Select student, certificate template, internship details, and signatory</p>
        </div>
        <a href="{{ route('admin.certificates.index') }}" class="text-xs font-bold text-slate-600 hover:text-slate-900 bg-slate-100 hover:bg-slate-200 px-4 py-2.5 rounded-xl border border-slate-200">
            ← Cancel
        </a>
    </div>

    <!-- Certificate Generator Card -->
    <div class="bg-white p-8 rounded-3xl border border-slate-200/80 shadow-sm">
        
        <form action="{{ route('admin.certificates.store') }}" method="POST" class="space-y-8">
            @csrf

            <!-- Section 1: Student & Template -->
            <div class="space-y-4">
                <h3 class="text-sm font-extrabold text-slate-900 uppercase tracking-wider border-b border-slate-100 pb-2">1. Recipient & Design Template</h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Select Student <span class="text-rose-500">*</span></label>
                        <select name="student_id" required class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                            <option value="">-- Choose Student --</option>
                            @foreach($students as $s)
                                <option value="{{ $s->id }}" {{ (old('student_id') == $s->id || $selectedStudentId == $s->id) ? 'selected' : '' }}>
                                    {{ $s->full_name }} ({{ $s->college->name ?? 'Direct' }})
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Certificate Template <span class="text-rose-500">*</span></label>
                        <select name="template_id" required class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                            @foreach($templates as $tmpl)
                                <option value="{{ $tmpl->id }}" {{ old('template_id') == $tmpl->id ? 'selected' : '' }}>
                                    {{ $tmpl->title }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>

            <!-- Section 2: Internship Course & Metadata -->
            <div class="space-y-4">
                <h3 class="text-sm font-extrabold text-slate-900 uppercase tracking-wider border-b border-slate-100 pb-2">2. Internship Course & Details</h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    
                    <!-- Course Select with Quick Add (+) Button -->
                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Internship Domain / Course <span class="text-rose-500">*</span></label>
                        <div class="flex items-center gap-3">
                            <select name="course_id" id="course_select" x-model="selectedCourseId" required
                                    class="flex-1 px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                                <option value="">-- Choose Course --</option>
                                <template x-for="crs in courses" :key="crs.id">
                                    <option :value="crs.id" x-text="crs.title"></option>
                                </template>
                            </select>

                            <button type="button" @click="showCourseModal = true" 
                                    class="px-4 py-3 rounded-xl bg-amber-600 hover:bg-amber-700 text-white font-bold text-sm shadow-md shadow-amber-600/20 flex items-center gap-2 flex-shrink-0 transition-transform active:scale-95"
                                    title="Add New Course Instantly">
                                <i data-lucide="plus" class="w-5 h-5"></i>
                                <span class="hidden sm:inline">Add Course</span>
                            </button>
                        </div>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Internship Work Mode</label>
                        <select name="internship_mode" class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                            <option value="Online" {{ old('internship_mode') == 'Online' ? 'selected' : '' }}>Online / Remote</option>
                            <option value="Offline" {{ old('internship_mode') == 'Offline' ? 'selected' : '' }}>In-Office / Offline</option>
                            <option value="Fieldwork" {{ old('internship_mode') == 'Fieldwork' ? 'selected' : '' }}>Field Work</option>
                            <option value="Hybrid" {{ old('internship_mode') == 'Hybrid' ? 'selected' : '' }}>Hybrid Mode</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Internship Nature</label>
                        <select name="internship_nature" class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                            <option value="Professional Internship">Professional Internship</option>
                            <option value="Social Work & Volunteer">Social Work & Volunteer</option>
                            <option value="Academic Credit Internship">Academic Credit Internship</option>
                        </select>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Total Duration</label>
                        <input type="text" name="duration" value="{{ old('duration', '3 Months') }}" required
                               placeholder="e.g. 3 Months / 45 Days"
                               class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Start Date <span class="text-rose-500">*</span></label>
                        <input type="date" name="start_date" value="{{ old('start_date', date('Y-m-d', strtotime('-3 months'))) }}" required
                               class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">End Date <span class="text-rose-500">*</span></label>
                        <input type="date" name="end_date" value="{{ old('end_date', date('Y-m-d')) }}" required
                               class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Grade / Performance (Optional)</label>
                        <input type="text" name="performance_grade" value="{{ old('performance_grade', 'Grade A+') }}"
                               placeholder="e.g. Grade A+ / Outstanding"
                               class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Role Designation</label>
                        <input type="text" name="role_designation" value="{{ old('role_designation', 'Student Intern') }}" required
                               placeholder="e.g. Student Intern / Field Lead"
                               class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                    </div>
                </div>
            </div>

            <!-- Section 3: Issue Date & Signatories -->
            <div class="space-y-4">
                <h3 class="text-sm font-extrabold text-slate-900 uppercase tracking-wider border-b border-slate-100 pb-2">3. Issue Information</h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Certificate Issue Date <span class="text-rose-500">*</span></label>
                        <input type="date" name="issue_date" value="{{ old('issue_date', date('Y-m-d')) }}" required
                               class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Signatory Title</label>
                        <input type="text" name="signatory_title" value="{{ old('signatory_title', 'President & Secretary') }}" required
                               class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-emerald-600 outline-none">
                    </div>
                </div>
            </div>

            <!-- Automation Controls -->
            <div class="p-4 rounded-2xl bg-emerald-50 border border-emerald-200 flex items-center justify-between">
                <label class="flex items-center gap-3 cursor-pointer">
                    <input type="checkbox" name="send_email" value="1" checked class="w-5 h-5 rounded text-emerald-600 focus:ring-emerald-500 border-slate-300">
                    <div>
                        <span class="text-sm font-bold text-emerald-900">Email Certificate PDF to Student Instantly</span>
                        <p class="text-xs text-emerald-700">Sends high-resolution PDF certificate & online verification URL to student's email inbox.</p>
                    </div>
                </label>
            </div>

            <!-- Submit Button -->
            <div class="pt-4 border-t border-slate-100 flex items-center justify-end gap-4">
                <a href="{{ route('admin.certificates.index') }}" class="px-6 py-3 rounded-xl border border-slate-200 text-sm font-bold text-slate-600 hover:bg-slate-50">
                    Cancel
                </a>
                <button type="submit" class="px-8 py-4 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 text-white text-sm font-extrabold shadow-xl shadow-emerald-600/30 transition-all hover:scale-105">
                    Generate & Issue Certificate Now
                </button>
            </div>
        </form>
    </div>

    <!-- INLINE QUICK-ADD (+) COURSE MODAL -->
    <div x-show="showCourseModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/60 backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 max-w-md w-full space-y-6 shadow-2xl">
            <div class="flex items-center justify-between border-b border-slate-100 pb-4">
                <div class="flex items-center gap-2 text-amber-700">
                    <div class="w-8 h-8 rounded-xl bg-amber-100 flex items-center justify-center font-bold">
                        <i data-lucide="plus" class="w-5 h-5"></i>
                    </div>
                    <h3 class="text-lg font-bold text-slate-900">Quick-Add New Course</h3>
                </div>
                <button @click="showCourseModal = false" class="text-slate-400 hover:text-slate-600">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>

            <form @submit.prevent="submitQuickCourse()" class="space-y-4">
                <div>
                    <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Course / Domain Title <span class="text-rose-500">*</span></label>
                    <input type="text" x-model="newCourse.title" required placeholder="e.g. Artificial Intelligence & ML"
                           class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-amber-600 outline-none">
                </div>

                <div>
                    <label class="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-2">Course Code</label>
                    <input type="text" x-model="newCourse.code" placeholder="e.g. AI-601"
                           class="w-full px-4 py-3 rounded-xl border border-slate-200 bg-slate-50 text-sm font-semibold focus:bg-white focus:border-amber-600 outline-none">
                </div>

                <div x-show="courseError" class="text-xs text-rose-600 font-semibold" x-text="courseError"></div>

                <div class="flex items-center justify-end gap-3 pt-4 border-t border-slate-100">
                    <button type="button" @click="showCourseModal = false" class="px-4 py-2.5 rounded-xl border border-slate-200 text-xs font-bold text-slate-600 hover:bg-slate-50">
                        Cancel
                    </button>
                    <button type="submit" :disabled="submittingCourse" class="px-5 py-2.5 rounded-xl bg-amber-600 hover:bg-amber-700 text-white text-xs font-bold shadow-lg shadow-amber-600/20 disabled:opacity-50">
                        <span x-show="!submittingCourse">Save & Select Course</span>
                        <span x-show="submittingCourse">Saving...</span>
                    </button>
                </div>
            </form>
        </div>
    </div>

</div>

@push('scripts')
<script>
    function certificateForm() {
        return {
            courses: @json($courses),
            selectedCourseId: "{{ old('course_id') }}",
            showCourseModal: false,
            submittingCourse: false,
            courseError: '',
            newCourse: { title: '', code: '' },

            async submitQuickCourse() {
                if (!this.newCourse.title) return;
                this.submittingCourse = true;
                this.courseError = '';

                try {
                    const response = await fetch("{{ route('admin.courses.store_inline') }}", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify(this.newCourse)
                    });

                    const data = await response.json();

                    if (data.success) {
                        this.courses.push(data.course);
                        this.selectedCourseId = data.course.id;
                        this.newCourse = { title: '', code: '' };
                        this.showCourseModal = false;
                    } else {
                        this.courseError = data.message || 'Error saving course.';
                    }
                } catch (e) {
                    this.courseError = 'Network error. Could not add course.';
                } finally {
                    this.submittingCourse = false;
                }
            }
        }
    }
</script>
@endpush
@endsection
