@extends('layouts.app')

@section('title', __('pos.stage_academy.title'))

@push('styles')
<link href="{{ asset('css/pos.css') }}" rel="stylesheet">
@endpush

@section('content')
<div class="pos-container">
    <div class="pos-header">
        <div class="d-flex align-items-center justify-content-between gap-3 w-100">
            <h2 class="pos-title mb-0">
                @if(($mode ?? 'index') === 'activations')
                    {{ __('pos.stage_academy.cards.activations') }}
                @else
                    {{ __('pos.stage_academy.title') }}
                @endif
            </h2>
            <div class="d-flex align-items-center gap-2">
                <a href="{{ ($mode ?? 'index') === 'activations' ? route('pos.stage-academy') : route('pos') }}" class="btn btn-outline-secondary app-back-end">
                    <i class="bi {{ app()->getLocale() == 'ar' ? 'bi-arrow-right' : 'bi-arrow-left' }}"></i> {{ __('common.back') }}
                </a>
                @if(($mode ?? 'index') === 'activations')
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#saActivationModal">
                        <i class="bi bi-plus-circle me-1"></i> {{ __('pos.stage_academy.activations.add_activation') }}
                    </button>
                @endif
            </div>
        </div>
    </div>

    @if(($mode ?? 'index') === 'index')
        <div class="pos-grid">
            <a href="{{ route('pos.stage-academy.users') }}" class="pos-item-card text-decoration-none">
                <div class="pos-item-content h-100 d-flex flex-column">
                    <h3 class="pos-item-title mb-1">{{ __('pos.stage_academy.cards.users') }}</h3>
                    <div class="small text-muted mb-2">{{ __('pos.stage_academy.cards.users_desc') }}</div>
                    <div class="mt-auto d-flex justify-content-between align-items-end">
                        <span class="pos-item-badge">{{ __('pos.stage_academy.cards.open') }}</span>
                        <i class="bi bi-people fs-3 text-primary"></i>
                    </div>
                </div>
            </a>

            <a href="{{ route('pos.stage-academy.activations') }}" class="pos-item-card text-decoration-none">
                <div class="pos-item-content h-100 d-flex flex-column">
                    <h3 class="pos-item-title mb-1">{{ __('pos.stage_academy.cards.activations') }}</h3>
                    <div class="small text-muted mb-2">{{ __('pos.stage_academy.cards.activations_desc') }}</div>
                    <div class="mt-auto d-flex justify-content-between align-items-end">
                        <span class="pos-item-badge">{{ __('pos.stage_academy.cards.open') }}</span>
                        <i class="bi bi-key fs-3 text-primary"></i>
                    </div>
                </div>
            </a>
        </div>
    @else
        @if(session('success'))
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ session('success') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        @endif
        @if(session('error'))
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {{ session('error') }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </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

        @if(! $tableExists)
            <div class="text-center py-5">
                <i class="bi bi-mortarboard text-muted" style="font-size: 4rem;"></i>
                <p class="text-muted mt-3 fs-5">{{ __('pos.stage_academy.no_data') }}</p>
            </div>
        @else
            <div class="card border-0 sa-pos-card mb-3">
                <div class="card-body">
                    <form method="GET" action="{{ route('pos.stage-academy.activations') }}">
                        <div class="row g-2 align-items-end">
                            <div class="col-md-5">
                                <label class="form-label">{{ __('common.search') }}</label>
                                <input type="text" name="search" value="{{ $search ?? '' }}" class="form-control" placeholder="{{ __('common.search_placeholder') }}">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">{{ __('common.date') }}</label>
                                <input type="date" name="date" value="{{ $date ?? now()->format('Y-m-d') }}" class="form-control" id="sa_activations_date">
                            </div>
                            <div class="col-md-3 d-flex align-items-center justify-content-between gap-2">
                                <div class="form-check mb-1">
                                    <input class="form-check-input" type="checkbox" value="1" id="sa_activations_show_all" name="show_all" {{ ($showAll ?? false) ? 'checked' : '' }}>
                                    <label class="form-check-label" for="sa_activations_show_all">
                                        {{ __('common.show_all') }}
                                    </label>
                                </div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="bi bi-funnel me-1"></i> {{ __('common.filter') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card border-0 sa-pos-card">
                <div class="card-body">
                    @if($activations->count() === 0)
                        <div class="text-center py-5">
                            <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                            <p class="text-muted mt-3 fs-5">{{ __('pos.stage_academy.activations.empty') }}</p>
                        </div>
                    @else
                        <div class="sa-smart-list">
                            @foreach($activations as $activation)
                                <div class="sa-smart-bar">
                                    <div class="sa-smart-bar-main">
                                        <div class="sa-smart-bar-title">
                                            <span class="fw-bold">{{ $activation->user?->name }}</span>
                                            <span class="text-muted small" dir="ltr">{{ $activation->user?->phone }}</span>
                                        </div>
                                        <div class="sa-smart-bar-sub text-muted small">
                                            <span>{{ __('subscriptions.invoice_number') }}: {{ $activation->invoice_number ?? '-' }}</span>
                                            <span>•</span>
                                            <span>{{ app()->getLocale() == 'ar' ? ($activation->course?->name_ar) : ($activation->course?->name_en) }}</span>
                                            <span>•</span>
                                            <span>{{ number_format((int) $activation->price, 0) }}</span>
                                            <span>•</span>
                                            <span>{{ __('subscriptions.payment_methods.' . $activation->payment_method) }}</span>
                                            <span>•</span>
                                            <span>{{ $activation->created_at?->format('Y-m-d') }}</span>
                                            <span>•</span>
                                            <span>{{ __('subscriptions.sales_employee') }}: {{ $activation->creator?->name ?? 'N/A' }}</span>
                                        </div>
                                    </div>
                                    <div class="sa-smart-bar-actions">
                                        <a href="{{ route('pos.stage-academy.activations.invoice', $activation) }}" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-receipt"></i>
                                        </a>
                                    </div>
                                </div>
                            @endforeach
                        </div>

                        <div class="mt-3">
                            {{ $activations->links() }}
                        </div>
                    @endif
                </div>
            </div>
        @endif

        <div class="modal fade" id="saActivationModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ __('pos.stage_academy.activations.modal_title') }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>

                    <form action="{{ route('pos.stage-academy.activations.store') }}" method="POST" id="saActivationForm">
                        @csrf
                        <input type="hidden" name="user_id" id="sa_user_id" value="">
                        <input type="hidden" name="course_id" id="sa_course_id" value="">

                        <div class="modal-body">
                            <div id="saStepUser">
                                <div class="sa-step-title mb-2">{{ __('pos.stage_academy.activations.step_user') }}</div>

                                <label class="form-label">{{ __('pos.stage_academy.activations.user_search') }}</label>
                                <div class="sa-smart-search mb-3">
                                    <i class="bi bi-search sa-smart-search-icon"></i>
                                    <input type="text" class="form-control sa-smart-search-input" id="sa_user_search" autocomplete="off" placeholder="{{ __('pos.stage_academy.activations.user_search_placeholder') }}">
                                </div>
                                <div class="list-group sa-search-results" id="sa_user_results"></div>

                                <div class="sa-selected mt-3 d-none" id="sa_selected_user">
                                    <div class="sa-selected-card">
                                        <div class="d-flex align-items-center justify-content-between gap-3">
                                            <div>
                                                <div class="fw-bold" id="sa_selected_user_name"></div>
                                                <div class="text-muted small" dir="ltr" id="sa_selected_user_phone"></div>
                                            </div>
                                            <button type="button" class="btn btn-primary" id="sa_go_course">
                                                <i class="bi bi-mortarboard me-1"></i> {{ __('pos.stage_academy.activations.add_course') }}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div id="saStepCourse" class="d-none">
                                <div class="d-flex align-items-center justify-content-between gap-2 mb-3">
                                    <div class="sa-step-title">{{ __('pos.stage_academy.activations.step_course') }}</div>
                                    <button type="button" class="btn btn-outline-secondary btn-sm" id="sa_back_user">
                                        <i class="bi bi-arrow-{{ app()->getLocale() == 'ar' ? 'right' : 'left' }}"></i> {{ __('common.back') }}
                                    </button>
                                </div>

                                <label class="form-label">{{ __('pos.stage_academy.activations.course_search') }}</label>
                                <div class="sa-smart-search mb-3">
                                    <i class="bi bi-search sa-smart-search-icon"></i>
                                    <input type="text" class="form-control sa-smart-search-input" id="sa_course_search" autocomplete="off" placeholder="{{ __('pos.stage_academy.activations.course_search_placeholder') }}">
                                </div>
                                <div class="list-group sa-search-results" id="sa_course_results"></div>

                                <div class="sa-selected mt-3 d-none" id="sa_selected_course">
                                    <div class="sa-selected-card">
                                        <div class="fw-bold" id="sa_selected_course_name"></div>
                                        <div class="text-muted small">#<span id="sa_selected_course_id"></span></div>
                                    </div>
                                </div>

                                <div class="row g-3 mt-2">
                                    <div class="col-md-6">
                                        <label for="sa_price" class="form-label">{{ __('pos.stage_academy.activations.price') }}</label>
                                        <input type="number" class="form-control" id="sa_price" name="price" min="0" step="1" value="" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="sa_payment_method" class="form-label">{{ __('pos.stage_academy.activations.payment_method') }}</label>
                                        <select class="form-select" id="sa_payment_method" name="payment_method" required>
                                            @foreach(($paymentMethods ?? []) as $method)
                                                <option value="{{ $method }}">{{ __('subscriptions.payment_methods.' . $method) }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                            <button type="submit" class="btn btn-primary" id="sa_save_btn" disabled>
                                <i class="bi bi-check2-circle me-1"></i> {{ __('pos.stage_academy.activations.save') }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    @endif
</div>
@endsection

@push('scripts')
<script>
    (() => {
        const showAll = document.getElementById('sa_activations_show_all');
        const dateInput = document.getElementById('sa_activations_date');
        const sync = () => {
            if (showAll && dateInput) {
                dateInput.disabled = showAll.checked;
            }
        };
        if (showAll && dateInput) {
            showAll.addEventListener('change', sync);
            sync();
        }

        const userSearchInput = document.getElementById('sa_user_search');
        const userResults = document.getElementById('sa_user_results');
        const selectedUserWrap = document.getElementById('sa_selected_user');
        const selectedUserName = document.getElementById('sa_selected_user_name');
        const selectedUserPhone = document.getElementById('sa_selected_user_phone');
        const userIdInput = document.getElementById('sa_user_id');
        const goCourseBtn = document.getElementById('sa_go_course');

        const stepUser = document.getElementById('saStepUser');
        const stepCourse = document.getElementById('saStepCourse');
        const backUserBtn = document.getElementById('sa_back_user');

        const courseSearchInput = document.getElementById('sa_course_search');
        const courseResults = document.getElementById('sa_course_results');
        const selectedCourseWrap = document.getElementById('sa_selected_course');
        const selectedCourseName = document.getElementById('sa_selected_course_name');
        const selectedCourseId = document.getElementById('sa_selected_course_id');
        const courseIdInput = document.getElementById('sa_course_id');

        const priceInput = document.getElementById('sa_price');
        const saveBtn = document.getElementById('sa_save_btn');

        let userTimer = null;
        let courseTimer = null;
        const isAr = "{{ app()->getLocale() }}" === "ar";

        const setStep = (step) => {
            if (step === 'user') {
                stepUser.classList.remove('d-none');
                stepCourse.classList.add('d-none');
            } else {
                stepUser.classList.add('d-none');
                stepCourse.classList.remove('d-none');
            }
        };

        const setSaveEnabled = () => {
            const ok = userIdInput.value && courseIdInput.value && priceInput.value !== '';
            saveBtn.disabled = !ok;
        };

        const renderUserResults = (items) => {
            userResults.innerHTML = '';
            if (!items.length) {
                userResults.innerHTML = `<div class="sa-empty-result text-muted small px-3 py-2">{{ __('pos.stage_academy.activations.no_results') }}</div>`;
                return;
            }

            items.forEach((item) => {
                const el = document.createElement('button');
                el.type = 'button';
                el.className = 'list-group-item list-group-item-action d-flex align-items-center justify-content-between gap-3';
                el.innerHTML = `
                    <div>
                        <div class="fw-semibold">${item.name}</div>
                        <div class="text-muted small" dir="ltr">${item.phone}</div>
                    </div>
                    <span class="btn btn-sm btn-outline-primary">{{ __('pos.stage_academy.activations.add_course') }}</span>
                `;
                el.addEventListener('click', () => {
                    userIdInput.value = item.id;
                    selectedUserName.textContent = item.name;
                    selectedUserPhone.textContent = item.phone;
                    selectedUserWrap.classList.remove('d-none');
                    userResults.innerHTML = '';
                    userSearchInput.value = '';
                    setStep('user');
                    courseIdInput.value = '';
                    selectedCourseWrap.classList.add('d-none');
                    setSaveEnabled();
                });
                userResults.appendChild(el);
            });
        };

        const renderCourseResults = (items) => {
            courseResults.innerHTML = '';
            if (!items.length) {
                courseResults.innerHTML = `<div class="sa-empty-result text-muted small px-3 py-2">{{ __('pos.stage_academy.activations.no_results') }}</div>`;
                return;
            }

            items.forEach((item) => {
                const name = isAr ? (item.name_ar || '') : (item.name_en || '');
                const el = document.createElement('button');
                el.type = 'button';
                el.className = 'list-group-item list-group-item-action d-flex align-items-center justify-content-between gap-3';
                el.innerHTML = `
                    <div>
                        <div class="fw-semibold">${name}</div>
                        <div class="text-muted small">#${item.id}</div>
                    </div>
                    <span class="text-muted small">${Number(item.price ?? 0).toLocaleString()}</span>
                `;
                el.addEventListener('click', () => {
                    courseIdInput.value = item.id;
                    selectedCourseName.textContent = name;
                    selectedCourseId.textContent = item.id;
                    selectedCourseWrap.classList.remove('d-none');
                    courseResults.innerHTML = '';
                    courseSearchInput.value = '';
                    priceInput.value = item.price ?? 0;
                    setSaveEnabled();
                });
                courseResults.appendChild(el);
            });
        };

        const searchUsers = (q) => {
            fetch(`{{ route('pos.stage-academy.activations.search-users') }}?q=${encodeURIComponent(q)}`, {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
                .then(r => r.json())
                .then(data => renderUserResults(data.results || []))
                .catch(() => { userResults.innerHTML = ''; });
        };

        const searchCourses = (q) => {
            fetch(`{{ route('pos.stage-academy.activations.search-courses') }}?q=${encodeURIComponent(q)}`, {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
                .then(r => r.json())
                .then(data => renderCourseResults(data.results || []))
                .catch(() => { courseResults.innerHTML = ''; });
        };

        if (userSearchInput) {
            userSearchInput.addEventListener('input', (e) => {
                clearTimeout(userTimer);
                const q = (e.target.value || '').trim();
                selectedUserWrap.classList.add('d-none');
                userIdInput.value = '';
                setSaveEnabled();
                if (!q) {
                    userResults.innerHTML = '';
                    return;
                }
                userTimer = setTimeout(() => searchUsers(q), 200);
            });
        }

        if (courseSearchInput) {
            courseSearchInput.addEventListener('input', (e) => {
                clearTimeout(courseTimer);
                const q = (e.target.value || '').trim();
                courseIdInput.value = '';
                selectedCourseWrap.classList.add('d-none');
                setSaveEnabled();
                if (!q) {
                    courseResults.innerHTML = '';
                    return;
                }
                courseTimer = setTimeout(() => searchCourses(q), 200);
            });
        }

        if (goCourseBtn) {
            goCourseBtn.addEventListener('click', () => {
                if (!userIdInput.value) {
                    return;
                }
                setStep('course');
                courseSearchInput?.focus();
            });
        }

        if (backUserBtn) {
            backUserBtn.addEventListener('click', () => {
                setStep('user');
            });
        }

        if (priceInput) {
            priceInput.addEventListener('input', setSaveEnabled);
        }

        const modalEl = document.getElementById('saActivationModal');
        if (modalEl) {
            modalEl.addEventListener('hidden.bs.modal', () => {
                userSearchInput.value = '';
                courseSearchInput.value = '';
                userResults.innerHTML = '';
                courseResults.innerHTML = '';
                userIdInput.value = '';
                courseIdInput.value = '';
                selectedUserWrap.classList.add('d-none');
                selectedCourseWrap.classList.add('d-none');
                priceInput.value = '';
                setStep('user');
                setSaveEnabled();
            });
        }
    })();
</script>
@endpush
