@extends('layouts.app')

@push('styles')
<style>
    @media print {
        @page {
            size: A4;
            margin: 1cm;
        }
        body {
            font-size: 12pt;
            background: white;
            color: black;
        }
        .no-print, .no-print * {
            display: none !important;
        }
        .print-section {
            width: 100%;
            margin: 0;
            padding: 0;
        }
        .print-header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }
        .print-header img {
            max-height: 60px;
            margin-bottom: 10px;
        }
        .print-watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 80px;
            font-weight: bold;
            color: rgba(0, 0, 0, 0.1);
            pointer-events: none;
            z-index: 9999;
            white-space: nowrap;
        }
        .bg-gray-50 {
            background-color: #f9fafb !important;
            -webkit-print-color-adjust: exact;
        }
        .bg-green-100, .bg-yellow-100, .bg-red-100 {
            -webkit-print-color-adjust: exact;
        }
        .border, .border-t, .border-b, .border-l, .border-r, .border-gray-200, .border-blue-200 {
            border-color: #e5e7eb !important;
            -webkit-print-color-adjust: exact;
        }
    }
</style>
@endpush

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    });

    function printBill() {
        const printContent = document.getElementById('printable-area').innerHTML;
        const printWindow = window.open('', '_blank');
        
        printWindow.document.write(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>Utility Bill #UTL-{{ str_pad($bill->BillID, 5, '0', STR_PAD_LEFT) }}</title>
                <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
                <style>
                    @page { size: A4; margin: 1cm; }
                    body { font-size: 12pt; background: white; color: black; }
                    .print-watermark {
                        position: fixed;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%) rotate(-45deg);
                        font-size: 80px;
                        font-weight: bold;
                        color: rgba(0, 0, 0, 0.05);
                        pointer-events: none;
                        z-index: 9999;
                        white-space: nowrap;
                    }
                    .print-header {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-bottom: 20px;
                        padding-bottom: 10px;
                        border-bottom: 1px solid #e5e7eb;
                    }
                    .company-info {
                        flex: 1;
                    }
                    .company-logo {
                        width: 150px;
                        text-align: right;
                    }
                    .company-logo img {
                        max-height: 80px;
                        width: auto;
                    }
                    .bill-title {
                        background-color: #1a365d;
                        color: white;
                        padding: 8px 15px;
                        font-weight: bold;
                        margin: 15px 0;
                        text-align: center;
                    }
                    .table > :not(:first-child) {
                        border-top: 2px solid #dee2e6;
                    }
                    .table > thead > tr > th {
                        border-bottom-width: 1px;
                        font-weight: 600;
                        text-transform: uppercase;
                        font-size: 0.75rem;
                        letter-spacing: 0.05em;
                        color: #6c757d;
                    }
                    .badge {
                        font-size: 0.75rem;
                        font-weight: 600;
                        padding: 0.35em 0.65em;
                    }
                </style>
            </head>
            <body class="bg-white">
                <div class="print-watermark">{{ config('app.name', 'Property Management') }}</div>
                
                <!-- Company Header -->
                <div class="print-header">
                    <div class="company-info">
                        <div style="font-weight: bold; font-size: 16px; margin-bottom: 5px;">{{ config('app.name', 'Property Management') }}</div>
                        <div>P.O. Box 14090-00800 Nairobi</div>
                        <div>Phone: +254 20 4446914</div>
                        <div>Email: info@hassconsult.co.ke</div>
                    </div>
                    <div class="company-logo">
                        <img src="{{ asset('images/watermarklogo.png') }}" alt="Company Logo">
                    </div>
                </div>
                
                <div class="bill-title">UTILITY BILL</div>
                
                ${printContent}
                
                <script>
                    window.onafterprint = function() {
                        window.close();
                    };
                    window.onload = function() {
                        setTimeout(function() {
                            window.print();
                        }, 500);
                    };
                <\/script>
            </body>
            </html>
        `);
        
        printWindow.document.close();
    }

    // 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');
    }
    
    // Handle Send Bill form submission
    document.addEventListener('DOMContentLoaded', function() {
        const sendBillForm = document.querySelector('form[action*="{{ route('bills.utility.send', $bill->BillID) }}"]');
        if (sendBillForm) {
            sendBillForm.addEventListener('submit', function(e) {
                e.preventDefault();
                showLoadingDialog();
                
                // Update loading dialog content for single bill
                const loadingTitle = document.querySelector('#loadingDialog h3');
                const loadingSubtitle = document.querySelector('#loadingDialog .text-blue-100.text-sm');
                const loadingText = document.querySelector('#loadingDialog .text-gray-800.font-semibold.text-lg');
                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 (loadingSubtitle) loadingSubtitle.textContent = 'Processing your request...';
                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(() => {
                    sendBillForm.submit();
                }, 100);
            });
        }
    });
</script>
@endpush

@section('content')
<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Utility Bill Details</h1>
        <div>
            <a href="{{ route('bills.utility.download', $bill->BillID) }}" class="btn btn-primary no-print" target="_blank">
                <i class="fas fa-print fa-sm text-white-50"></i> Print Bill
            </a>
            <a href="{{ route('bills.utility.index') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left fa-sm text-white-50"></i> Back to Bills
            </a>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <!-- Bill Header -->
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary">Bill #UTL-{{ str_pad($bill->BillID, 5, '0', STR_PAD_LEFT) }}</h6>
                    <span class="badge {{ $bill->BalanceCF <= 0 ? 'badge-success' : ($bill->DueDate < now() ? 'badge-danger' : 'badge-warning') }}">
                        {{ $bill->BalanceCF <= 0 ? 'Paid' : ($bill->DueDate < now() ? 'Overdue' : 'Pending') }}
                    </span>
                </div>
                <div class="card-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h6>Bill To:</h6>
                            <address>
                                <strong>{{ $bill->CustomerName }}</strong><br>
                                @if($bill->PropertyName)
                                    {{ $bill->PropertyName }}<br>
                                    @if($bill->UnitName)
                                        Unit: {{ $bill->UnitName }}<br>
                                    @endif
                                @endif
                                {{ $bill->CustomerEmail }}<br>
                                {{ $bill->Phone }}
                            </address>
                        </div>
                        <div class="col-md-6 text-md-right">
                            <h6>Bill Details:</h6>
                            <p>
                                <strong>Bill #:</strong> UTL-{{ str_pad($bill->BillID, 5, '0', STR_PAD_LEFT) }}<br>
                                <strong>Billing Period:</strong> {{ \Carbon\Carbon::parse($bill->BillingDate)->format('F Y') }}<br>
                                <strong>Bill Date:</strong> {{ \Carbon\Carbon::parse($bill->BillingDate)->format('d M Y') }}<br>
                                <strong>Due Date:</strong> {{ \Carbon\Carbon::parse($bill->DueDate)->format('d M Y') }}<br>
                                <strong>Status:</strong> 
                                <span class="badge {{ $bill->BalanceCF <= 0 ? 'badge-success' : ($bill->DueDate < now() ? 'badge-danger' : 'badge-warning') }}">
                                    {{ $bill->BalanceCF <= 0 ? 'Paid' : ($bill->DueDate < now() ? 'Overdue' : 'Pending') }}
                                </span>
                            </p>
                        </div>
                    </div>

                    <!-- Bill Items -->
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Description</th>
                                    @if($billLines->contains('BLineQty', '>', 1))
                                        <th class="text-right">Qty</th>
                                        <th class="text-right">Rate</th>
                                    @endif
                                    <th class="text-right">Amount (KES)</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($billLines as $index => $line)
                                    <tr>
                                        <td>{{ $index + 1 }}</td>
                                        <td>{{ $line->BLineDesc }}</td>
                                        @if($billLines->contains('BLineQty', '>', 1))
                                            <td class="text-right">{{ $line->BLineQty > 1 ? number_format($line->BLineQty, 2) : '' }}</td>
                                            <td class="text-right">{{ $line->BLineQty > 1 ? number_format($line->BLineUnitPrice, 2) : '' }}</td>
                                        @endif
                                        <td class="text-right">{{ number_format($line->BLineAmount, 2) }}</td>
                                    </tr>
                                @endforeach
                            </tbody>
                            <tfoot>
                                <tr>
                                    <td colspan="{{ $billLines->contains('BLineQty', '>', 1) ? '4' : '2' }}" class="text-right"><strong>Subtotal:</strong></td>
                                    <td class="text-right">{{ number_format($subtotal, 2) }}</td>
                                </tr>
                                @if($tax > 0)
                                <tr>
                                    <td colspan="{{ $billLines->contains('BLineQty', '>', 1) ? '4' : '2' }}" class="text-right"><strong>Tax:</strong></td>
                                    <td class="text-right">{{ number_format($tax, 2) }}</td>
                                </tr>
                                @endif
                                @if($bill->BalanceCF < $total)
                                <tr>
                                    <td colspan="{{ $billLines->contains('BLineQty', '>', 1) ? '4' : '2' }}" class="text-right"><strong>Amount Paid:</strong></td>
                                    <td class="text-right text-success">-{{ number_format($total - $bill->BalanceCF, 2) }}</td>
                                </tr>
                                @endif
                                <tr class="table-active">
                                    <td colspan="{{ $billLines->contains('BLineQty', '>', 1) ? '4' : '2' }}" class="text-right"><strong>Total Due:</strong></td>
                                    <td class="text-right"><strong>{{ number_format($bill->BalanceCF > 0 ? $bill->BalanceCF : $total, 2) }}</strong></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    @if($bill->BalanceCF > 0)
                    <div class="alert alert-warning mt-4">
                        <i class="fas fa-exclamation-triangle"></i> 
                        Payment of <strong>KES {{ number_format($bill->BalanceCF, 2) }}</strong> is due by 
                        <strong>{{ \Carbon\Carbon::parse($bill->DueDate)->format('F d, Y') }}</strong>.
                    </div>
                    @endif
                </div>
            </div>

            <!-- Payment History -->
            @if(isset($payments) && $payments->count() > 0)
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Payment History</h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Reference</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($payments as $payment)
                                    <tr>
                                        <td>{{ \Carbon\Carbon::parse($payment->PaymentDate)->format('d M Y') }}</td>
                                        <td>{{ $payment->PaymentReference ?? 'N/A' }}</td>
                                        <td class="text-right">{{ number_format($payment->Amount, 2) }}</td>
                                        <td>
                                            <span class="badge {{ $payment->Status == 'Completed' ? 'badge-success' : 'badge-warning' }}">
                                                {{ $payment->Status }}
                                            </span>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            @endif
        </div>

        <div class="col-lg-4">
            <!-- Actions -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Actions</h6>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        @if($bill->BalanceCF > 0)
                            <!-- <a href="#" class="btn btn-success btn-block mb-2" data-bs-toggle="modal" data-bs-target="#recordPaymentModal">
                                <i class="fas fa-money-bill-wave"></i> Record Payment
                            </a> -->
                            <form action="{{ route('bills.utility.send', $bill->BillID) }}" method="POST" class="d-grid">
                                @csrf
                                <button type="submit" class="btn btn-primary btn-block mb-2">
                                    <i class="fas fa-envelope"></i> Send to Customer
                                </button>
                            </form>
                        @endif
                        <a href="{{ route('bills.utility.download', $bill->BillID) }}" class="btn btn-info btn-block mb-2" target="_blank">
                            <i class="fas fa-download"></i> Download PDF
                        </a>
                    </div>
                </div>
            </div>

            <!-- Bill Summary -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Bill Summary</h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <tr>
                                <th>Subtotal:</th>
                                <td class="text-right">{{ number_format($subtotal, 2) }}</td>
                            </tr>
                            @if($tax > 0)
                            <tr>
                                <th>Tax:</th>
                                <td class="text-right">{{ number_format($tax, 2) }}</td>
                            </tr>
                            @endif
                            @if($bill->BalanceCF < $total)
                            <tr>
                                <th>Amount Paid:</th>
                                <td class="text-right text-success">-{{ number_format($total - $bill->BalanceCF, 2) }}</td>
                            </tr>
                            @endif
                            <tr class="table-active">
                                <th>Total Due:</th>
                                <th class="text-right">{{ number_format($bill->BalanceCF > 0 ? $bill->BalanceCF : $total, 2) }}</th>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Notes -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Notes</h6>
                </div>
                <div class="card-body">
                    <p class="text-muted">
                        @if($bill->BalanceCF <= 0)
                            This bill has been fully paid. Thank you for your payment.
                        @elseif($bill->DueDate < now())
                            This bill is overdue. Please make payment as soon as possible to avoid any service interruptions.
                        @else
                            Payment is due by {{ \Carbon\Carbon::parse($bill->DueDate)->format('F d, Y') }}.
                        @endif
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Record Payment Modal -->
<div class="modal fade" id="recordPaymentModal" tabindex="-1" role="dialog" aria-labelledby="recordPaymentModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="recordPaymentModalLabel">Record Payment</h5>
                <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="{{ route('payments.store') }}" method="POST">
                @csrf
                <input type="hidden" name="bill_id" value="{{ $bill->BillID }}">
                <input type="hidden" name="bill_type" value="utility">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="amount">Amount (KES)</label>
                        <input type="number" step="0.01" class="form-control" id="amount" name="amount" value="{{ $bill->BalanceCF }}" required>
                    </div>
                    <div class="form-group">
                        <label for="payment_date">Payment Date</label>
                        <input type="date" class="form-control" id="payment_date" name="payment_date" value="{{ date('Y-m-d') }}" required>
                    </div>
                    <div class="form-group">
                        <label for="payment_method">Payment Method</label>
                        <select class="form-control" id="payment_method" name="payment_method" required>
                            <option value="">Select Payment Method</option>
                            <option value="Cash">Cash</option>
                            <option value="M-Pesa">M-Pesa</option>
                            <option value="Bank Transfer">Bank Transfer</option>
                            <option value="Cheque">Cheque</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="reference">Reference/Receipt #</label>
                        <input type="text" class="form-control" id="reference" name="reference" placeholder="e.g. M-PESA XA1234">
                    </div>
                    <div class="form-group">
                        <label for="notes">Notes</label>
                        <textarea class="form-control" id="notes" name="notes" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Record Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 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>

@endsection
