@extends('layouts.app')

@section('title', $title ?? __('renewals.title'))

@push('styles')
<link href="{{ asset('css/stage-academy.css') }}" rel="stylesheet">
<link href="{{ asset('css/accounts.css') }}" rel="stylesheet">
<style>
    .renewals-card .sa-icon {
        width: 52px;
        height: 52px;
        font-size: 1.35rem;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(13, 110, 253, 0.1);
        color: #0d6efd;
    }

    .renewals-card.promotion .sa-icon {
        background: rgba(25, 135, 84, 0.12);
        color: #198754;
    }

    body.dark-mode .renewals-card .sa-icon {
        background: rgba(59, 130, 246, 0.16);
        color: #93c5fd;
    }

    body.dark-mode .renewals-card.promotion .sa-icon {
        background: rgba(34, 197, 94, 0.16);
        color: #86efac;
    }

    .renewal-card {
        transition: transform 0.2s;
    }
    .renewal-card:hover {
        transform: translateY(-2px);
    }
    .status-badge {
        font-size: 0.8rem;
        padding: 0.25rem 0.5rem;
        border-radius: 4px;
    }
    .status-overdue {
        background-color: #ffebee;
        color: #c62828;
        border: 1px solid #ffcdd2;
    }
    .status-due-soon {
        background-color: #fff3e0;
        color: #ef6c00;
        border: 1px solid #ffe0b2;
    }
    .status-upcoming {
        background-color: #e8f5e9;
        color: #2e7d32;
        border: 1px solid #c8e6c9;
    }

    /* Dark Mode Overrides */
    body.dark-mode .status-overdue {
        background-color: rgba(198, 40, 40, 0.2);
        color: #ef9a9a;
        border-color: rgba(198, 40, 40, 0.3);
    }
    body.dark-mode .status-due-soon {
        background-color: rgba(239, 108, 0, 0.2);
        color: #ffcc80;
        border-color: rgba(239, 108, 0, 0.3);
    }
    body.dark-mode .status-upcoming {
        background-color: rgba(46, 125, 50, 0.2);
        color: #a5d6a7;
        border-color: rgba(46, 125, 50, 0.3);
    }
    
    body.dark-mode .table {
        color: #e2e8f0;
        border-color: #334155;
    }
    
    body.dark-mode .table > :not(caption) > * > * {
        background-color: transparent;
        color: inherit;
        border-color: #334155;
    }
    
    body.dark-mode .table-hover tbody tr:hover {
        background-color: rgba(255, 255, 255, 0.05);
    }
</style>
@endpush

@section('content')
<div class="container-fluid">
    @if(isset($renewals))
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-1">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('dashboard') }}</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('renewals') }}">{{ __('renewals.title') }}</a></li>
                        <li class="breadcrumb-item active" aria-current="page">{{ $title }}</li>
                    </ol>
                </nav>
                <h4 class="fw-bold mb-0">{{ $title }}</h4>
            </div>
            <a href="{{ route('renewals') }}" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-arrow-left"></i>
                <span class="ms-1">{{ __('back') }}</span>
            </a>
        </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

        <div class="row mb-4">
            <div class="col-12">
                <form action="{{ $searchRoute }}" method="GET">
                    <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="search" class="form-control border-start-0 ps-0" name="search" placeholder="{{ __('subscriptions.search_placeholder') }}" value="{{ request('search') }}">
                    </div>
                </form>
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th class="py-3 ps-4">{{ __('subscriptions.customer_name') }}</th>
                                <th class="py-3">{{ __('service_type') }}</th>
                                <th class="py-3">{{ __('subscriptions.renewal_due_date') }}</th>
                                <th class="py-3">{{ __('subscriptions.renewal_amount') }}</th>
                                <th class="py-3">{{ __('status') }}</th>
                                <th class="py-3 text-end pe-4">{{ __('subscriptions.actions') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($renewals as $renewal)
                                @php
                                    $dueDate = $renewal->renewal_due_date
                                        ? \Carbon\Carbon::parse($renewal->renewal_due_date)->locale(app()->getLocale())
                                        : null;
                                    $now = \Carbon\Carbon::now()->locale(app()->getLocale());
                                    if (
                                        $dueDate
                                        && in_array($renewal->service?->type, ['monthly_subscription_open', 'monthly_subscription_limited'], true)
                                        && $dueDate->copy()->endOfDay()->gt($now->copy()->startOfDay()->addDays(30)->endOfDay())
                                    ) {
                                        $dueDate = $now->copy()->startOfDay()->addDays(30);
                                    }
                                    $daysDiff = $dueDate ? $now->diffInDays($dueDate, false) : null;

                                    if (($renewal->service?->type === 'monthly_subscription_limited') && $renewal->is_expired) {
                                        $statusClass = 'status-overdue';
                                        $statusText = __('status_expired');
                                    } elseif ($daysDiff !== null && $daysDiff < 0) {
                                        $statusClass = 'status-overdue';
                                        $statusText = __('status_overdue');
                                    } elseif ($daysDiff !== null && $daysDiff <= 30) {
                                        $statusClass = 'status-due-soon';
                                        $statusText = __('status_due_soon');
                                    } else {
                                        $statusClass = 'status-upcoming';
                                        $statusText = __('status_upcoming');
                                    }

                                    $route = '#';
                                    if ($renewal->service) {
                                        switch ($renewal->service->type) {
                                            case 'web_development':
                                                $route = route('services.web_development.index', ['search' => $renewal->invoice_number]);
                                                break;
                                            case 'app_development':
                                                $route = route('services.app_development.index', ['search' => $renewal->invoice_number]);
                                                break;
                                            case 'domains_emails':
                                                $route = route('services.domains_emails.index', ['search' => $renewal->invoice_number]);
                                                break;
                                            case 'wordpress_templates':
                                                $route = route('services.wordpress_templates.index', ['search' => $renewal->invoice_number]);
                                                break;
                                            case 'ads_creation':
                                                $route = route('services.ads_creation.index', ['search' => $renewal->invoice_number]);
                                                break;
                                            case 'monthly_subscription_open':
                                                $route = route('services.monthly_subscription_open.index', ['search' => $renewal->invoice_number]);
                                                break;
                                            case 'monthly_subscription_limited':
                                                $route = route('services.monthly_subscription_limited.index', ['search' => $renewal->invoice_number]);
                                                break;
                                            case 'one_time_service':
                                                $route = route('services.one_time_service.index', ['search' => $renewal->invoice_number]);
                                                break;
                                        }
                                    }
                                @endphp
                                <tr>
                                    <td class="ps-4">
                                        <div class="fw-bold">{{ $renewal->customer_name }}</div>
                                        <small class="text-muted">{{ $renewal->phone }}</small>
                                    </td>
                                    <td>
                                        @if($renewal->service)
                                            {{ $renewal->service->name }}
                                        @else
                                            -
                                        @endif
                                    </td>
                                    <td>
                                        <div>{{ $dueDate ? $dueDate->format('Y-m-d') : '-' }}</div>
                                        @if($dueDate)
                                            <small class="text-muted">{{ $dueDate->diffForHumans() }}</small>
                                        @endif
                                    </td>
                                    <td>{{ number_format($renewal->renewal_amount, 0) }}</td>
                                    <td>
                                        <span class="status-badge {{ $statusClass }}">
                                            {{ $statusText }}
                                        </span>
                                    </td>
                                    <td class="text-end pe-4">
                                        @php
                                            $canQuickRenew =
                                                (auth()->user()->hasPermission('customers.renewals.create') ?? false)
                                                || (auth()->user()->hasPermission('renewals.promotion.create') ?? false)
                                                || (auth()->user()->hasPermission('renewals.software.create') ?? false)
                                                || (auth()->user()->hasPermission('renewals.view') ?? false)
                                                || (auth()->user()->hasPermission('renewals.promotion.view') ?? false)
                                                || (auth()->user()->hasPermission('renewals.software.view') ?? false);
                                        @endphp
                                        @if($canQuickRenew)
                                            <button
                                                type="button"
                                                class="btn btn-sm btn-outline-success me-1"
                                                title="{{ __('quick_renew') }}"
                                                onclick="openRenewModal('{{ $renewal->id }}', '{{ $renewal->invoice_number }}', '{{ $renewal->renewal_due_date }}', '{{ $renewal->renewal_amount }}', '{{ $renewal->payment_method }}')"
                                            >
                                                <i class="bi bi-lightning-charge"></i>
                                            </button>
                                        @else
                                            <button
                                                type="button"
                                                class="btn btn-sm btn-outline-secondary me-1"
                                                title="لا تملك صلاحية التجديد"
                                                disabled
                                            >
                                                <i class="bi bi-lightning-charge"></i>
                                            </button>
                                        @endif
                                        @php
                                            $serviceType = $renewal->service->type ?? '';
                                            $isExcluded = in_array($serviceType, ['monthly_subscription_open', 'monthly_subscription_limited']);
                                        @endphp

                                        @if(!$isExcluded)
                                            @php
                                                $rawName = $renewal->customer_name;
                                                $customerName = explode(' - ', $rawName)[0];

                                                $businessName = $renewal->business_name ?? __('N/A');
                                                $projectDetails = $renewal->details ?? '';
                                                $projectType = $renewal->service ? __('service_types.' . $renewal->service->type) : '';
                                                $projectLink = $renewal->business_url ?? '';
                                                $expiryDate = $dueDate->format('Y-m-d');
                                                $remainingDays = (int) abs($daysDiff);
                                                $daysText = $daysDiff >= 0 ? "باقي $remainingDays يوم" : "منذ $remainingDays يوم";
                                                $amount = number_format($renewal->renewal_amount, 0);

                                                $message = "السيد/السيدة $customerName المحترم(ة)،\n\n";
                                                if ($projectDetails) {
                                                    $message .= "تفاصيل المشروع: $projectDetails\n";
                                                }
                                                $message .= "اسم العمل: $businessName\n";
                                                $message .= "نوع المشروع: $projectType\n";
                                                if ($projectLink) {
                                                    $message .= "رابط المشروع: $projectLink\n";
                                                }
                                                $message .= "\nنود إعلامكم بقرب انتهاء مدة اشتراك الخدمات المقدمة، ونرجو منكم التفضل بتجديد الاشتراك قبل تاريخ الانتهاء في {$expiryDate}، ($daysText)، لتجنب التوقف وحذف البيانات.\n";
                                                $message .= "💰 مبلغ تجديد الاشتراك: $amount دينار عراقي\n\n";
                                                $message .= "⚠️ ملاحظة مهمة:\nفي حال عدم تسديد مبلغ التجديد ضمن المدة المحددة، ستقوم الشركات المختصة بفرض غرامة تأخيرية تتراوح بين ٨٠ إلى ١٠٠ دولار أمريكي، أو قد يتم حجب اسم الموقع (Domain) بشكل مؤقت أو دائم دون إشعار آخر.\n";
                                                $message .= "لضمان استمرارية الخدمة وتفادي أي انقطاع، يرجى الإسراع بإتمام عملية التسديد في أقرب وقت ممكن.\n";
                                                $message .= "للاستفسار أو تأكيد الدفع، يرجى التواصل مع قسم الدعم الفني.\n";
                                                $message .= "مع فائق الاحترام،\nإدارة النظام / الدعم الفني";

                                                $phone = preg_replace('/[^0-9]/', '', $renewal->phone);
                                                if (str_starts_with($phone, '0')) {
                                                    $phone = '964' . substr($phone, 1);
                                                } elseif (!str_starts_with($phone, '964')) {
                                                    $phone = '964' . $phone;
                                                }

                                                $whatsappUrl = "https://wa.me/$phone?text=" . urlencode($message);
                                            @endphp
                                            <a href="{{ $whatsappUrl }}" target="_blank" class="btn btn-sm btn-outline-success" title="{{ __('send_reminder') }}">
                                                <i class="bi bi-whatsapp"></i>
                                            </a>
                                        @else
                                            <a href="{{ route('renewals.history', $renewal->id) }}" class="btn btn-sm btn-outline-primary" title="{{ __('view_details') }}">
                                                <i class="bi bi-eye"></i>
                                            </a>
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="6" class="text-center py-5 text-muted">
                                        <i class="bi bi-calendar-x fs-1 mb-3 d-block"></i>
                                        {{ __('no_renewals_found') }}
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            @if($renewals->hasPages())
                <div class="card-footer bg-white border-top-0 py-3">
                    {{ $renewals->links() }}
                </div>
            @endif
        </div>
    @else
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-1">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('dashboard') }}</a></li>
                        <li class="breadcrumb-item active" aria-current="page">{{ __('renewals.title') }}</li>
                    </ol>
                </nav>
                <h4 class="fw-bold mb-0">{{ __('renewals.title') }}</h4>
            </div>
        </div>

        <div class="row g-3 accounts-grid">
            <div class="col-12 col-md-6 col-lg-4 col-xl-3">
                <a href="{{ route('renewals.software') }}" class="accounts-link text-decoration-none">
                    <div class="card sa-card renewals-card">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="sa-icon"><i class="bi bi-code-slash"></i></div>
                            <div class="sa-text">
                                <h6 class="mb-0 fw-bold">{{ __('renewals.cards.software') }}</h6>
                            </div>
                        </div>
                    </div>
                </a>
            </div>

            <div class="col-12 col-md-6 col-lg-4 col-xl-3">
                <a href="{{ route('renewals.promotion') }}" class="accounts-link text-decoration-none">
                    <div class="card sa-card renewals-card promotion">
                        <div class="card-body d-flex align-items-center gap-3">
                            <div class="sa-icon"><i class="bi bi-megaphone"></i></div>
                            <div class="sa-text">
                                <h6 class="mb-0 fw-bold">{{ __('renewals.cards.promotion') }}</h6>
                            </div>
                        </div>
                    </div>
                </a>
            </div>
        </div>
    @endif
</div>

@if(isset($renewals))
    <div class="modal fade" id="renewModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow">
                <form id="renewForm" action="" method="POST">
                    @csrf
                    <div class="modal-header border-bottom-0">
                        <h5 class="modal-title fw-bold">{{ __('renew_subscription') }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-info d-flex align-items-center mb-4">
                            <i class="bi bi-info-circle-fill fs-4 me-3"></i>
                            <div>
                                <div class="small text-uppercase fw-bold opacity-75">{{ __('invoice_number') }}</div>
                                <div class="fw-bold" id="modalInvoiceNumber">...</div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">{{ __('new_renewal_date') }}</label>
                            <input type="date" name="renewal_date" class="form-control" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">{{ __('subscriptions.payment_method') }}</label>
                            <select name="payment_method" class="form-select" 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>

                        <div class="mb-3">
                            <label class="form-label">{{ __('amount') }}</label>
                            <div class="input-group">
                                <input type="number" name="amount" class="form-control" step="0.01" required>
                                <span class="input-group-text">IQD</span>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">{{ __('note') }} <span class="text-muted small">({{ __('optional') }})</span></label>
                            <textarea name="note" class="form-control" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer border-top-0">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">{{ __('cancel') }}</button>
                        <button type="submit" class="btn btn-primary px-4">{{ __('confirm_renewal') }}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @push('scripts')
        <script>
            function openRenewModal(id, invoice, currentDueDate, renewalAmount, paymentMethod) {
                const form = document.getElementById('renewForm');
                const renewUrlTemplate = "{{ route('customers.renew', ['id' => '__ID__']) }}";
                form.action = renewUrlTemplate.replace('__ID__', id);

                document.getElementById('modalInvoiceNumber').textContent = invoice;

                const dateInput = form.querySelector('input[name="renewal_date"]');
                if (dateInput) {
                    const baseDate = new Date();
                    baseDate.setDate(baseDate.getDate() + 30);
                    dateInput.value = baseDate.toISOString().slice(0, 10);
                }

                const amountInput = form.querySelector('input[name="amount"]');
                if (amountInput) {
                    const raw = (renewalAmount || '').toString().trim();
                    amountInput.value = raw !== '' ? raw : 0;
                }

                const paymentSelect = form.querySelector('select[name="payment_method"]');
                if (paymentSelect) {
                    const value = (paymentMethod || '').toString().trim();
                    paymentSelect.value = value !== '' ? value : 'Cash';
                }

                new bootstrap.Modal(document.getElementById('renewModal')).show();
            }
        </script>
    @endpush
@endif
@endsection
