@extends('layouts.app')

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

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

@section('content')
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="h4 fw-bold text-dark mb-0">{{ __('stage_academy.trainers.title') }}</h2>
        <div class="d-flex align-items-center gap-2">
            <button type="button" class="btn btn-primary bg-gradient border-0" onclick="openAddModal()">
                <i class="bi bi-plus-lg"></i>
                {{ __('stage_academy.trainers.add_button') }}
            </button>
            <a href="{{ route('stage-academy') }}" class="btn btn-outline-secondary">
                <i class="bi {{ app()->getLocale() == 'ar' ? 'bi-arrow-right' : 'bi-arrow-left' }}"></i> {{ __('common.back') }}
            </a>
        </div>
    </div>

    @if($errors->any())
        <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0" role="alert">
            <ul class="mb-0 ps-3">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    @endif

    <div class="sa-smart-list">
        @forelse($trainers as $trainer)
            @php
                $localizedName = app()->getLocale() === 'ar' ? $trainer->name_ar : $trainer->name_en;
                $localizedDetails = app()->getLocale() === 'ar' ? $trainer->details_ar : $trainer->details_en;
                $percentage = max(0, min(100, (float) $trainer->percentage));
                $percentageLabel = rtrim(rtrim(number_format($percentage, 2, '.', ''), '0'), '.');
                $socialLinks = [
                    ['field' => 'facebook', 'icon' => 'bi-facebook', 'label' => 'common.facebook'],
                    ['field' => 'instagram', 'icon' => 'bi-instagram', 'label' => 'common.instagram'],
                    ['field' => 'tiktok', 'icon' => 'bi-tiktok', 'label' => 'common.tiktok'],
                    ['field' => 'youtube', 'icon' => 'bi-youtube', 'label' => 'common.youtube'],
                    ['field' => 'twitter', 'icon' => 'bi-twitter-x', 'label' => 'common.twitter'],
                    ['field' => 'website', 'icon' => 'bi-globe', 'label' => 'common.website'],
                ];
            @endphp

            <div class="sa-smart-row">
                <div class="d-flex align-items-start gap-3 flex-grow-1">
                    <div class="sa-thumb">
                        @if($trainer->image)
                            <img src="{{ Storage::url($trainer->image) }}" alt="{{ $localizedName }}">
                        @else
                            <i class="bi bi-image text-primary"></i>
                        @endif
                    </div>

                    <div class="flex-grow-1">
                        <div class="d-flex justify-content-between align-items-start gap-2 flex-wrap">
                            <div class="fw-bold text-dark">{{ $localizedName }}</div>
                            <div class="sa-percent-badge">{{ $percentageLabel }}%</div>
                        </div>

                        @if($localizedDetails)
                            <div class="text-muted small mt-1">{{ $localizedDetails }}</div>
                        @endif

                        <div class="sa-progress mt-2">
                            <div class="sa-progress-bar" data-progress="{{ $percentage }}"></div>
                        </div>

                        @php
                            $hasAnySocial = false;
                            foreach ($socialLinks as $link) {
                                if (!empty($trainer->{$link['field']})) {
                                    $hasAnySocial = true;
                                    break;
                                }
                            }
                        @endphp

                        @if($hasAnySocial)
                            <div class="sa-social">
                                @foreach($socialLinks as $link)
                                    @php $url = $trainer->{$link['field']}; @endphp
                                    @if($url)
                                        <a href="{{ $url }}" target="_blank" rel="noopener" title="{{ __($link['label']) }}">
                                            <i class="bi {{ $link['icon'] }}"></i>
                                        </a>
                                    @endif
                                @endforeach
                            </div>
                        @endif
                    </div>
                </div>

                <div class="d-flex align-items-center gap-2 flex-shrink-0">
                    <button
                        type="button"
                        class="btn btn-light btn-sm sa-action-btn text-primary"
                        data-item='@json($trainer)'
                        onclick="openEditModal(this)"
                        title="{{ __('common.edit') }}"
                    >
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button
                        type="button"
                        class="btn btn-light btn-sm sa-action-btn text-danger"
                        data-id="{{ $trainer->id }}"
                        onclick="openDeleteModal(this)"
                        title="{{ __('common.delete') }}"
                    >
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        @empty
            <div class="text-center py-5 text-muted">
                <i class="bi bi-inbox fs-1 d-block mb-3 opacity-50"></i>
                <p class="mb-0">{{ __('stage_academy.trainers.empty') }}</p>
            </div>
        @endforelse
    </div>
</div>

@php
    $oldTrainer = [
        'id' => old('id'),
        'name_ar' => old('name_ar'),
        'name_en' => old('name_en'),
        'details_ar' => old('details_ar'),
        'details_en' => old('details_en'),
        'percentage' => old('percentage'),
        'facebook' => old('facebook'),
        'instagram' => old('instagram'),
        'tiktok' => old('tiktok'),
        'youtube' => old('youtube'),
        'twitter' => old('twitter'),
        'website' => old('website'),
    ];
@endphp

<div
    id="trainersConfig"
    data-store-route="{{ route('stage-academy.trainers.store') }}"
    data-update-route-template="{{ route('stage-academy.trainers.update', 0) }}"
    data-delete-route-template="{{ route('stage-academy.trainers.destroy', 0) }}"
    data-add-title="{{ __('stage_academy.trainers.add_button') }}"
    data-edit-title="{{ __('common.edit') }}"
    data-has-errors="{{ $errors->any() ? '1' : '0' }}"
    data-old='@json($oldTrainer)'
></div>

<div class="modal fade" id="trainerModal" tabindex="-1" aria-labelledby="trainerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <form id="trainerForm" method="POST" enctype="multipart/form-data">
                @csrf
                <input type="hidden" name="_method" id="methodField" value="POST">
                <input type="hidden" name="id" id="trainerId" value="{{ old('id') }}">

                <div class="modal-header">
                    <h5 class="modal-title" id="trainerModalLabel">{{ __('stage_academy.trainers.add_button') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-12 col-md-6">
                            <label for="name_ar" class="form-label">{{ __('stage_academy.trainers.form.name_ar') }}</label>
                            <input type="text" class="form-control" id="name_ar" name="name_ar" required maxlength="255" value="{{ old('name_ar') }}">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="name_en" class="form-label">{{ __('stage_academy.trainers.form.name_en') }}</label>
                            <input type="text" class="form-control" id="name_en" name="name_en" required maxlength="255" value="{{ old('name_en') }}">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="details_ar" class="form-label">{{ __('stage_academy.trainers.form.details_ar') }}</label>
                            <textarea class="form-control" id="details_ar" name="details_ar" rows="3">{{ old('details_ar') }}</textarea>
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="details_en" class="form-label">{{ __('stage_academy.trainers.form.details_en') }}</label>
                            <textarea class="form-control" id="details_en" name="details_en" rows="3">{{ old('details_en') }}</textarea>
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="image" class="form-label">{{ __('stage_academy.trainers.form.image') }}</label>
                            <input type="file" class="form-control" id="image" name="image" accept="image/*">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="percentage" class="form-label">{{ __('stage_academy.trainers.form.percentage') }}</label>
                            <input type="number" class="form-control" id="percentage" name="percentage" required min="0" max="100" step="0.01" value="{{ old('percentage') }}">
                        </div>

                        <div class="col-12">
                            <hr class="my-1">
                        </div>

                        <div class="col-12 col-md-6">
                            <label for="facebook" class="form-label">{{ __('common.facebook') }}</label>
                            <input type="url" class="form-control" id="facebook" name="facebook" value="{{ old('facebook') }}">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="instagram" class="form-label">{{ __('common.instagram') }}</label>
                            <input type="url" class="form-control" id="instagram" name="instagram" value="{{ old('instagram') }}">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="tiktok" class="form-label">{{ __('common.tiktok') }}</label>
                            <input type="url" class="form-control" id="tiktok" name="tiktok" value="{{ old('tiktok') }}">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="youtube" class="form-label">{{ __('common.youtube') }}</label>
                            <input type="url" class="form-control" id="youtube" name="youtube" value="{{ old('youtube') }}">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="twitter" class="form-label">{{ __('common.twitter') }}</label>
                            <input type="url" class="form-control" id="twitter" name="twitter" value="{{ old('twitter') }}">
                        </div>
                        <div class="col-12 col-md-6">
                            <label for="website" class="form-label">{{ __('common.website') }}</label>
                            <input type="url" class="form-control" id="website" name="website" value="{{ old('website') }}">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                    <button type="submit" class="btn btn-primary bg-gradient border-0">{{ __('common.save') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form id="deleteForm" method="POST">
                @csrf
                @method('DELETE')

                <div class="modal-header border-bottom-0 pb-0">
                    <h5 class="modal-title text-danger" id="deleteModalLabel">{{ __('common.confirm_delete_title') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body py-4">
                    <p class="mb-0 fs-5 text-center">{{ __('common.confirm_delete_message') }}</p>
                </div>
                <div class="modal-footer border-top-0 pt-0 justify-content-center">
                    <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">{{ __('common.cancel') }}</button>
                    <button type="submit" class="btn btn-danger px-4">{{ __('common.confirm_delete_action') }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    const config = document.getElementById('trainersConfig');
    const storeRoute = config.dataset.storeRoute;
    const updateRouteTemplate = config.dataset.updateRouteTemplate;
    const deleteRouteTemplate = config.dataset.deleteRouteTemplate;
    const addTitle = config.dataset.addTitle;
    const editTitle = config.dataset.editTitle;

    function openAddModal(clear = true) {
        const form = document.getElementById('trainerForm');
        form.action = storeRoute;
        document.getElementById('methodField').value = "POST";
        document.getElementById('trainerModalLabel').innerText = addTitle;

        if (clear) {
            document.getElementById('trainerId').value = "";
            document.getElementById('name_ar').value = "";
            document.getElementById('name_en').value = "";
            document.getElementById('details_ar').value = "";
            document.getElementById('details_en').value = "";
            document.getElementById('percentage').value = "";
            document.getElementById('facebook').value = "";
            document.getElementById('instagram').value = "";
            document.getElementById('tiktok').value = "";
            document.getElementById('youtube').value = "";
            document.getElementById('twitter').value = "";
            document.getElementById('website').value = "";
            document.getElementById('image').value = "";
        }

        const modal = new bootstrap.Modal(document.getElementById('trainerModal'));
        modal.show();
    }

    function openEditModal(button) {
        const item = JSON.parse(button.dataset.item);
        const form = document.getElementById('trainerForm');
        form.action = updateRouteTemplate.replace('/0', '/' + item.id);

        document.getElementById('methodField').value = "PUT";
        document.getElementById('trainerId').value = item.id;
        document.getElementById('trainerModalLabel').innerText = editTitle;
        document.getElementById('name_ar').value = item.name_ar ?? "";
        document.getElementById('name_en').value = item.name_en ?? "";
        document.getElementById('details_ar').value = item.details_ar ?? "";
        document.getElementById('details_en').value = item.details_en ?? "";
        document.getElementById('percentage').value = item.percentage ?? "";
        document.getElementById('facebook').value = item.facebook ?? "";
        document.getElementById('instagram').value = item.instagram ?? "";
        document.getElementById('tiktok').value = item.tiktok ?? "";
        document.getElementById('youtube').value = item.youtube ?? "";
        document.getElementById('twitter').value = item.twitter ?? "";
        document.getElementById('website').value = item.website ?? "";
        document.getElementById('image').value = "";

        const modal = new bootstrap.Modal(document.getElementById('trainerModal'));
        modal.show();
    }

    function openDeleteModal(button) {
        const id = button.dataset.id;
        const form = document.getElementById('deleteForm');
        form.action = deleteRouteTemplate.replace('/0', '/' + id);

        const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
        modal.show();
    }

    const hasErrors = config.dataset.hasErrors === '1';
    if (hasErrors) {
        document.addEventListener('DOMContentLoaded', function() {
            const oldData = JSON.parse(config.dataset.old || '{}');
            if (oldData.id) {
                const fakeButton = document.createElement('button');
                fakeButton.dataset.item = JSON.stringify(oldData);
                openEditModal(fakeButton);
            } else {
                openAddModal(false);
            }
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.sa-progress-bar[data-progress]').forEach(function(el) {
            const value = parseFloat(el.dataset.progress || '0');
            const safeValue = Math.min(100, Math.max(0, isNaN(value) ? 0 : value));
            el.style.width = safeValue + '%';
        });
    });
</script>
@endsection
