@extends('layouts.self-paced-dashboard')

@section('title', 'Certificates')
@section('page-title', 'Certificates')
@section('page-subtitle', 'Manage and verify all issued certificates of completion')

@section('hero-actions')
    <a href="{{ route('self-paced.dashboard.certificates.export') . '?' . http_build_query(request()->only(['course_id', 'is_revoked', 'date_from', 'date_to'])) }}"
       class="inline-flex items-center gap-2 px-4 py-2 bg-white/10 hover:bg-white/20 text-white text-sm font-medium rounded-lg transition border border-white/30">
        <i class="fas fa-file-csv"></i> Export CSV
    </a>
@endsection

@section('content')
<div x-data="certificateIndex()" x-init="init()">

    {{-- Filters & Search Bar --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 p-4 mb-5">
        <div class="flex flex-col sm:flex-row gap-3 flex-wrap">

            {{-- Search --}}
            <div class="relative flex-1 min-w-[200px]">
                <span class="absolute inset-y-0 left-3 flex items-center text-gray-400 pointer-events-none">
                    <i class="fas fa-search text-sm"></i>
                </span>
                <input type="text"
                       x-model="search"
                       @input.debounce.400ms="fetchCertificates()"
                       placeholder="Search by certificate #, holder name, or course…"
                       class="w-full pl-9 pr-4 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition">
            </div>

            {{-- Course filter --}}
            <select x-model="courseId"
                    @change="fetchCertificates()"
                    class="text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white">
                <option value="">All Courses</option>
                @foreach($courses as $course)
                    <option value="{{ $course->id }}">{{ $course->title }}</option>
                @endforeach
            </select>

            {{-- Status filter --}}
            <select x-model="isRevoked"
                    @change="fetchCertificates()"
                    class="text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white">
                <option value="">All Statuses</option>
                <option value="0">Valid</option>
                <option value="1">Revoked</option>
            </select>

            {{-- Date From --}}
            <input type="date"
                   x-model="dateFrom"
                   @change="fetchCertificates()"
                   title="Issue date from"
                   class="text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white">

            {{-- Date To --}}
            <input type="date"
                   x-model="dateTo"
                   @change="fetchCertificates()"
                   title="Issue date to"
                   class="text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-indigo-400 transition bg-white">

            {{-- Clear --}}
            <button @click="clearFilters()"
                    x-show="search || courseId || isRevoked !== '' || dateFrom || dateTo"
                    x-cloak
                    class="inline-flex items-center gap-1.5 px-3 py-2 text-sm text-gray-500 hover:text-gray-700 border border-gray-200 rounded-lg hover:bg-gray-50 transition">
                <i class="fas fa-times text-xs"></i> Clear
            </button>
        </div>
    </div>

    {{-- Table Card --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">

        {{-- Loading overlay --}}
        <div x-show="loading" x-cloak class="flex items-center justify-center py-16">
            <i class="fas fa-spinner fa-spin text-indigo-400 text-2xl"></i>
        </div>

        <div x-show="!loading" x-cloak>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr>
                            <th class="bg-indigo-50 text-indigo-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide w-10">#</th>
                            <th class="bg-purple-50 text-purple-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Certificate #</th>
                            <th class="bg-blue-50 text-blue-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Holder</th>
                            <th class="bg-green-50 text-green-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Course</th>
                            <th class="bg-amber-50 text-amber-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Issue Date</th>
                            <th class="bg-teal-50 text-teal-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Status</th>
                            <th class="bg-rose-50 text-rose-700 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Verifications</th>
                            <th class="bg-gray-50 text-gray-600 font-semibold text-left px-4 py-3 text-xs uppercase tracking-wide">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="certificates-tbody" class="divide-y divide-gray-50">
                        @include('self-paced.dashboard.certificates.partials.table', ['certificates' => $certificates])
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            @if($certificates->hasPages())
            <div class="px-4 py-3 border-t border-gray-100" id="certificates-pagination">
                {{ $certificates->links() }}
            </div>
            @endif
        </div>
    </div>

    {{-- Revoke Modal --}}
    <div x-show="revokeModal.open"
         x-cloak
         class="fixed inset-0 z-50 flex items-center justify-center p-4"
         @keydown.escape.window="revokeModal.open = false">
        <div class="absolute inset-0 bg-black/40 backdrop-blur-sm" @click="revokeModal.open = false"></div>
        <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden" x-transition>
            <div class="flex items-center justify-between px-6 py-4 bg-gradient-to-r from-red-600 to-red-700 rounded-t-2xl">
                <div>
                    <h3 class="text-base font-semibold text-white flex items-center gap-2">
                        <i class="fas fa-ban"></i> Revoke Certificate
                    </h3>
                    <p class="text-xs text-red-200" x-text="'Certificate: ' + revokeModal.certNumber"></p>
                </div>
                <button type="button" @click="revokeModal.open = false" class="text-white/80 hover:text-white transition">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6">
            <form :action="revokeModal.action" method="POST">
                @csrf
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        <i class="fas fa-comment-alt text-gray-400 mr-1"></i> Revocation Reason <span class="text-red-500">*</span>
                    </label>
                    <textarea name="revocation_reason"
                              rows="3"
                              required
                              placeholder="Provide a reason for revoking this certificate…"
                              class="w-full text-sm border border-gray-200 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-red-300 focus:border-red-400 transition resize-none"></textarea>
                </div>
                <div class="flex gap-3">
                    <button type="button"
                            @click="revokeModal.open = false"
                            class="flex-1 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition">
                        Cancel
                    </button>
                    <button type="submit"
                            class="flex-1 px-4 py-2 text-sm font-semibold text-white bg-red-500 hover:bg-red-600 rounded-lg transition">
                        <i class="fas fa-ban mr-1"></i> Revoke
                    </button>
                </div>
            </form>
            </div>
        </div>
    </div>

</div>
@endsection

@push('scripts')
<script>
function certificateIndex() {
    return {
        search: '',
        courseId: '',
        isRevoked: '',
        dateFrom: '',
        dateTo: '',
        loading: false,
        revokeModal: {
            open: false,
            certId: null,
            certNumber: '',
            action: '',
        },

        init() {
            const params = new URLSearchParams(window.location.search);
            this.search    = params.get('search')     || '';
            this.courseId  = params.get('course_id')  || '';
            this.isRevoked = params.get('is_revoked') ?? '';
            this.dateFrom  = params.get('date_from')  || '';
            this.dateTo    = params.get('date_to')    || '';
        },

        fetchCertificates(page) {
            this.loading = true;
            const params = new URLSearchParams();
            if (this.search)           params.set('search',     this.search);
            if (this.courseId)         params.set('course_id',  this.courseId);
            if (this.isRevoked !== '') params.set('is_revoked', this.isRevoked);
            if (this.dateFrom)         params.set('date_from',  this.dateFrom);
            if (this.dateTo)           params.set('date_to',    this.dateTo);
            if (page)                  params.set('page',       page);

            axios.get('{{ route('self-paced.dashboard.certificates.index') }}?' + params.toString(), {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(res => {
                document.getElementById('certificates-tbody').innerHTML = res.data.html;
                const pag = document.getElementById('certificates-pagination');
                if (pag && res.data.pagination) pag.innerHTML = res.data.pagination;
            })
            .catch(() => {})
            .finally(() => { this.loading = false; });
        },

        clearFilters() {
            this.search    = '';
            this.courseId  = '';
            this.isRevoked = '';
            this.dateFrom  = '';
            this.dateTo    = '';
            this.fetchCertificates();
        },

        openRevokeModal(certId, certNumber) {
            this.revokeModal.certId     = certId;
            this.revokeModal.certNumber = certNumber;
            this.revokeModal.action     = `/self-paced/dashboard/certificates/${certId}/revoke`;
            this.revokeModal.open       = true;
        },
    };
}
</script>
@endpush
