@extends('layouts.admin')

@section('title', 'Quotations')

@section('page-title', 'Quotations')

@section('content')
<style>
    @media print {
        .no-print-quotations { display: none !important; }
        #quotations-print-area { display: block !important; }
    }
</style>
<div class="max-w-[1400px] mx-auto p-6 lg:p-10 space-y-6">
    <div class="no-print-quotations flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div class="space-y-1">
            <nav class="flex flex-wrap items-center gap-2 text-sm text-gray-500">
                <a class="hover:text-primary transition-colors" href="{{ route('admin.dashboard') }}">Home</a>
                <span class="material-symbols-outlined text-[14px]">chevron_right</span>
                <a class="hover:text-primary transition-colors" href="#">Sales</a>
                <span class="material-symbols-outlined text-[14px]">chevron_right</span>
                <span class="text-gray-900 font-medium">Quotations</span>
            </nav>
            <h1 class="text-2xl font-bold tracking-tight text-gray-900">Quotations</h1>
        </div>
        <div class="flex flex-wrap gap-3">
            <button type="button" class="hidden sm:flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-200 shadow-sm transition-all">
                <span class="material-symbols-outlined text-[20px]">file_upload</span>
                <span>Import</span>
            </button>
            <a href="{{ route('admin.quotations.create') }}" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-bold shadow-lg shadow-primary/30 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-all">
                <span class="material-symbols-outlined text-[20px]">add</span>
                <span>New Quotation</span>
            </a>
        </div>
    </div>

    <div class="no-print-quotations bg-white rounded-xl shadow-sm border border-gray-200 p-4 sm:p-5">
        <form method="GET" action="{{ route('admin.quotations.index') }}" id="quotation-filters-form" class="flex flex-col gap-4">
            <div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:gap-3">
                <div class="relative group w-full lg:flex-[2]">
                    <label class="block text-xs font-medium text-gray-500 mb-1 lg:hidden">Search</label>
                    <span class="absolute bottom-2.5 left-3 text-gray-400 group-focus-within:text-primary pointer-events-none material-symbols-outlined text-[20px]">search</span>
                    <input name="search" value="{{ request('search') }}" class="w-full py-2.5 pl-10 pr-3 text-sm border border-gray-200 rounded-lg focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" placeholder="Search by number, customer, email..." type="search"/>
                </div>
                <div class="relative w-full lg:flex-1">
                    <label class="block text-xs font-medium text-gray-500 mb-1 lg:hidden">Status</label>
                    <select name="status" onchange="this.form.submit()" class="w-full appearance-none bg-white border border-gray-200 text-gray-700 py-2.5 pl-3 pr-10 rounded-lg text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary cursor-pointer hover:border-gray-300 transition-colors">
                        <option value="">Status: All</option>
                        <option value="draft" {{ request('status') == 'draft' ? 'selected' : '' }}>Pending</option>
                        <option value="accepted" {{ request('status') == 'accepted' ? 'selected' : '' }}>Approved</option>
                        <option value="rejected" {{ request('status') == 'rejected' ? 'selected' : '' }}>Rejected</option>
                    </select>
                    <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                        <span class="material-symbols-outlined text-[20px]">expand_more</span>
                    </div>
                </div>
                <div class="relative w-full lg:flex-[1.4]">
                    <label class="block text-xs font-medium text-gray-500 mb-1 lg:hidden">Customer</label>
                    <select name="customer_id" onchange="this.form.submit()" class="w-full appearance-none bg-white border border-gray-200 text-gray-700 py-2.5 pl-3 pr-10 rounded-lg text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary cursor-pointer">
                        <option value="">Customer: All</option>
                        @foreach($customers as $customer)
                            <option value="{{ $customer->id }}" {{ (string) request('customer_id') === (string) $customer->id ? 'selected' : '' }}>{{ $customer->name }}</option>
                        @endforeach
                    </select>
                    <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-500">
                        <span class="material-symbols-outlined text-[20px]">expand_more</span>
                    </div>
                </div>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 w-full lg:flex-[1.8]">
                    <div>
                        <label class="block text-xs font-medium text-gray-500 mb-1 lg:hidden">From</label>
                        <input type="date" name="date_from" value="{{ request('date_from') }}" class="w-full py-2.5 px-3 text-sm border border-gray-200 rounded-lg focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"/>
                    </div>
                    <div>
                        <label class="block text-xs font-medium text-gray-500 mb-1 lg:hidden">To</label>
                        <input type="date" name="date_to" value="{{ request('date_to') }}" class="w-full py-2.5 px-3 text-sm border border-gray-200 rounded-lg focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"/>
                    </div>
                </div>
            </div>
            <div class="mt-1 border-t border-gray-100 pt-3 lg:mt-0 lg:border-t-0 lg:pt-0 flex flex-col lg:flex-row lg:items-center gap-2 sm:gap-3">
                @if(request('per_page'))
                    <input type="hidden" name="per_page" value="{{ request('per_page') }}">
                @endif
                <div class="flex flex-wrap gap-2 lg:flex-nowrap lg:shrink-0">
                    <button type="submit" class="inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium bg-primary text-white hover:bg-blue-600 transition-colors whitespace-nowrap">
                        <span class="material-symbols-outlined text-[18px]">filter_alt</span>
                        Apply filters
                    </button>
                    <a href="{{ route('admin.quotations.index') }}" class="inline-flex items-center justify-center px-4 py-2.5 rounded-lg text-sm font-medium border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors whitespace-nowrap">Clear</a>
                </div>
                <div class="flex flex-wrap items-center gap-2 lg:ml-auto lg:flex-nowrap lg:min-w-0 lg:justify-end">
                    <div class="relative min-w-0 w-full sm:min-w-[160px] sm:w-auto sm:flex-initial lg:max-w-[220px]">
                        <label class="sr-only">Date preset</label>
                        <select id="quotation-date-preset" class="w-full appearance-none bg-white border border-gray-200 text-gray-700 py-2.5 pl-3 pr-9 rounded-lg text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary cursor-pointer">
                            <option value="">Quick: date range</option>
                            <option value="7">Last 7 days</option>
                            <option value="30">Last 30 days</option>
                            <option value="90">Last 90 days</option>
                        </select>
                        <span class="pointer-events-none absolute inset-y-0 right-2 flex items-center text-gray-500 material-symbols-outlined text-[20px]">calendar_today</span>
                    </div>
                    <a href="{{ route('admin.quotations.index', array_merge(request()->except('page'), ['export' => 'csv'])) }}" class="inline-flex items-center justify-center p-2.5 text-gray-500 hover:text-primary hover:bg-gray-50 rounded-lg border border-gray-200 transition-colors shrink-0" title="Export CSV">
                        <span class="material-symbols-outlined text-[20px]">download</span>
                    </a>
                    <button type="button" onclick="window.print()" class="inline-flex items-center justify-center p-2.5 text-gray-500 hover:text-primary hover:bg-gray-50 rounded-lg border border-gray-200 transition-colors shrink-0" title="Print list">
                        <span class="material-symbols-outlined text-[20px]">print</span>
                    </button>
                </div>
            </div>
        </form>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden" id="quotations-print-area">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[720px]">
                <thead>
                    <tr class="bg-gray-50/50 border-b border-gray-200">
                        <th class="py-4 px-4 sm:px-6 w-12 no-print-quotations">
                            <input class="rounded border-gray-300 text-primary focus:ring-primary" type="checkbox" disabled aria-disabled="true"/>
                        </th>
                        <th class="py-4 px-4 sm:px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Quotation #</th>
                        <th class="py-4 px-4 sm:px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Customer</th>
                        <th class="py-4 px-4 sm:px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Date</th>
                        <th class="py-4 px-4 sm:px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">Expiry</th>
                        <th class="py-4 px-4 sm:px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right">Amount</th>
                        <th class="py-4 px-4 sm:px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-center">Status</th>
                        <th class="py-4 px-4 sm:px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse($quotations as $quotation)
                        <tr class="group hover:bg-gray-50/50 transition-colors">
                            <td class="py-4 px-4 sm:px-6 no-print-quotations">
                                <input class="rounded border-gray-300 text-primary focus:ring-primary" type="checkbox" disabled aria-disabled="true"/>
                            </td>
                            <td class="py-4 px-4 sm:px-6">
                                <a href="{{ route('admin.quotations.show', $quotation) }}" class="text-sm font-semibold text-primary hover:underline hover:text-blue-600">
                                    {{ $quotation->quotation_number }}
                                </a>
                            </td>
                            <td class="py-4 px-4 sm:px-6">
                                <div class="flex items-center gap-3 min-w-0">
                                    <div class="size-8 rounded-full bg-gray-100 flex items-center justify-center text-xs font-bold text-gray-600 shrink-0">
                                        {{ strtoupper(substr($quotation->customer->name ?? '?', 0, 2)) }}
                                    </div>
                                    <div class="flex flex-col min-w-0">
                                        <span class="text-sm font-medium text-gray-900 truncate">{{ $quotation->customer->name ?? 'N/A' }}</span>
                                        <span class="text-xs text-gray-500 truncate">{{ $quotation->customer->email ?? 'N/A' }}</span>
                                    </div>
                                </div>
                            </td>
                            <td class="py-4 px-4 sm:px-6 text-sm text-gray-600 whitespace-nowrap">{{ $quotation->issue_date->format('M d, Y') }}</td>
                            <td class="py-4 px-4 sm:px-6 text-sm text-gray-600 whitespace-nowrap">{{ $quotation->expiry_date ? $quotation->expiry_date->format('M d, Y') : 'N/A' }}</td>
                            <td class="py-4 px-4 sm:px-6 text-sm font-medium text-gray-900 text-right font-mono whitespace-nowrap">{{ $quotation->currency }} {{ number_format($quotation->total, 2) }}</td>
                            <td class="py-4 px-4 sm:px-6 text-center">
                                @php
                                    $statusColors = [
                                        'draft' => ['bg' => 'bg-orange-100', 'text' => 'text-orange-800', 'label' => 'Pending'],
                                        'sent' => ['bg' => 'bg-blue-100', 'text' => 'text-blue-800', 'label' => 'Sent'],
                                        'viewed' => ['bg' => 'bg-purple-100', 'text' => 'text-purple-800', 'label' => 'Viewed'],
                                        'accepted' => ['bg' => 'bg-green-100', 'text' => 'text-green-800', 'label' => 'Approved'],
                                        'rejected' => ['bg' => 'bg-red-100', 'text' => 'text-red-800', 'label' => 'Rejected'],
                                        'expired' => ['bg' => 'bg-gray-100', 'text' => 'text-gray-800', 'label' => 'Expired'],
                                        'converted' => ['bg' => 'bg-indigo-100', 'text' => 'text-indigo-800', 'label' => 'Converted'],
                                    ];
                                    $config = $statusColors[$quotation->status] ?? $statusColors['draft'];
                                @endphp
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {{ $config['bg'] }} {{ $config['text'] }}">
                                    {{ $config['label'] }}
                                </span>
                            </td>
                            <td class="py-4 px-4 sm:px-6 text-right">
                                <div class="relative inline-block text-left">
                                    <button type="button"
                                        data-admin-fixed-menu-trigger="quotation-action-menu-{{ $quotation->id }}"
                                        onclick="adminFixedActionMenuToggle(event || window.event, 'quotation-action-menu-{{ $quotation->id }}')"
                                        class="inline-flex items-center justify-center rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600"
                                        title="More actions">
                                        <span class="material-symbols-outlined text-[20px]">more_vert</span>
                                    </button>
                                    <div id="quotation-action-menu-{{ $quotation->id }}" data-admin-fixed-action-menu class="hidden w-48 overflow-hidden rounded-lg border border-gray-200 bg-white shadow-lg">
                                        <div class="py-1">
                                            <a href="{{ route('admin.quotations.show', $quotation) }}" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 transition-colors hover:bg-gray-50">
                                                <span class="material-symbols-outlined text-[18px]">visibility</span>
                                                <span>View</span>
                                            </a>
                                            <a href="{{ route('admin.quotations.edit', $quotation) }}" class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 transition-colors hover:bg-gray-50">
                                                <span class="material-symbols-outlined text-[18px]">edit</span>
                                                <span>Edit</span>
                                            </a>
                                            <button type="button" onclick="openQuotationSendModal({{ $quotation->id }}); closeAllQuotationActionMenus();" class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-gray-700 transition-colors hover:bg-gray-50">
                                                <span class="material-symbols-outlined text-[18px]">send</span>
                                                <span>Send</span>
                                            </button>
                                            <button type="button"
                                                class="js-quotation-delete flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-red-600 transition-colors hover:bg-red-50"
                                                data-quotation-id="{{ $quotation->id }}"
                                                data-quotation-number="{{ e($quotation->quotation_number) }}">
                                                <span class="material-symbols-outlined text-[18px]">delete</span>
                                                <span>Delete</span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="8" class="py-12 px-6 text-center text-gray-500">
                                <span class="material-symbols-outlined text-4xl mb-2 block">request_quote</span>
                                <p>No quotations found</p>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($quotations->hasPages())
            <div class="no-print-quotations px-4 sm:px-6 py-4 border-t border-gray-200 flex flex-col sm:flex-row items-center justify-between gap-4">
                <p class="text-sm text-gray-500 text-center sm:text-left">
                    Showing <span class="font-medium text-gray-900">{{ $quotations->firstItem() }}</span> to <span class="font-medium text-gray-900">{{ $quotations->lastItem() }}</span> of <span class="font-medium text-gray-900">{{ $quotations->total() }}</span> results
                </p>
                <div class="flex items-center gap-1 flex-wrap justify-center">
                    @if($quotations->onFirstPage())
                        <button disabled class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">Previous</button>
                    @else
                        <a href="{{ $quotations->previousPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">Previous</a>
                    @endif
                    @foreach($quotations->getUrlRange(1, min(3, $quotations->lastPage())) as $page => $url)
                        <a href="{{ $url }}" class="size-8 text-sm font-medium rounded {{ $quotations->currentPage() == $page ? 'bg-primary text-white' : 'text-gray-600 hover:bg-gray-50' }} flex items-center justify-center">{{ $page }}</a>
                    @endforeach
                    @if($quotations->hasMorePages())
                        <span class="px-2 text-gray-400">...</span>
                        <a href="{{ $quotations->url($quotations->lastPage()) }}" class="size-8 text-sm font-medium rounded text-gray-600 hover:bg-gray-50 flex items-center justify-center">{{ $quotations->lastPage() }}</a>
                        <a href="{{ $quotations->nextPageUrl() }}" class="px-3 py-1 text-sm text-gray-500 rounded hover:bg-gray-50">Next</a>
                    @endif
                </div>
            </div>
        @endif
    </div>
</div>

{{-- Delete confirmation --}}
<div id="q-delete-modal" data-admin-modal class="hidden fixed inset-0 z-[80] overflow-y-auto" role="dialog" aria-modal="true" aria-labelledby="q-delete-title">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeQuotationDeleteModal()" aria-hidden="true"></div>
        <div class="relative z-10 w-full max-w-md rounded-xl bg-white p-5 shadow-xl sm:p-6">
            <div class="flex items-start justify-between gap-3 mb-4">
                <div class="flex items-start gap-4 min-w-0">
                    <div class="h-12 w-12 shrink-0 rounded-full bg-red-100 flex items-center justify-center">
                        <span class="material-symbols-outlined text-red-600">warning</span>
                    </div>
                    <div class="min-w-0">
                        <h3 id="q-delete-title" class="text-lg font-bold text-gray-900">Delete quotation</h3>
                        <p class="text-sm text-gray-600">This action cannot be undone.</p>
                    </div>
                </div>
                <button type="button" onclick="closeQuotationDeleteModal()" class="shrink-0 rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600" aria-label="Close">
                    <span class="material-symbols-outlined text-[22px]">close</span>
                </button>
            </div>
            <p class="text-sm text-gray-700 mb-6">
                Are you sure you want to delete <span id="q-delete-number" class="font-semibold"></span>?
            </p>
            <form id="q-delete-form" method="POST" class="flex flex-col-reverse sm:flex-row items-stretch sm:items-center justify-end gap-3">
                @csrf
                @method('DELETE')
                <button type="button" onclick="closeQuotationDeleteModal()" class="px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">Cancel</button>
                <button type="submit" class="px-4 py-2.5 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700">Delete</button>
            </form>
        </div>
    </div>
</div>

{{-- Send options --}}
<div id="q-send-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeQuotationSendModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-5 sm:p-6 max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between mb-4 sm:mb-6">
                <h3 class="text-lg sm:text-xl font-bold text-gray-900">Send quotation</h3>
                <button type="button" onclick="closeQuotationSendModal()" class="text-gray-400 hover:text-gray-600 p-1 rounded-lg hover:bg-gray-100">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <div class="space-y-2 sm:space-y-3">
                <button type="button" onclick="quotationSendEmail(); return false;" class="w-full flex items-start gap-3 px-4 py-3 text-left bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span class="material-symbols-outlined text-primary shrink-0">email</span>
                    <div class="min-w-0">
                        <div class="font-medium text-gray-900">Email</div>
                        <div class="text-xs text-gray-500">Send to an email address</div>
                    </div>
                </button>
                <button type="button" onclick="openQuotationWaLinkModal(); return false;" class="w-full flex items-start gap-3 px-4 py-3 text-left bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span class="material-symbols-outlined text-green-600 shrink-0">link</span>
                    <div class="min-w-0">
                        <div class="font-medium text-gray-900">Send link via WhatsApp</div>
                        <div class="text-xs text-gray-500">Opens WhatsApp with the public view link</div>
                    </div>
                </button>
                <button type="button" onclick="openQuotationWaPdfModal(); return false;" class="w-full flex items-start gap-3 px-4 py-3 text-left bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span class="material-symbols-outlined text-green-600 shrink-0">chat</span>
                    <div class="min-w-0">
                        <div class="font-medium text-gray-900">Send PDF via WhatsApp</div>
                        <div class="text-xs text-gray-500">WhatsApp Business API with PDF attachment</div>
                    </div>
                </button>
                <a id="q-send-download-link" href="#" class="w-full flex items-start gap-3 px-4 py-3 text-left bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span class="material-symbols-outlined text-primary shrink-0">picture_as_pdf</span>
                    <div class="min-w-0">
                        <div class="font-medium text-gray-900">Download PDF</div>
                        <div class="text-xs text-gray-500">Save quotation as PDF</div>
                    </div>
                </a>
                <button type="button" onclick="quotationPrint(); return false;" class="w-full flex items-start gap-3 px-4 py-3 text-left bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span class="material-symbols-outlined text-gray-600 shrink-0">print</span>
                    <div class="min-w-0">
                        <div class="font-medium text-gray-900">Print</div>
                        <div class="text-xs text-gray-500">Opens a print-friendly page</div>
                    </div>
                </button>
                <button type="button" onclick="quotationCopyLink(event); return false;" class="w-full flex items-start gap-3 px-4 py-3 text-left bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors">
                    <span class="material-symbols-outlined text-primary shrink-0">content_copy</span>
                    <div class="min-w-0">
                        <div class="font-medium text-gray-900">Copy public link</div>
                        <div class="text-xs text-gray-500">Copy shareable link to clipboard</div>
                    </div>
                </button>
            </div>
        </div>
    </div>
</div>

{{-- Email --}}
<div id="q-email-modal" data-admin-modal class="hidden fixed inset-0 z-[60] overflow-y-auto">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeQuotationEmailModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-5 sm:p-6 max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-900">Send via email</h3>
                <button type="button" onclick="closeQuotationEmailModal()" class="text-gray-400 hover:text-gray-600"><span class="material-symbols-outlined">close</span></button>
            </div>
            <form id="q-email-form" class="space-y-4">
                @csrf
                <input type="hidden" id="q-email-quotation-id" name="quotation_id">
                <div class="bg-gray-50 rounded-lg p-4">
                    <div class="flex justify-between text-sm">
                        <span class="text-gray-600">Quotation</span>
                        <span id="q-email-quotation-number" class="font-semibold text-gray-900"></span>
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Recipient email</label>
                    <input type="email" id="q-email-input" name="email" required class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900" placeholder="customer@example.com">
                </div>
                <div class="flex flex-col-reverse sm:flex-row gap-3 pt-2 border-t border-gray-200">
                    <button type="button" onclick="closeQuotationEmailModal()" class="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">Cancel</button>
                    <button type="submit" class="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-primary rounded-lg hover:bg-blue-600">Send</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- WhatsApp PDF (API) --}}
<div id="q-whatsapp-modal" data-admin-modal class="hidden fixed inset-0 z-[60] overflow-y-auto">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeQuotationWhatsAppModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-5 sm:p-6 max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-900">WhatsApp PDF (Business API)</h3>
                <button type="button" onclick="closeQuotationWhatsAppModal()" class="text-gray-400 hover:text-gray-600"><span class="material-symbols-outlined">close</span></button>
            </div>
            <form id="q-whatsapp-form" class="space-y-4">
                @csrf
                <input type="hidden" id="q-whatsapp-quotation-id">
                <div class="bg-gray-50 rounded-lg p-4 text-sm">
                    <div class="flex justify-between"><span class="text-gray-600">Quotation</span><span id="q-whatsapp-quotation-number" class="font-semibold text-gray-900"></span></div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Phone (with country code)</label>
                    <input type="text" id="q-whatsapp-phone" name="phone" required class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900" placeholder="+2348012345678">
                    <p class="text-xs text-gray-500 mt-1">Uses your configured WhatsApp Business API. Customer phone is prefilled when available.</p>
                </div>
                <div class="flex flex-col-reverse sm:flex-row gap-3 pt-2 border-t border-gray-200">
                    <button type="button" onclick="closeQuotationWhatsAppModal()" class="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">Cancel</button>
                    <button type="submit" class="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700">Send PDF</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- WhatsApp link (wa.me) --}}
<div id="q-wa-link-modal" data-admin-modal class="hidden fixed inset-0 z-[60] overflow-y-auto">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeQuotationWaLinkModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-5 sm:p-6 max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-900">Send link via WhatsApp</h3>
                <button type="button" onclick="closeQuotationWaLinkModal()" class="text-gray-400 hover:text-gray-600"><span class="material-symbols-outlined">close</span></button>
            </div>
            <form id="q-wa-link-form" class="space-y-4">
                <input type="hidden" id="q-wa-link-quotation-id">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Customer WhatsApp number</label>
                    <input type="text" id="q-wa-link-phone" required class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900" placeholder="+2348012345678">
                    <p class="text-xs text-gray-500 mt-1">Opens WhatsApp Web or app with your public quotation link.</p>
                </div>
                <div class="flex flex-col-reverse sm:flex-row gap-3 pt-2 border-t border-gray-200">
                    <button type="button" onclick="closeQuotationWaLinkModal()" class="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">Cancel</button>
                    <button type="submit" class="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700">Open WhatsApp</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Result --}}
<div id="q-result-modal" data-admin-modal class="hidden fixed inset-0 z-[70] overflow-y-auto">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="closeQuotationResultModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-md w-full p-6">
            <div class="text-center">
                <div id="q-result-icon" class="mx-auto flex items-center justify-center h-16 w-16 rounded-full mb-4">
                    <span id="q-result-icon-symbol" class="material-symbols-outlined text-4xl"></span>
                </div>
                <h3 id="q-result-title" class="text-xl font-bold text-gray-900 mb-2"></h3>
                <p id="q-result-message" class="text-sm text-gray-600 mb-6"></p>
                <button type="button" onclick="closeQuotationResultModal()" id="q-result-btn" class="w-full px-4 py-2 text-sm font-medium text-white rounded-lg transition-colors">OK</button>
            </div>
        </div>
    </div>
</div>

<script>
let currentQuotationId = null;

function closeAllQuotationActionMenus() {
    if (typeof window.adminFixedActionMenuCloseAll === 'function') {
        window.adminFixedActionMenuCloseAll();
    } else {
        document.querySelectorAll('[id^="quotation-action-menu-"]').forEach(function (menu) {
            menu.classList.add('hidden');
        });
    }
}

function openQuotationDeleteModal(quotationId, quotationNumber) {
    const deleteForm = document.getElementById('q-delete-form');
    const deleteNumber = document.getElementById('q-delete-number');
    const modal = document.getElementById('q-delete-modal');
    if (!modal || !deleteForm) {
        return;
    }
    deleteForm.action = `/admin/quotations/${quotationId}`;
    if (deleteNumber) {
        deleteNumber.textContent = quotationNumber || '';
    }
    modal.classList.remove('hidden');
}

function closeQuotationDeleteModal() {
    document.getElementById('q-delete-modal')?.classList.add('hidden');
}

document.querySelectorAll('.js-quotation-delete').forEach((btn) => {
    btn.addEventListener('click', () => {
        const id = btn.getAttribute('data-quotation-id');
        const num = btn.getAttribute('data-quotation-number') || '';
        if (id) {
            openQuotationDeleteModal(id, num);
            closeAllQuotationActionMenus();
        }
    });
});

function getAdminCsrfToken() {
    const meta = document.querySelector('meta[name="csrf-token"]');
    if (meta?.content) return meta.content;
    const input = document.querySelector('input[name="_token"]');
    return input?.value || '';
}

function adminJsonFetchInit(body) {
    return {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': getAdminCsrfToken(),
        },
        body: body !== undefined ? JSON.stringify(body) : undefined,
    };
}

function openQuotationSendModal(quotationId) {
    currentQuotationId = quotationId;
    const dl = document.getElementById('q-send-download-link');
    if (dl) dl.href = `/admin/quotations/${quotationId}/download`;
    document.getElementById('q-send-modal').classList.remove('hidden');
}

function closeQuotationSendModal() {
    document.getElementById('q-send-modal').classList.add('hidden');
}

async function fetchQuotationShareLink() {
    const res = await fetch(`/admin/quotations/${currentQuotationId}/share-link`, {
        method: 'GET',
        credentials: 'same-origin',
        headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': getAdminCsrfToken(),
        },
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok || !data.success || !data.link) {
        throw new Error(data.message || 'Could not create share link');
    }
    return data.link;
}

async function quotationCopyLink(ev) {
    const btn = ev?.target?.closest('button');
    if (!currentQuotationId) return;
    const orig = btn ? btn.innerHTML : '';
    if (btn) { btn.disabled = true; btn.innerHTML = '<span class="material-symbols-outlined animate-spin text-[18px]">sync</span>'; }
    try {
        const link = await fetchQuotationShareLink();
        try {
            await navigator.clipboard.writeText(link);
            showQuotationResult('success', 'Copied', 'Public link copied to clipboard.');
        } catch {
            const inp = document.createElement('input');
            inp.value = link;
            document.body.appendChild(inp);
            inp.select();
            document.execCommand('copy');
            document.body.removeChild(inp);
            showQuotationResult('success', 'Copied', 'Public link copied to clipboard.');
        }
        closeQuotationSendModal();
    } catch (e) {
        showQuotationResult('error', 'Error', e.message || 'Failed to copy link');
    } finally {
        if (btn) { btn.disabled = false; btn.innerHTML = orig; }
    }
}

function quotationPrint() {
    if (!currentQuotationId) return;
    window.open(`/admin/quotations/${currentQuotationId}/print`, '_blank', 'noopener,noreferrer');
    closeQuotationSendModal();
}

function quotationSendEmail() {
    const qid = currentQuotationId;
    if (!qid) return;
    closeQuotationSendModal();
    setTimeout(() => {
        currentQuotationId = qid;
        openQuotationEmailModal();
    }, 100);
}

function openQuotationEmailModal() {
    if (!currentQuotationId) return;
    document.getElementById('q-email-quotation-id').value = currentQuotationId;
    fetch(`/admin/quotations/${currentQuotationId}/data`, {
        credentials: 'same-origin',
        headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
    })
        .then(r => r.json())
        .then(data => {
            document.getElementById('q-email-quotation-number').textContent = data.quotation_number || '';
            document.getElementById('q-email-input').value = data.customer_email || '';
            document.getElementById('q-email-modal').classList.remove('hidden');
        })
        .catch(() => {
            document.getElementById('q-email-modal').classList.remove('hidden');
        });
}

function closeQuotationEmailModal() {
    document.getElementById('q-email-modal').classList.add('hidden');
}

function openQuotationWaPdfModal() {
    const qid = currentQuotationId;
    if (!qid) return;
    closeQuotationSendModal();
    setTimeout(() => {
        currentQuotationId = qid;
        document.getElementById('q-whatsapp-quotation-id').value = qid;
        fetch(`/admin/quotations/${qid}/data`, {
            credentials: 'same-origin',
            headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        })
            .then(r => r.json())
            .then(data => {
                document.getElementById('q-whatsapp-quotation-number').textContent = data.quotation_number || '';
                document.getElementById('q-whatsapp-phone').value = data.customer_phone || '';
                document.getElementById('q-whatsapp-modal').classList.remove('hidden');
            })
            .catch(() => {
                document.getElementById('q-whatsapp-modal').classList.remove('hidden');
            });
    }, 100);
}

function closeQuotationWhatsAppModal() {
    document.getElementById('q-whatsapp-modal').classList.add('hidden');
}

function openQuotationWaLinkModal() {
    const qid = currentQuotationId;
    if (!qid) return;
    closeQuotationSendModal();
    setTimeout(() => {
        currentQuotationId = qid;
        document.getElementById('q-wa-link-quotation-id').value = qid;
        fetch(`/admin/quotations/${qid}/data`, {
            credentials: 'same-origin',
            headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
        })
            .then(r => r.json())
            .then(data => {
                document.getElementById('q-wa-link-phone').value = data.customer_phone || '';
                document.getElementById('q-wa-link-modal').classList.remove('hidden');
            })
            .catch(() => {
                document.getElementById('q-wa-link-modal').classList.remove('hidden');
            });
    }, 100);
}

function closeQuotationWaLinkModal() {
    document.getElementById('q-wa-link-modal').classList.add('hidden');
}

function showQuotationResult(type, title, message) {
    const modal = document.getElementById('q-result-modal');
    const icon = document.getElementById('q-result-icon');
    const sym = document.getElementById('q-result-icon-symbol');
    const btn = document.getElementById('q-result-btn');
    document.getElementById('q-result-title').textContent = title;
    document.getElementById('q-result-message').textContent = message;
    if (type === 'success') {
        icon.className = 'mx-auto flex items-center justify-center h-16 w-16 rounded-full mb-4 bg-green-100';
        sym.textContent = 'check_circle';
        sym.className = 'material-symbols-outlined text-4xl text-green-600';
        btn.className = 'w-full px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700 transition-colors';
    } else {
        icon.className = 'mx-auto flex items-center justify-center h-16 w-16 rounded-full mb-4 bg-red-100';
        sym.textContent = 'error';
        sym.className = 'material-symbols-outlined text-4xl text-red-600';
        btn.className = 'w-full px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors';
    }
    modal.classList.remove('hidden');
}

function closeQuotationResultModal() {
    document.getElementById('q-result-modal').classList.add('hidden');
}

document.getElementById('quotation-date-preset')?.addEventListener('change', function () {
    const days = this.value;
    const form = document.getElementById('quotation-filters-form');
    if (!form || !days) return;
    const end = new Date();
    const start = new Date();
    start.setDate(end.getDate() - parseInt(days, 10) + 1);
    const fmt = d => d.toISOString().slice(0, 10);
    form.querySelector('[name="date_from"]').value = fmt(start);
    form.querySelector('[name="date_to"]').value = fmt(end);
    form.submit();
});

document.getElementById('q-email-form')?.addEventListener('submit', async function (e) {
    e.preventDefault();
    const id = document.getElementById('q-email-quotation-id').value;
    const email = document.getElementById('q-email-input').value.trim();
    const submit = this.querySelector('button[type="submit"]');
    const orig = submit.innerHTML;
    submit.disabled = true;
    submit.innerHTML = '<span class="material-symbols-outlined animate-spin">sync</span>';
    try {
        const res = await fetch(`/admin/quotations/${id}/send-email`, adminJsonFetchInit({ email }));
        const data = await res.json().catch(() => ({}));
        if (res.status === 419) {
            showQuotationResult('error', 'Session expired', 'Refresh the page and try again.');
            return;
        }
        if (data.success) {
            closeQuotationEmailModal();
            showQuotationResult('success', 'Sent', data.message || 'Email queued successfully.');
        } else {
            showQuotationResult('error', 'Failed', data.message || 'Could not send email.');
        }
    } catch {
        showQuotationResult('error', 'Error', 'Network error. Try again.');
    } finally {
        submit.disabled = false;
        submit.innerHTML = orig;
    }
});

document.getElementById('q-whatsapp-form')?.addEventListener('submit', async function (e) {
    e.preventDefault();
    const id = document.getElementById('q-whatsapp-quotation-id').value;
    const phone = document.getElementById('q-whatsapp-phone').value.trim();
    const submit = this.querySelector('button[type="submit"]');
    const orig = submit.innerHTML;
    if (!phone) {
        showQuotationResult('error', 'Phone required', 'Enter a phone number with country code.');
        return;
    }
    submit.disabled = true;
    submit.innerHTML = '<span class="material-symbols-outlined animate-spin">sync</span>';
    try {
        const res = await fetch(`/admin/quotations/${id}/send-whatsapp`, adminJsonFetchInit({ phone }));
        const data = await res.json().catch(() => ({}));
        if (res.status === 419) {
            showQuotationResult('error', 'Session expired', 'Refresh the page and try again.');
            return;
        }
        if (data.success) {
            closeQuotationWhatsAppModal();
            showQuotationResult('success', 'Sent', data.message || 'WhatsApp message sent.');
        } else {
            showQuotationResult('error', 'Failed', data.message || 'WhatsApp send failed.');
        }
    } catch {
        showQuotationResult('error', 'Error', 'Network error. Try again.');
    } finally {
        submit.disabled = false;
        submit.innerHTML = orig;
    }
});

document.getElementById('q-wa-link-form')?.addEventListener('submit', async function (e) {
    e.preventDefault();
    const raw = document.getElementById('q-wa-link-phone').value.trim();
    const digits = raw.replace(/\D/g, '');
    if (!digits) {
        showQuotationResult('error', 'Invalid number', 'Enter a phone number with country code.');
        return;
    }
    const submit = this.querySelector('button[type="submit"]');
    const orig = submit.innerHTML;
    submit.disabled = true;
    submit.innerHTML = '<span class="material-symbols-outlined animate-spin">sync</span>';
    try {
        const link = await fetchQuotationShareLink();
        const msg = `Hello,\n\nPlease view your quotation here:\n${link}\n\nThank you.`;
        const url = `https://wa.me/${digits}?text=${encodeURIComponent(msg)}`;
        window.open(url, '_blank', 'noopener,noreferrer');
        closeQuotationWaLinkModal();
        showQuotationResult('success', 'WhatsApp', 'If a new tab did not open, allow pop-ups for this site.');
    } catch (err) {
        showQuotationResult('error', 'Error', err.message || 'Could not open WhatsApp.');
    } finally {
        submit.disabled = false;
        submit.innerHTML = orig;
    }
});
</script>
@endsection
