@extends('layouts.dashboard')

@section('title', 'Template Assignment')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="mb-1">Template Assignment</h4>
        <p class="text-muted mb-0">Assign global templates to client organizations</p>
    </div>
</div>

<div class="row g-4">
    <!-- Global Templates -->
    <div class="col-lg-5">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-transparent">
                <h6 class="mb-0"><i class="bi bi-file-text me-2"></i>Global Templates</h6>
            </div>
            <div class="card-body">
                @if($globalTemplates->count() > 0)
                <div class="alert alert-info small">
                    <i class="bi bi-info-circle me-2"></i>
                    Select templates to assign to a client. Clients can customize assigned templates.
                </div>
                <form id="assignForm">
                    @csrf
                    <div class="list-group list-group-flush">
                        @foreach($globalTemplates as $template)
                        <label class="list-group-item d-flex align-items-center gap-3">
                            <input type="checkbox" class="form-check-input template-checkbox" name="template_ids[]" value="{{ $template->id }}">
                            <div class="flex-grow-1">
                                <div class="fw-medium">{{ $template->name }}</div>
                                <small class="text-muted">
                                    <span class="badge bg-light text-dark">{{ ucfirst($template->type) }}</span>
                                </small>
                            </div>
                        </label>
                        @endforeach
                    </div>
                </form>
                @else
                <div class="text-center text-muted py-4">
                    <i class="bi bi-file-earmark-x" style="font-size: 2rem;"></i>
                    <p class="mb-0 mt-2">No global templates available</p>
                    <a href="{{ route('dashboard.templates.create') }}" class="btn btn-sm btn-primary mt-2">
                        Create Template
                    </a>
                </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Client Selection -->
    <div class="col-lg-7">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-transparent">
                <h6 class="mb-0"><i class="bi bi-building me-2"></i>Select Client</h6>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    @forelse($clients as $client)
                    <div class="col-md-6">
                        <div class="card h-100 client-card" data-client-id="{{ $client->id }}" style="cursor: pointer;">
                            <div class="card-body">
                                <div class="d-flex align-items-center gap-2 mb-2">
                                    <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center" style="width: 36px; height: 36px;">
                                        {{ strtoupper(substr($client->name, 0, 1)) }}
                                    </div>
                                    <div>
                                        <div class="fw-medium">{{ $client->name }}</div>
                                        <small class="text-muted">{{ $client->templates_count }} templates</small>
                                    </div>
                                </div>
                                <div class="d-flex gap-1">
                                    @php
                                    $badgeClass = match($client->subscription_type) {
                                    'trial' => 'bg-warning',
                                    'basic' => 'bg-info',
                                    'premium' => 'bg-danger',
                                    'enterprise' => 'bg-purple',
                                    default => 'bg-secondary'
                                    };
                                    @endphp
                                    <span class="badge {{ $badgeClass }} small">{{ ucfirst($client->subscription_type) }}</span>
                                    @if($client->is_active && !$client->isSubscriptionExpired())
                                    <span class="badge bg-success small">Active</span>
                                    @else
                                    <span class="badge bg-secondary small">Inactive</span>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    @empty
                    <div class="col-12">
                        <div class="text-center text-muted py-4">
                            <i class="bi bi-building-x" style="font-size: 2rem;"></i>
                            <p class="mb-0 mt-2">No clients available</p>
                            <a href="{{ route('dashboard.clients.create') }}" class="btn btn-sm btn-primary mt-2">
                                Create Client
                            </a>
                        </div>
                    </div>
                    @endforelse
                </div>
            </div>
        </div>

        <!-- Client Templates (shown when client is selected) -->
        <div class="card border-0 shadow-sm mt-4" id="clientTemplatesCard" style="display: none;">
            <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
                <h6 class="mb-0">
                    <i class="bi bi-file-text me-2"></i>
                    <span id="selectedClientName">Client</span>'s Templates
                </h6>
                <button type="button" class="btn btn-primary btn-sm" id="assignBtn" disabled>
                    <i class="bi bi-plus-lg me-1"></i>Assign Selected
                </button>
            </div>
            <div class="card-body" id="clientTemplatesList">
                <!-- Loaded via AJAX -->
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .bg-purple {
        background-color: #8b5cf6 !important;
    }

    .client-card {
        transition: all 0.2s;
        border: 2px solid transparent;
    }

    .client-card:hover {
        border-color: #667eea;
    }

    .client-card.selected {
        border-color: #667eea;
        background-color: #f8f9fa;
    }
</style>
@endpush

@push('scripts')
<script>
    let selectedClientId = null;

    // Client selection
    document.querySelectorAll('.client-card').forEach(card => {
        card.addEventListener('click', function() {
            document.querySelectorAll('.client-card').forEach(c => c.classList.remove('selected'));
            this.classList.add('selected');

            selectedClientId = this.dataset.clientId;
            loadClientTemplates(selectedClientId);
        });
    });

    // Load client templates
    function loadClientTemplates(clientId) {
        const card = document.getElementById('clientTemplatesCard');
        const list = document.getElementById('clientTemplatesList');
        const nameSpan = document.getElementById('selectedClientName');

        card.style.display = 'block';
        list.innerHTML = '<div class="text-center py-3"><div class="spinner-border spinner-border-sm"></div></div>';

        fetch(`{{ url('/admin/clients') }}/${clientId}/templates`)
            .then(res => res.json())
            .then(data => {
                nameSpan.textContent = data.client.name;

                if (data.templates.length === 0) {
                    list.innerHTML = '<div class="text-center text-muted py-3">No templates assigned yet</div>';
                } else {
                    let html = '<div class="list-group list-group-flush">';
                    data.templates.forEach(t => {
                        html += `
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                <div>
                                    <div class="fw-medium">${t.name}</div>
                                    <small class="text-muted">
                                        <span class="badge bg-light text-dark">${t.type}</span>
                                        ${t.is_derived ? '<span class="badge bg-info">Modified</span>' : ''}
                                    </small>
                                </div>
                                <form method="POST" action="{{ url('/admin/template-assignment') }}/${clientId}/${t.id}" style="display:inline;">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="Remove"
                                        data-confirm="Remove this template from the organization?"
                                        data-confirm-title="Remove Template"
                                        data-confirm-btn="Remove"
                                        data-confirm-class="btn-danger">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </div>
                        `;
                    });
                    html += '</div>';
                    list.innerHTML = html;

                    // Re-wire data-confirm handlers for dynamically added elements
                    list.querySelectorAll('[data-confirm]').forEach(function(el) {
                        el.addEventListener('click', function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            const title = el.getAttribute('data-confirm-title') || 'Confirm Action';
                            const message = el.getAttribute('data-confirm') || 'Are you sure?';
                            const btnText = el.getAttribute('data-confirm-btn') || 'Confirm';
                            const btnClass = el.getAttribute('data-confirm-class') || 'btn-danger';
                            const form = el.closest('form');
                            if (form) {
                                confirmAction(form, title, message, btnText, btnClass);
                            }
                        });
                    });
                }

                updateAssignButton();
            })
            .catch(err => {
                list.innerHTML = '<div class="text-center text-danger py-3">Error loading templates</div>';
            });
    }

    // Template checkbox change
    document.querySelectorAll('.template-checkbox').forEach(cb => {
        cb.addEventListener('change', updateAssignButton);
    });

    function updateAssignButton() {
        const btn = document.getElementById('assignBtn');
        const checked = document.querySelectorAll('.template-checkbox:checked').length;
        btn.disabled = !selectedClientId || checked === 0;
    }

    // Assign templates
    document.getElementById('assignBtn').addEventListener('click', function() {
        if (!selectedClientId) return;

        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `{{ url('/admin/template-assignment') }}/${selectedClientId}`;

        const csrf = document.createElement('input');
        csrf.type = 'hidden';
        csrf.name = '_token';
        csrf.value = '{{ csrf_token() }}';
        form.appendChild(csrf);

        document.querySelectorAll('.template-checkbox:checked').forEach(cb => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'template_ids[]';
            input.value = cb.value;
            form.appendChild(input);
        });

        document.body.appendChild(form);
        form.submit();
    });
</script>
@endpush