@extends('layouts.app')

@section('title', $service->name ?? __('subscriptions.one_time_service'))

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

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4 class="fw-bold m-0">{{ $service->name ?? __('subscriptions.one_time_service') }}</h4>
                <div class="d-flex align-items-center gap-2">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addSubscriberModal" onclick="resetForm()">
                        <i class="bi bi-person-plus-fill me-2"></i> {{ __('pos.add_customer') }}
                    </button>
                    <a href="{{ url()->previous() }}" class="btn btn-outline-secondary">
                        <i class="bi {{ app()->getLocale() == 'ar' ? 'bi-arrow-right' : 'bi-arrow-left' }}"></i> {{ __('common.back') }}
                    </a>
                </div>
            </div>
            
            <!-- Smart Search -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="input-group shadow-sm">
                        <span class="input-group-text bg-white border-end-0"><i class="bi bi-search text-muted"></i></span>
                        <input type="text" class="form-control border-start-0 ps-0" id="searchInput" placeholder="{{ __('subscriptions.search_placeholder') }}" value="{{ request('search') }}" autocomplete="off">
                    </div>
                </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(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 alert-dismissible fade show" role="alert">
                    <ul class="mb-0">
                        @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="subscriptions-list" id="subscriptionsList">
                @include('services.one_time_service.partials.list')
            </div>
        </div>
    </div>
</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="addSubscriberModal" 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" id="modalTitle">{{ __('pos.add_customer') }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="subscriberForm" action="{{ route('services.one_time_service.store') }}" method="POST">
                @csrf
                <div id="methodField"></div>
                <input type="hidden" name="service_id" value="{{ $service->id }}">
                
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="customer_name" class="form-label">{{ __('subscriptions.customer_name') }} <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="customer_name" name="customer_name" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="phone" class="form-label">{{ __('subscriptions.phone') }} <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="phone" name="phone" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="whatsapp" class="form-label">{{ __('subscriptions.whatsapp') }} <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="whatsapp" name="whatsapp" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="business_name" class="form-label">{{ __('subscriptions.business_name') }} <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="business_name" name="business_name" required>
                        </div>
                        
                        <div class="col-12">
                            <label for="address" class="form-label">{{ __('subscriptions.address') }} <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="address" name="address" rows="2" required></textarea>
                        </div>
                        
                        <div class="col-md-12">
                            <label for="business_url" class="form-label">{{ __('subscriptions.business_url') }}</label>
                            <input type="url" class="form-control" id="business_url" name="business_url" placeholder="https://...">
                        </div>

                        <div class="col-md-6">
                            <label for="consultations_count" class="form-label">عدد جلسات الاستشارات <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="consultations_count" name="consultations_count" value="1" min="1" step="1" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="price" class="form-label">{{ __('subscriptions.price') }} <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="price" name="price" value="{{ isset($service->price) ? number_format($service->price, 0, '', '') : 0 }}" min="0" step="1" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label for="payment_method" class="form-label">{{ __('subscriptions.payment_method') }} <span class="text-danger">*</span></label>
                            <select class="form-select" id="payment_method" name="payment_method" required>
                                <option value="Cash">{{ __('subscriptions.payment_methods.Cash') }}</option>
                                <option value="Zain Cash">{{ __('subscriptions.payment_methods.Zain Cash') }}</option>
                                <option value="POS">{{ __('subscriptions.payment_methods.POS') }}</option>
                                <option value="Qi">{{ __('subscriptions.payment_methods.Qi') }}</option>
                                <option value="Switch">{{ __('subscriptions.payment_methods.Switch') }}</option>
                            </select>
                        </div>

                        @if(auth()->user()?->is_admin)
                            <div class="col-md-6">
                                <label for="sales_employee_id" class="form-label">{{ __('subscriptions.sales_employee') }}</label>
                                <select class="form-select" id="sales_employee_id" name="sales_employee_id">
                                    <option value="">{{ __('common.choose') ?? 'Choose' }}</option>
                                    @foreach(($employees ?? collect()) as $employee)
                                        <option value="{{ $employee->id }}">{{ $employee->full_name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        @endif
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('cancel') ?? 'Cancel' }}</button>
                    <button type="submit" class="btn btn-primary">{{ __('save') ?? 'Save' }}</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteSubscriberModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ __('confirm_delete') ?? 'Confirm Delete' }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>{{ __('delete_confirmation_message') ?? 'Are you sure you want to delete this subscriber?' }}</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('cancel') ?? 'Cancel' }}</button>
                <form id="deleteForm" method="POST" action="">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger">{{ __('delete') ?? 'Delete' }}</button>
                </form>
            </div>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script>
    let searchTimeout;
    document.getElementById('searchInput').addEventListener('input', function(e) {
        clearTimeout(searchTimeout);
        const query = e.target.value;
        
        searchTimeout = setTimeout(() => {
            fetch(`{{ route('services.one_time_service.index') }}?service_id={{ $service->id }}&search=${query}`, {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.text())
            .then(html => {
                document.getElementById('subscriptionsList').innerHTML = html;
            });
        }, 300);
    });

    function resetForm() {
        document.getElementById('subscriberForm').action = "{{ route('services.one_time_service.store') }}";
        document.getElementById('methodField').innerHTML = '';
        document.getElementById('modalTitle').innerText = "{{ __('pos.add_customer') }}";
        
        document.getElementById('customer_name').value = '';
        document.getElementById('phone').value = '';
        document.getElementById('whatsapp').value = '';
        document.getElementById('address').value = '';
        document.getElementById('business_name').value = '';
        document.getElementById('business_url').value = '';
        document.getElementById('consultations_count').value = '1';
        document.getElementById('price').value = "{{ isset($service->price) ? number_format($service->price, 0, '', '') : 0 }}";
        document.getElementById('payment_method').value = 'Cash';
        const salesEmployeeSelect = document.getElementById('sales_employee_id');
        if (salesEmployeeSelect) {
            salesEmployeeSelect.value = '';
        }
    }

    function openEditModal(button) {
        const id = button.getAttribute('data-id');
        const data = {
            customer_name: button.getAttribute('data-customer_name'),
            phone: button.getAttribute('data-phone'),
            whatsapp: button.getAttribute('data-whatsapp'),
            address: button.getAttribute('data-address'),
            business_name: button.getAttribute('data-business_name'),
            business_url: button.getAttribute('data-business_url'),
            consultations_count: button.getAttribute('data-consultations_count'),
            price: button.getAttribute('data-price'),
            payment_method: button.getAttribute('data-payment_method'),
            sales_employee_id: button.getAttribute('data-sales_employee_id')
        };
        
        const form = document.getElementById('subscriberForm');
        form.action = "{{ route('services.one_time_service.update', ['id' => '__ID__']) }}".replace('__ID__', id);
        
        document.getElementById('methodField').innerHTML = '<input type="hidden" name="_method" value="PUT">';
        document.getElementById('modalTitle').innerText = "{{ __('subscriptions.edit_subscriber') }}";
        
        document.getElementById('customer_name').value = data.customer_name;
        document.getElementById('phone').value = data.phone;
        document.getElementById('whatsapp').value = data.whatsapp;
        document.getElementById('address').value = data.address;
        document.getElementById('business_name').value = data.business_name;
        document.getElementById('business_url').value = data.business_url;
        document.getElementById('consultations_count').value = data.consultations_count || '1';
        document.getElementById('price').value = data.price;
        document.getElementById('payment_method').value = data.payment_method;
        const salesEmployeeSelect = document.getElementById('sales_employee_id');
        if (salesEmployeeSelect) {
            salesEmployeeSelect.value = data.sales_employee_id || '';
        }
        
        const modal = new bootstrap.Modal(document.getElementById('addSubscriberModal'));
        modal.show();
    }

    function openDeleteModal(id) {
        const form = document.getElementById('deleteForm');
        form.action = "{{ route('services.one_time_service.destroy', ['id' => '__ID__']) }}".replace('__ID__', id);
        
        const modal = new bootstrap.Modal(document.getElementById('deleteSubscriberModal'));
        modal.show();
    }
</script>
@endpush
