@extends('layouts.app')

@push('styles')
<style>
    .invoice-card {
        border: 1px solid #e2e8f0;
        border-radius: 1rem;
        overflow: hidden;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    }
    .invoice-card:hover {
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    }
    .invoice-header {
        background: linear-gradient(135deg, #1e40af 0%, #1e3a8a 100%);
        color: white;
        padding: 2rem 2rem;
        position: relative;
        overflow: hidden;
    }
    .invoice-header::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 200px;
        height: 200px;
        background: radial-gradient(circle, rgba(250, 204, 21, 0.1) 0%, transparent 70%);
        border-radius: 50%;
        transform: translate(50%, -50%);
    }
    .invoice-header::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 150px;
        height: 150px;
        background: radial-gradient(circle, rgba(250, 204, 21, 0.08) 0%, transparent 70%);
        border-radius: 50%;
        transform: translate(-30%, 30%);
    }
    .status-badge {
        padding: 0.35rem 0.75rem;
        border-radius: 9999px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: capitalize;
        display: inline-flex;
        align-items: center;
        gap: 0.25rem;
    }
    .status-paid {
        background-color: #d1fae5;
        color: #065f46;
    }
    .status-unpaid {
        background-color: #fee2e2;
        color: #b91c1c;
    }
    .status-overdue {
        background-color: #fef3c7;
        color: #92400e;
    }
    .status-partial {
        background-color: #dbeafe;
        color: #1e40af;
    }
    .action-btn {
        width: 32px;
        height: 32px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
    }
    .amount-cell {
        font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
        font-weight: 700;
        letter-spacing: -0.025em;
        color: #1e40af;
        font-size: 0.95rem;
    }
    .empty-state {
        padding: 4rem 2rem;
        text-align: center;
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        border-radius: 1rem;
        margin: 2rem 0;
        border: 2px dashed #cbd5e1;
    }
    .empty-state i {
        font-size: 3rem;
        color: #94a3b8;
        margin-bottom: 1.5rem;
    }
    .table-header {
        background: linear-gradient(135deg, #1e40af 0%, #1e3a8a 100%);
        position: relative;
        overflow: hidden;
    }
    .table-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 2px;
        background: linear-gradient(90deg, #fbbf24 0%, #f59e0b 50%, #fbbf24 100%);
    }
    .table-header::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 1px;
        background: rgba(251, 191, 36, 0.3);
    }
    .table-header th {
        color: white;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        position: relative;
        z-index: 1;
    }
    .table-header th:hover {
        background: rgba(255, 255, 255, 0.1);
    }
    .table-row:hover {
        background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    }
    .table-data {
        font-size: 0.75rem;
    }
    .table-data-small {
        font-size: 0.65rem;
    }
    .filter-select {
        background: white;
        border: 2px solid #e2e8f0;
    }
    .filter-select:focus {
        border-color: #1e40af;
        box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.1);
    }
    .btn-primary {
        background: linear-gradient(135deg, #1e40af 0%, #1e3a8a 100%);
        border: none;
    }
    .btn-primary:hover {
        background: linear-gradient(135deg, #1e3a8a 0%, #1e2f5f 100%);
        box-shadow: 0 4px 12px rgba(30, 64, 175, 0.3);
    }
    .btn-success {
        background: linear-gradient(135deg, #16a34a 0%, #15803d 100%);
        border: none;
    }
    .btn-success:hover {
        background: linear-gradient(135deg, #15803d 0%, #166534 100%);
        box-shadow: 0 4px 12px rgba(22, 163, 74, 0.3);
    }
    .invoice-number {
        background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
        padding: 0.25rem 0.5rem;
        border-radius: 0.375rem;
        border-left: 3px solid #1e40af;
    }
    .customer-info {
        position: relative;
    }
    .customer-info::before {
        content: '';
        position: absolute;
        left: -8px;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 70%;
        background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
        border-radius: 2px;
    }
    .property-cell {
        background: linear-gradient(135deg, #fef3c7 0%, #fde68a 20%, transparent 20%);
        padding: 0.25rem 0.5rem;
        border-radius: 0.375rem;
    }
    .amount-display {
        background: linear-gradient(135deg, #f0f9ff 0%, #dbeafe 100%);
        padding: 0.5rem 0.75rem;
        border-radius: 0.5rem;
        border: 1px solid #bfdbfe;
        position: relative;
        overflow: hidden;
    }
    .amount-display::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 20px;
        height: 20px;
        background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
        transform: translate(25%, -25%) rotate(45deg);
    }
    .due-date-cell {
        position: relative;
    }
    .due-date-cell::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 2px;
        background: linear-gradient(90deg, #fb923c 0%, #f97316 50%, transparent 100%);
    }
    .dropdown-menu {
        opacity: 0;
        pointer-events: none;
    }
    .dropdown-menu.show {
        opacity: 1;
        pointer-events: auto;
    }
    .dropdown-item {
        position: relative;
        overflow: hidden;
    }
    .dropdown-container {
        position: relative;
        min-width: 40px;
    }
    .dropdown-menu {
        min-width: 200px;
        max-width: 250px;
        z-index: 9999;
    }
    .table-actions {
        position: relative;
        padding-right: 1rem;
    }
    .table-actions td {
        position: relative;
        overflow: visible;
    }
    .table-row {
        position: relative;
        z-index: 1;
    }
    .table-row:hover {
        z-index: 2;
    }
    .dropdown-item-form {
        margin: 0;
        padding: 0;
        border: none;
        background: none;
    }
    .dropdown-item-form button {
        background: none;
        border: none;
        padding: 0;
        margin: 0;
        width: 100%;
        text-align: left;
        font: inherit;
        cursor: pointer;
        outline: none;
    }
</style>
@endpush

@section('content')
<div class="container mx-auto px-4 py-6">
    <div class="invoice-card bg-white rounded-lg">
        <div class="invoice-header flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div class="flex-1 relative z-10">
                <h2 class="text-2xl font-bold text-white mb-1">Rent & Billing Invoices</h2>
                <p class="text-blue-100 text-sm flex items-center">
                    <i class="fas fa-file-invoice mr-2 text-yellow-400"></i>
                    Manage all rent invoices in one place
                </p>
            </div>
            @if(isset($billingPeriod) && $invoices->isNotEmpty())
                <div class="flex items-center space-x-2">
                    <button type="button" 
                            onclick="openSendAllModal()"
                            class="btn-success inline-flex items-center px-4 py-2 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition ease-in-out duration-150 relative z-10">
                        <i class="fas fa-paper-plane mr-2"></i> Send All Invoices
                    </button>
                </div>

                <!-- Send All Invoices Modal -->
                <div id="sendAllModal" class="modal fade" tabindex="-1" aria-labelledby="sendAllModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-lg modal-dialog-centered">
                        <div class="modal-content">
                            <!-- Modal Header -->
                            <div class="modal-header bg-primary text-white">
                                <div class="d-flex align-items-center">
                                    <div class="bg-white bg-opacity-20 rounded p-2 me-3">
                                        <i class="fas fa-paper-plane"></i>
                                    </div>
                                    <div>
                                        <h5 class="modal-title mb-1" id="sendAllModalLabel">Send All Invoices</h5>
                                        <small class="text-white-50">Customize your bulk email message</small>
                                    </div>
                                </div>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close" onclick="closeSendAllModal()"></button>
                            </div>
                            
                            <!-- Modal Body -->
                            <div class="modal-body">
                                <form id="sendAllForm" action="{{ route('invoices.rent.send-all') }}" method="POST">
                                    @csrf
                                    <input type="hidden" name="billing_period" value="{{ $billingPeriod }}">
                                    <input type="hidden" name="include_pdf" value="1">
                                    
                                    <!-- Billing Period Info -->
                                    <div class="alert alert-info d-flex align-items-center mb-4">
                                        <i class="fas fa-calendar-alt me-2"></i>
                                        <div>
                                            <strong>Billing Period:</strong> <span class="fw-bold">{{ $billingPeriod }}</span>
                                        </div>
                                    </div>
                                    
                                    <!-- Email Subject Template -->
                                    <div class="mb-4">
                                        <label for="subject" class="form-label d-flex align-items-center">
                                            <i class="fas fa-heading text-primary me-2"></i>
                                            Email Subject
                                            <span id="subjectIndicator" class="badge bg-success ms-2 d-none">Custom</span>
                                        </label>
                                        <div class="input-group">
                                            <input type="text" 
                                                   class="form-control" 
                                                   name="subject" 
                                                   id="subject"
                                                   value=""
                                                   placeholder="Leave empty to use company default template">
                                            <span class="input-group-text">
                                                <i id="subjectIcon" class="fas fa-envelope text-muted"></i>
                                            </span>
                                        </div>
                                    </div>
                                    
                                    <!-- Email Message Template -->
                                    <div class="mb-4">
                                        <label for="message" class="form-label d-flex align-items-center">
                                            <i class="fas fa-envelope text-primary me-2"></i>
                                            Email Message
                                            <span id="messageIndicator" class="badge bg-success ms-2 d-none">Custom</span>
                                        </label>
                                        <div class="form-floating">
                                            <textarea name="message" 
                                                      class="form-control" 
                                                      id="message" 
                                                      rows="5"
                                                      placeholder="Leave empty to use company default template"
                                                      style="height: 120px;"></textarea>
                                            <label for="message" class="text-muted">
                                                <small>Leave empty to use company default template</small>
                                            </label>
                                            <div class="form-text text-end">
                                                <small><span id="charCount">0</span> characters</small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Template Info -->
                                    <div class="card bg-light mb-4">
                                        <div class="card-body py-3">
                                            <div class="d-flex align-items-start">
                                                <i class="fas fa-info-circle text-info me-2 mt-1"></i>
                                                <div>
                                                    <h6 class="card-title mb-2 small">Available Variables:</h6>
                                                    <div class="d-flex flex-wrap gap-1">
                                                        <code class="badge bg-secondary">{customer_name}</code>
                                                        <code class="badge bg-secondary">{bill_id}</code>
                                                        <code class="badge bg-secondary">{billing_period}</code>
                                                        <code class="badge bg-secondary">{account_number}</code>
                                                        <code class="badge bg-secondary">{total_amount}</code>
                                                        <code class="badge bg-secondary">{company_name}</code>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                            
                            <!-- Modal Footer -->
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="closeSendAllModal()">
                                    <i class="fas fa-times me-2"></i>Cancel
                                </button>
                                <button type="button" onclick="handleSendAllSubmit(event)" class="btn btn-success">
                                    <i class="fas fa-paper-plane me-2"></i>Send All Invoices
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            @endif

            <!-- Loading Dialog -->
            <div id="loadingDialog" class="fixed inset-0 bg-black bg-opacity-50 overflow-y-auto h-full w-full hidden z-50 backdrop-blur-sm">
                <div class="relative top-20 mx-auto p-0 border-0 rounded-2xl shadow-2xl bg-white max-w-md w-full mx-4 transform transition-all animate-pulse">
                    <!-- Modal Header with Gradient -->
                    <div class="bg-gradient-to-r from-blue-600 to-blue-700 rounded-t-2xl px-6 py-5 border-b border-blue-800">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 bg-white bg-opacity-20 rounded-full p-3 mr-4 animate-bounce">
                                    <i class="fas fa-paper-plane text-white text-xl"></i>
                                </div>
                                <div>
                                    <h3 class="text-xl font-bold text-white mb-1">Sending Email</h3>
                                    <p class="text-blue-100 text-sm">Processing your request...</p>
                                </div>
                            </div>
                            <div class="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
                        </div>
                    </div>
                    
                    <!-- Modal Body -->
                    <div class="px-6 py-8 bg-gradient-to-b from-white to-gray-50">
                        <div class="flex flex-col items-center space-y-4">
                            <!-- Main Spinner -->
                            <div class="relative">
                                <div class="w-16 h-16 border-4 border-blue-200 rounded-full animate-spin"></div>
                                <div class="absolute top-0 left-0 w-16 h-16 border-4 border-blue-600 rounded-full animate-spin border-t-transparent"></div>
                                <div class="absolute top-2 left-2 w-12 h-12 border-4 border-blue-300 rounded-full animate-spin border-b-transparent"></div>
                            </div>
                            
                            <!-- Status Text -->
                            <div class="text-center space-y-2">
                                <p class="text-gray-800 font-semibold text-lg">Sending Bill to Customer</p>
                                <p class="text-gray-600 text-sm">Please wait while we generate and send your invoice</p>
                                <div class="flex items-center justify-center space-x-2 mt-3">
                                    <div class="w-2 h-2 bg-blue-600 rounded-full animate-pulse"></div>
                                    <div class="w-2 h-2 bg-blue-600 rounded-full animate-pulse" style="animation-delay: 0.2s"></div>
                                    <div class="w-2 h-2 bg-blue-600 rounded-full animate-pulse" style="animation-delay: 0.4s"></div>
                                </div>
                            </div>
                            
                            <!-- Progress Bar -->
                            <div class="w-full bg-gray-200 rounded-full h-2 overflow-hidden">
                                <div class="bg-gradient-to-r from-blue-500 to-blue-600 h-2 rounded-full animate-pulse" style="width: 60%; animation: shimmer 2s infinite;"></div>
                            </div>
                            
                            <!-- Additional Info -->
                            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 w-full">
                                <div class="flex items-center space-x-3">
                                    <i class="fas fa-info-circle text-blue-600"></i>
                                    <div class="text-sm">
                                        <p class="text-blue-800 font-medium">This may take a few moments</p>
                                        <p class="text-blue-600 text-xs">Generating PDF and sending email...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Modal Footer -->
                    <div class="px-6 py-4 bg-gray-100 rounded-b-2xl border-t border-gray-200">
                        <div class="flex items-center justify-between">
                            <p class="text-xs text-gray-500">
                                <i class="fas fa-lock mr-1"></i>
                                Secure transaction in progress
                            </p>
                            <div class="flex items-center space-x-1">
                                <div class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                                <span class="text-xs text-green-600 font-medium">Active</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Custom CSS for animations -->
            <style>
                @keyframes shimmer {
                    0% { transform: translateX(-100%); }
                    100% { transform: translateX(200%); }
                }
                .animate-shimmer {
                    animation: shimmer 2s infinite;
                }
            </style>
            
            <div class="flex flex-wrap gap-3 w-full sm:w-auto relative z-10">
                <form method="GET" action="{{ route('invoices.rent.index') }}" class="flex items-center space-x-3">
                    <div class="relative w-48">
                        <select name="billing_period" id="billing-period" onchange="this.form.submit()" class="filter-select w-full block appearance-none text-gray-700 py-2 pl-3 pr-8 rounded-md leading-tight focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">All Billing Periods</option>
                            
                            @if(count($billingPeriods) > 0)
                                <option disabled>──────────</option>
                                @foreach($billingPeriods as $period)
                                    <option value="{{ $period }}" {{ $billingPeriod == $period ? 'selected' : '' }}>
                                        {{ \Carbon\Carbon::parse($period)->format('F Y') }}
                                    </option>
                                @endforeach
                            @endif
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-blue-500">
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                    </div>

                    <div class="relative w-48">
                        <select name="property" id="property-filter" onchange="this.form.submit()" class="filter-select w-full block appearance-none text-gray-700 py-2 pl-3 pr-8 rounded-md leading-tight focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">All Properties</option>
                            
                            @if(count($properties) > 0)
                                <option disabled>──────────</option>
                                @foreach($properties as $propId => $propName)
                                    <option value="{{ $propId }}" {{ $selectedProperty == $propId ? 'selected' : '' }}>
                                        {{ $propName }}
                                    </option>
                                @endforeach
                            @endif
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-blue-500">
                            <i class="fas fa-building"></i>
                        </div>
                    </div>

                    @if(request('billing_period') || request('property'))
                        <a href="{{ route('invoices.rent.index') }}" class="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200">
                            <i class="fas fa-times mr-1 text-red-500"></i> Clear Filters
                        </a>
                    @endif
                </form>
              
            </div>
        </div>

        <div class="p-6">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 rounded-lg overflow-hidden shadow-sm">
                    <thead class="table-header">
                        <tr>
                            <th scope="col" class="px-6 py-4 text-left text-xs uppercase tracking-wider">#</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs uppercase tracking-wider">Invoice #</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs uppercase tracking-wider">Customer</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs uppercase tracking-wider">Property</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs uppercase tracking-wider">Amount</th>
                            <th scope="col" class="px-6 py-4 text-left text-xs uppercase tracking-wider">Due Date</th>
                            <th scope="col" class="px-6 py-4 text-right text-xs uppercase tracking-wider pr-8">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-100">
                        @forelse($invoices as $invoice)
                            <tr class="table-row hover:shadow-md transition-all duration-200">
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600 font-medium table-data">
                                    {{ $loop->iteration }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="invoice-number">
                                        <div class="text-sm font-bold text-gray-900 table-data">
                                            INV-{{ str_pad($invoice->BillID ?? '000', 6, '0', STR_PAD_LEFT) }}
                                        </div>
                                        <div class="text-xs text-gray-500 flex items-center mt-1 table-data-small">
                                            <i class="fas fa-calendar mr-1 text-blue-400"></i>
                                            {{ \Carbon\Carbon::parse($invoice->BillingDate)->format('M d, Y') }}
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="customer-info pl-4">
                                        <div class="text-sm font-semibold text-gray-900 table-data">
                                            {{ $invoice->customer->CustomerName ?? 'N/A' }}
                                        </div>
                                        <div class="text-xs text-gray-500 flex items-center mt-1 table-data-small">
                                            <i class="fas fa-door-open mr-1 text-yellow-500"></i>
                                            {{ $invoice->unit->UnitIdentity ?? 'N/A' }}
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="property-cell text-sm font-medium text-gray-900 flex items-center px-3 py-2 rounded table-data">
                                        <i class="fas fa-building mr-2 text-blue-500"></i>
                                        {{ $invoice->unit->property->PropName ?? 'N/A' }}
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap amount-cell">
                                    <div class="amount-display">
                                        <div class="flex items-center">
                                            <span class="text-yellow-600 mr-1 font-bold table-data">KES</span>
                                            <span class="text-blue-700 table-data">{{ number_format($invoice->TotalPayable, 2) }}</span>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                    <div class="due-date-cell">
                                        <div class="flex items-center">
                                            <i class="fas fa-clock mr-2 text-orange-500"></i>
                                            <span class="table-data">{{ $invoice->DueDate ? \Carbon\Carbon::parse($invoice->DueDate)->format('M d, Y') : 'N/A' }}</span>
                                        </div>
                                    </div>
                                </td>
                               
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium pr-8 table-actions">
                                    <div class="dropdown-container">
                                        <button type="button" 
                                                class="action-btn bg-gradient-to-r from-blue-600 to-blue-700 text-yellow-400 hover:from-blue-700 hover:to-blue-800 inline-flex items-center justify-center w-8 h-8 rounded-full shadow-md hover:shadow-lg transition-all duration-200 transform hover:scale-105 border border-blue-500"
                                                onclick="toggleDropdown('dropdown-{{ $invoice->BillID }}')"
                                                data-tooltip="Actions">
                                            <i class="fas fa-chevron-down text-sm"></i>
                                        </button>
                                        
                                        <div id="dropdown-{{ $invoice->BillID }}" class="dropdown-menu hidden absolute right-0 z-50 w-48 origin-top-right bg-white divide-y divide-gray-100 rounded-lg shadow-xl ring-1 ring-black ring-opacity-5 focus:outline-none border border-gray-200" style="right: 0; left: auto; min-width: 180px; top: 100%; margin-top: 0; z-index: 9999; position: absolute;">
                                            <div class="py-1">
                                                <a href="{{ route('invoices.rent.show', $invoice->BillID) }}" 
                                                   class="dropdown-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gradient-to-r hover:from-blue-50 hover:to-blue-100 hover:text-blue-700 transition-all duration-150">
                                                    <i class="fas fa-eye mr-3 h-4 w-4 text-blue-500"></i>
                                                    View Details
                                                </a>
                                                <!-- <a href="{{ route('invoices.rent.edit', $invoice->BillID) }}" 
                                                   class="dropdown-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gradient-to-r hover:from-yellow-50 hover:to-yellow-100 hover:text-yellow-700 transition-all duration-150">
                                                    <i class="fas fa-edit mr-3 h-4 w-4 text-yellow-500"></i>
                                                    Edit
                                                </a> -->
                                                <a href="{{ route('invoices.rent.print', $invoice->BillID) }}" 
                                                   class="dropdown-item flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gradient-to-r hover:from-green-50 hover:to-green-100 hover:text-green-700 transition-all duration-150"
                                                   target="_blank" rel="noopener noreferrer">
                                                    <i class="fas fa-download mr-3 h-4 w-4 text-green-500"></i>
                                                    Download Bill
                                                </a>
                                                <form action="{{ route('invoices.rent.send', $invoice->BillID) }}" method="POST" class="dropdown-item-form">
                                                    @csrf
                                                        <input type="hidden" name="email" value="{{ $invoice->customer->CustomerEmail ?? '' }}">
                                                    <input type="hidden" name="subject" value="">
                                                    <input type="hidden" name="message" value="">
                                                    <input type="hidden" name="include_pdf" value="1">
                                                    <button type="submit" 
                                                            class="dropdown-item flex items-center w-full px-4 py-2 text-sm text-gray-700 hover:bg-gradient-to-r hover:from-purple-50 hover:to-purple-100 hover:text-purple-700 transition-all duration-150">
                                                        <i class="fas fa-paper-plane mr-3 h-4 w-4 text-purple-500"></i>
                                                        Send Bill
                                                    </button>
                                                </form>
                                                <!-- <form action="{{ route('invoices.rent.destroy', $invoice->BillID) }}" 
                                                      method="POST" 
                                                      onsubmit="return confirm('Are you sure you want to delete this invoice?');">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" 
                                                            class="flex items-center w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900">
                                                        <i class="fas fa-trash mr-3 h-4 w-4 text-red-500"></i>
                                                        Delete
                                                    </button>
                                                </form> -->
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="8" class="px-6 py-12 text-center">
                                    <div class="empty-state">
                                        <div class="inline-flex items-center justify-center w-20 h-20 bg-blue-100 rounded-full mb-4">
                                            <i class="fas fa-file-invoice text-3xl text-blue-500"></i>
                                        </div>
                                        <h3 class="mt-4 text-xl font-bold text-gray-900">No invoices found</h3>
                                        <p class="mt-2 text-sm text-gray-600 max-w-md mx-auto">Get started by creating your first rent invoice or adjust your filters to see existing invoices.</p>
                                        <div class="mt-8">
                                            <a href="{{ route('invoices.rent.create') }}" class="btn-primary inline-flex items-center px-6 py-3 border border-transparent text-sm font-medium rounded-md shadow-sm text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                                <i class="fas fa-plus -ml-1 mr-2 h-5 w-5"></i>
                                                Create New Invoice
                                            </a>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            
            @if($invoices->hasPages())
                <div class="mt-6">
                    {{ $invoices->links() }}
                </div>
            @endif
        </div>
    </div>
</div>

@push('scripts')
<script>
    // Function to open the send all invoices modal
    function openSendAllModal() {
        // Show loading state
        const subjectField = document.getElementById('subject');
        const messageField = document.getElementById('message');
        const subjectIndicator = document.getElementById('subjectIndicator');
        const messageIndicator = document.getElementById('messageIndicator');
        const subjectIcon = document.getElementById('subjectIcon');
        const charCount = document.getElementById('charCount');
        
        subjectField.value = 'Loading...';
        messageField.value = 'Loading...';
        
        // Show Bootstrap modal
        const modal = new bootstrap.Modal(document.getElementById('sendAllModal'));
        modal.show();
        
        // Fetch company templates
        fetch('{{ route("company.templates") }}')
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error('Error fetching templates:', data.error);
                    subjectField.value = '';
                    messageField.value = '';
                    return;
                }
                
                // Populate fields with company templates
                subjectField.value = data.email_subject || '';
                messageField.value = data.email_message || '';
                
                // Update character count
                charCount.textContent = messageField.value.length;
                
                // Show indicators and styling for custom templates
                if (data.has_custom_templates.email_subject) {
                    subjectField.classList.add('border-success');
                    subjectField.classList.remove('border-secondary');
                    subjectIndicator.classList.remove('d-none');
                    subjectIcon.classList.remove('text-muted');
                    subjectIcon.classList.add('text-success');
                } else {
                    subjectField.classList.remove('border-success');
                    subjectField.classList.add('border-secondary');
                    subjectIndicator.classList.add('d-none');
                    subjectIcon.classList.remove('text-success');
                    subjectIcon.classList.add('text-muted');
                }
                
                if (data.has_custom_templates.email_message) {
                    messageField.classList.add('border-success');
                    messageField.classList.remove('border-secondary');
                    messageIndicator.classList.remove('d-none');
                } else {
                    messageField.classList.remove('border-success');
                    messageField.classList.add('border-secondary');
                    messageIndicator.classList.add('d-none');
                }
            })
            .catch(error => {
                console.error('Error fetching templates:', error);
                subjectField.value = '';
                messageField.value = '';
                charCount.textContent = '0';
            });
    }
    
    // Function to handle Send All Invoices form submission
    function handleSendAllSubmit(e) {
        e.preventDefault();
        
        // Close the modal first
        closeSendAllModal();
        
        // Show loading dialog
        showLoadingDialog();
        
        // Update loading dialog content for "Send All"
        const loadingTitle = document.querySelector('#loadingDialog h3');
        const loadingText = document.querySelector('#loadingDialog .text-gray-800.font-semibold');
        const loadingSubtext = document.querySelector('#loadingDialog .text-gray-600.text-sm');
        const infoText = document.querySelector('#loadingDialog .text-blue-600.text-xs');
        
        if (loadingTitle) loadingTitle.textContent = 'Sending All Invoices';
        if (loadingText) loadingText.textContent = 'Sending Multiple Bills';
        if (loadingSubtext) loadingSubtext.textContent = 'Please wait while we generate and send all invoices';
        if (infoText) infoText.textContent = 'Processing multiple invoices and sending emails...';
        
        // Submit the form after showing loading dialog
        setTimeout(() => {
            document.getElementById('sendAllForm').submit();
        }, 100);
    }
    
    // Add character counter for message field
    document.addEventListener('DOMContentLoaded', function() {
        const messageField = document.getElementById('message');
        const charCount = document.getElementById('charCount');
        
        if (messageField && charCount) {
            messageField.addEventListener('input', function() {
                charCount.textContent = this.value.length;
            });
        }
    });
    
    // Function to close the send all invoices modal
    function closeSendAllModal() {
        const modal = bootstrap.Modal.getInstance(document.getElementById('sendAllModal'));
        if (modal) {
            modal.hide();
        }
    }
    
    // Function to show loading dialog
    function showLoadingDialog() {
        document.getElementById('loadingDialog').classList.remove('hidden');
        document.body.classList.add('overflow-hidden');
    }
    
    // Function to hide loading dialog
    function hideLoadingDialog() {
        document.getElementById('loadingDialog').classList.add('hidden');
        document.body.classList.remove('overflow-hidden');
    }
    
    // Add event listeners to all Send Bill forms
    document.addEventListener('DOMContentLoaded', function() {
        // Handle Send Bill forms in dropdowns
        const sendBillForms = document.querySelectorAll('.dropdown-item-form');
        sendBillForms.forEach(form => {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                showLoadingDialog();
                
                // Update loading dialog content for single bill
                const loadingTitle = document.querySelector('#loadingDialog h3');
                const loadingText = document.querySelector('#loadingDialog .text-gray-800.font-semibold');
                const loadingSubtext = document.querySelector('#loadingDialog .text-gray-600.text-sm');
                const infoText = document.querySelector('#loadingDialog .text-blue-600.text-xs');
                
                if (loadingTitle) loadingTitle.textContent = 'Sending Email';
                if (loadingText) loadingText.textContent = 'Sending Bill to Customer';
                if (loadingSubtext) loadingSubtext.textContent = 'Please wait while we generate and send your invoice';
                if (infoText) infoText.textContent = 'Generating PDF and sending email...';
                
                // Submit the form after showing loading dialog
                setTimeout(() => {
                    form.submit();
                }, 100);
            });
        });
        
        // Handle message field character counter
        const messageField = document.getElementById('message');
        const charCount = document.getElementById('charCount');
        
        if (messageField && charCount) {
            messageField.addEventListener('input', function() {
                charCount.textContent = this.value.length;
            });
        }
    });
    
    // Function to toggle dropdown visibility
    function toggleDropdown(dropdownId) {
        const dropdown = document.getElementById(dropdownId);
        const isHidden = dropdown.classList.contains('hidden');
        
        // Close all dropdowns first
        document.querySelectorAll('[id^="dropdown-"]').forEach(el => {
            el.classList.add('hidden');
            el.classList.remove('show');
        });
        
        // Open the clicked dropdown if it was hidden
        if (isHidden) {
            dropdown.classList.remove('hidden');
            // Trigger animation
            setTimeout(() => {
                dropdown.classList.add('show');
            }, 10);
        }
    }
    
    // Close dropdown when clicking outside
    document.addEventListener('click', function(event) {
        const modal = document.getElementById('sendAllModal');
        if (modal && event.target === modal) {
            closeSendAllModal();
        }
        
        // Close dropdowns when clicking outside
        if (!event.target.closest('.relative')) {
            document.querySelectorAll('[id^="dropdown-"]').forEach(el => {
                el.classList.remove('show');
                // Add delay before hiding to allow animation to complete
                setTimeout(() => {
                    if (!el.classList.contains('show')) {
                        el.classList.add('hidden');
                    }
                }, 200);
            });
        }
    });

    // Initialize tooltips
    document.addEventListener('DOMContentLoaded', function() {
        const tooltipElements = document.querySelectorAll('[data-tooltip]');
        tooltipElements.forEach(el => {
            const tooltip = document.createElement('div');
            tooltip.className = 'hidden md:block absolute z-10 py-1 px-2 text-xs font-medium text-white bg-gray-900 rounded-md shadow-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200';
            tooltip.textContent = el.getAttribute('data-tooltip');
            
            const wrapper = document.createElement('div');
            wrapper.className = 'relative group';
            wrapper.appendChild(el.cloneNode(true));
            wrapper.appendChild(tooltip);
            
            el.parentNode.replaceChild(wrapper, el);
            
            // Position tooltip
            wrapper.addEventListener('mouseenter', () => {
                const rect = wrapper.getBoundingClientRect();
                tooltip.style.top = `${rect.top - 30}px`;
                tooltip.style.left = `${rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2)}px`;
                tooltip.classList.remove('opacity-0');
                tooltip.classList.add('opacity-100');
            });
            
            wrapper.addEventListener('mouseleave', () => {
                tooltip.classList.remove('opacity-100');
                tooltip.classList.add('opacity-0');
            });
        });
    });
</script>
@endpush
@endsection
