@extends('layouts.app')

@section('title', __('stage_academy.cards.users'))

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

@section('content')
<div class="container-fluid">
    @php
        $isPosStageAcademy = request()->routeIs('pos.stage-academy.users');
        $backUrl = $isPosStageAcademy ? route('pos.stage-academy') : route('stage-academy');
    @endphp
    <div class="d-flex align-items-center gap-3 mb-4">
        <div class="flex-grow-1">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-1">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('dashboard') }}</a></li>
                    @if($isPosStageAcademy)
                        <li class="breadcrumb-item"><a href="{{ route('pos') }}">{{ __('pos.title') }}</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('pos.stage-academy') }}">{{ __('pos.stage_academy.title') }}</a></li>
                    @else
                        <li class="breadcrumb-item"><a href="{{ route('stage-academy') }}">{{ __('stage_academy.title') }}</a></li>
                    @endif
                    <li class="breadcrumb-item active" aria-current="page">{{ __('stage_academy.cards.users') }}</li>
                </ol>
            </nav>
            <h4 class="fw-bold mb-0">{{ __('stage_academy.users.title') }}</h4>
            <div class="text-muted small">{{ __('stage_academy.users.subtitle') }}</div>
        </div>
        <div class="d-flex align-items-center gap-2">
            <a href="{{ $backUrl }}" class="btn btn-outline-secondary app-back-end">
                <i class="bi bi-arrow-{{ app()->getLocale() == 'ar' ? 'right' : 'left' }}"></i> {{ __('common.back') }}
            </a>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                <i class="bi bi-plus-circle me-1"></i> {{ __('stage_academy.users.add_user') }}
            </button>
        </div>
    </div>

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

    <div class="card sa-card border-0 mb-3">
        <div class="card-body">
            <form method="GET" action="{{ request()->url() }}">
                <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 ?? '' }}" class="form-control" id="sa_users_date">
                    </div>
                    <div class="col-md-3 d-flex align-items-end justify-content-end">
                        <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 sa-card border-0">
        <div class="card-body">
            @if($users->isEmpty())
                <div class="text-center py-5 text-muted">
                    <i class="bi bi-people-fill fs-1 d-block mb-3"></i>
                    <div>{{ __('stage_academy.users.empty') }}</div>
                </div>
            @else
                <div class="table-responsive">
                    <table class="table align-middle mb-0">
                        <thead>
                            <tr>
                                <th style="width: 60px;">{{ __('stage_academy.users.fields.image') }}</th>
                                <th>{{ __('stage_academy.users.fields.name') }}</th>
                                <th>{{ __('stage_academy.users.fields.country') }}</th>
                                <th>{{ __('stage_academy.users.fields.province') }}</th>
                                <th>{{ __('stage_academy.users.fields.gender') }}</th>
                                <th>{{ __('stage_academy.users.fields.phone') }}</th>
                                <th class="text-end">{{ __('common.actions') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($users as $user)
                                <tr>
                                    <td>
                                        @if(! empty($user->image) && \Illuminate\Support\Facades\Schema::hasColumn('stage_academy_users', 'image'))
                                            <img src="{{ asset('storage/'.$user->image) }}" alt="{{ $user->name }}" style="width: 42px; height: 42px; object-fit: cover; border-radius: 50%;">
                                        @else
                                            <div class="d-flex align-items-center justify-content-center bg-white border rounded-circle" style="width: 42px; height: 42px;">
                                                <i class="bi bi-person-fill text-secondary"></i>
                                            </div>
                                        @endif
                                    </td>
                                    <td class="fw-semibold">{{ $user->name }}</td>
                                    <td>{{ $countries[$user->country] ?? $user->country }}</td>
                                    <td>
                                        @if($user->country === 'iq' && !empty($user->province))
                                            {{ $provinceLabels[$user->province] ?? $user->province }}
                                        @else
                                            -
                                        @endif
                                    </td>
                                    <td>{{ __('stage_academy.users.gender.' . $user->gender) }}</td>
                                    <td dir="ltr">{{ $user->phone }}</td>
                                    <td class="text-end">
                                        <div class="sa-actions">
                                            <button
                                                type="button"
                                                class="btn btn-sm btn-light sa-action-btn"
                                                data-bs-toggle="modal"
                                                data-bs-target="#editUserModal"
                                                data-id="{{ $user->id }}"
                                                data-name="{{ $user->name }}"
                                                data-country="{{ $user->country }}"
                                                data-province="{{ $user->province }}"
                                                data-gender="{{ $user->gender }}"
                                                data-phone="{{ $user->phone }}"
                                            >
                                                <i class="bi bi-pencil"></i> {{ __('common.edit') }}
                                            </button>

                                            <form action="{{ $isPosStageAcademy ? route('pos.stage-academy.users.destroy', $user) : route('stage-academy.users.destroy', $user) }}" method="POST" class="d-inline">
                                                @csrf
                                                @method('DELETE')
                                                <button type="submit" class="btn btn-sm btn-outline-danger sa-action-btn js-confirm" data-confirm-message="{{ __('stage_academy.users.confirm_delete') }}">
                                                    <i class="bi bi-trash"></i> {{ __('common.delete') }}
                                                </button>
                                            </form>

                                            <form action="{{ $isPosStageAcademy ? route('pos.stage-academy.users.reset-password', $user) : route('stage-academy.users.reset-password', $user) }}" method="POST" class="d-inline">
                                                @csrf
                                                <button type="submit" class="btn btn-sm btn-outline-warning sa-action-btn">
                                                    <i class="bi bi-key"></i> {{ __('stage_academy.users.reset_password') }}
                                                </button>
                                            </form>

                                            @if($isPosStageAcademy)
                                                @php
                                                    $phoneDigits = preg_replace('/\\D+/', '', (string) $user->phone);
                                                    $waPhone = $phoneDigits;

                                                    if (str_starts_with($waPhone, '00')) {
                                                        $waPhone = substr($waPhone, 2);
                                                    }

                                                    if ($user->country === 'iq') {
                                                        if (str_starts_with($waPhone, '0')) {
                                                            $waPhone = '964'.ltrim($waPhone, '0');
                                                        } elseif (! str_starts_with($waPhone, '964') && strlen($waPhone) <= 11) {
                                                            $waPhone = '964'.$waPhone;
                                                        }
                                                    }

                                                    $portalUrl = route('stage-academy-portal.login');
                                                    $message = __('stage_academy.users.whatsapp.message', [
                                                        'name' => $user->name,
                                                        'link' => $portalUrl,
                                                        'username' => $user->phone,
                                                        'password' => '123456789',
                                                    ]);
                                                    $message = str_replace(["\\r\\n", "\\n", "\\r"], "\n", (string) $message);
                                                    $message = str_replace(["\r\n", "\r"], "\n", (string) $message);
                                                    if ($user->name && ! str_contains($message, (string) $user->name)) {
                                                        $message = str_replace(['مرحباً عزيزنا،', 'مرحبا عزيزنا،', 'مرحباً عزيزنا', 'مرحبا عزيزنا'], 'مرحباً '.$user->name.'،', $message);
                                                        $message = str_replace('Hello,', 'Hello '.$user->name.',', $message);
                                                    }
                                                    $waUrl = ($waPhone !== '')
                                                        ? 'https://api.whatsapp.com/send?phone='.$waPhone.'&text='.rawurlencode($message)
                                                        : 'https://api.whatsapp.com/send?text='.rawurlencode($message);
                                                @endphp
                                                <a href="{{ $waUrl }}" target="_blank" rel="noopener" class="btn btn-sm btn-success sa-action-btn">
                                                    <i class="bi bi-whatsapp"></i> {{ __('stage_academy.users.share_whatsapp') }}
                                                </a>
                                            @endif

                                            <a href="{{ $isPosStageAcademy ? route('pos.stage-academy.users.courses', $user) : route('stage-academy.users.courses', $user) }}" class="btn btn-sm btn-outline-primary sa-action-btn">
                                                <i class="bi bi-mortarboard"></i> {{ __('stage_academy.users.courses.button') }}
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

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

<div class="modal fade" id="addUserModal" 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">{{ __('stage_academy.users.add_user') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="{{ $isPosStageAcademy ? route('pos.stage-academy.users.store') : route('stage-academy.users.store') }}" method="POST">
                @csrf
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">{{ __('stage_academy.users.fields.name') }}</label>
                            <input type="text" name="name" class="form-control @error('name') is-invalid @enderror" value="{{ old('name') }}" required>
                            @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('stage_academy.users.fields.gender') }}</label>
                            <select name="gender" class="form-select @error('gender') is-invalid @enderror" required>
                                <option value="">{{ __('common.select') }}</option>
                                <option value="male" {{ old('gender') === 'male' ? 'selected' : '' }}>{{ __('stage_academy.users.gender.male') }}</option>
                                <option value="female" {{ old('gender') === 'female' ? 'selected' : '' }}>{{ __('stage_academy.users.gender.female') }}</option>
                            </select>
                            @error('gender')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('stage_academy.users.fields.country') }}</label>
                            <select name="country" id="create_country" class="form-select @error('country') is-invalid @enderror" required dir="ltr">
                                <option value="">{{ __('common.select') }}</option>
                                @foreach($countries as $code => $labelKey)
                                    <option value="{{ $code }}" {{ old('country') === $code ? 'selected' : '' }}>{{ $labelKey }}</option>
                                @endforeach
                            </select>
                            @error('country')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-6" id="create_province_wrap">
                            <label class="form-label">{{ __('stage_academy.users.fields.province') }}</label>
                            <select name="province" id="create_province" class="form-select @error('province') is-invalid @enderror" required dir="ltr">
                                <option value="">{{ __('common.select') }}</option>
                            </select>
                            @error('province')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('stage_academy.users.fields.phone') }}</label>
                            <input type="text" name="phone" class="form-control @error('phone') is-invalid @enderror" value="{{ old('phone') }}" required dir="ltr">
                            @error('phone')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>
                        @if(! $isPosStageAcademy)
                            <div class="col-md-6">
                                <label class="form-label">{{ __('stage_academy.users.fields.password') }}</label>
                                <input type="password" name="password" class="form-control @error('password') is-invalid @enderror" required dir="ltr">
                                @error('password')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">{{ __('stage_academy.users.fields.password_confirmation') }}</label>
                                <input type="password" name="password_confirmation" class="form-control @error('password_confirmation') is-invalid @enderror" required dir="ltr">
                                @error('password_confirmation')<div class="invalid-feedback">{{ $message }}</div>@enderror
                            </div>
                        @endif
                    </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">{{ __('common.save') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="editUserModal" 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">{{ __('stage_academy.users.edit_user') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editUserForm" method="POST">
                @csrf
                @method('PUT')
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">{{ __('stage_academy.users.fields.name') }}</label>
                            <input type="text" name="name" id="edit_name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('stage_academy.users.fields.gender') }}</label>
                            <select name="gender" id="edit_gender" class="form-select" required>
                                <option value="">{{ __('common.select') }}</option>
                                <option value="male">{{ __('stage_academy.users.gender.male') }}</option>
                                <option value="female">{{ __('stage_academy.users.gender.female') }}</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('stage_academy.users.fields.country') }}</label>
                            <select name="country" id="edit_country" class="form-select" required dir="ltr">
                                <option value="">{{ __('common.select') }}</option>
                                @foreach($countries as $code => $labelKey)
                                    <option value="{{ $code }}">{{ $labelKey }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6" id="edit_province_wrap">
                            <label class="form-label">{{ __('stage_academy.users.fields.province') }}</label>
                            <select name="province" id="edit_province" class="form-select" required dir="ltr">
                                <option value="">{{ __('common.select') }}</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">{{ __('stage_academy.users.fields.phone') }}</label>
                            <input type="text" name="phone" id="edit_phone" class="form-control" required dir="ltr">
                        </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">{{ __('common.save') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script type="application/json" id="saUsersConfig">
{!! json_encode([
    'provincesByCountry' => $provincesByCountry,
    'provinceLabels' => $provinceLabels,
    'chooseLabel' => __('common.select'),
    'baseUsersUrl' => $isPosStageAcademy ? url('/pos/stage-academy/users') : url('/stage-academy/users'),
    'openAddModal' => (bool) session('open_add_modal', false),
    'editUserId' => session('edit_user_id'),
    'oldInput' => [
        'name' => old('name'),
        'country' => old('country'),
        'province' => old('province'),
        'gender' => old('gender'),
        'phone' => old('phone'),
    ],
], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE) !!}
</script>
<script>
    const configEl = document.getElementById('saUsersConfig');
    let config = {};
    try {
        config = JSON.parse(configEl ? configEl.textContent : '{}');
    } catch (e) {
        config = {};
    }
    const provincesByCountry = config.provincesByCountry || {};
    const provinceLabels = config.provinceLabels || {};
    const chooseLabel = config.chooseLabel || '';
    const baseUsersUrl = config.baseUsersUrl || '';

    function fillProvinces(countryCode, provinceSelect, selectedValue = '') {
        const provinces = provincesByCountry[countryCode] || [];
        provinceSelect.innerHTML = `<option value="">${chooseLabel}</option>`;

        provinces.forEach((provinceCode) => {
            const label = provinceLabels[provinceCode] || provinceCode;
            const option = document.createElement('option');
            option.value = provinceCode;
            option.textContent = label;
            if (selectedValue && selectedValue === provinceCode) {
                option.selected = true;
            }
            provinceSelect.appendChild(option);
        });
    }

    function toggleProvince(countryCode, provinceWrap, provinceSelect) {
        if (!provinceWrap || !provinceSelect) {
            return;
        }

        if (countryCode === 'iq') {
            provinceWrap.classList.remove('d-none');
            provinceSelect.required = true;
        } else {
            provinceWrap.classList.add('d-none');
            provinceSelect.required = false;
            provinceSelect.value = '';
            provinceSelect.innerHTML = `<option value="">${chooseLabel}</option>`;
        }
    }

    const createCountry = document.getElementById('create_country');
    const createProvince = document.getElementById('create_province');
    const createProvinceWrap = document.getElementById('create_province_wrap');

    if (createCountry && createProvince) {
        createCountry.addEventListener('change', () => {
            toggleProvince(createCountry.value, createProvinceWrap, createProvince);
            if (createCountry.value === 'iq') {
                fillProvinces(createCountry.value, createProvince);
            }
        });
        if (config.oldInput?.country) {
            toggleProvince(config.oldInput.country, createProvinceWrap, createProvince);
            fillProvinces(config.oldInput.country, createProvince, config.oldInput?.province || '');
        } else {
            toggleProvince('', createProvinceWrap, createProvince);
        }
    }

    const editModal = document.getElementById('editUserModal');
    const editForm = document.getElementById('editUserForm');
    const editName = document.getElementById('edit_name');
    const editCountry = document.getElementById('edit_country');
    const editProvince = document.getElementById('edit_province');
    const editProvinceWrap = document.getElementById('edit_province_wrap');
    const editGender = document.getElementById('edit_gender');
    const editPhone = document.getElementById('edit_phone');

    document.querySelectorAll('.js-confirm').forEach((btn) => {
        btn.addEventListener('click', (e) => {
            const message = btn.getAttribute('data-confirm-message') || '';
            if (!confirm(message)) {
                e.preventDefault();
            }
        });
    });

    if (editModal) {
        editModal.addEventListener('show.bs.modal', (event) => {
            const button = event.relatedTarget;
            const id = button.getAttribute('data-id');
            const name = button.getAttribute('data-name');
            const country = button.getAttribute('data-country');
            const province = button.getAttribute('data-province');
            const gender = button.getAttribute('data-gender');
            const phone = button.getAttribute('data-phone');

            editForm.action = `${baseUsersUrl}/${id}`;
            editName.value = name || '';
            editCountry.value = country || '';
            toggleProvince(editCountry.value, editProvinceWrap, editProvince);
            if (editCountry.value === 'iq') {
                fillProvinces(editCountry.value, editProvince, province || '');
            }
            editGender.value = gender || '';
            editPhone.value = phone || '';
        });

        editCountry.addEventListener('change', () => {
            toggleProvince(editCountry.value, editProvinceWrap, editProvince);
            if (editCountry.value === 'iq') {
                fillProvinces(editCountry.value, editProvince);
            }
        });
    }

    if (config.openAddModal) {
        const addModal = document.getElementById('addUserModal');
        if (addModal) {
            const modal = bootstrap.Modal.getOrCreateInstance(addModal);
            modal.show();
        }
    }

    if (config.editUserId) {
        const editModalEl = document.getElementById('editUserModal');
        const modal = bootstrap.Modal.getOrCreateInstance(editModalEl);
        editForm.action = `${baseUsersUrl}/${config.editUserId}`;
        editName.value = config.oldInput?.name || '';
        editCountry.value = config.oldInput?.country || '';
        toggleProvince(editCountry.value, editProvinceWrap, editProvince);
        if (editCountry.value === 'iq') {
            fillProvinces(editCountry.value, editProvince, config.oldInput?.province || '');
        }
        editGender.value = config.oldInput?.gender || '';
        editPhone.value = config.oldInput?.phone || '';
        modal.show();
    }
</script>
@endpush
