@extends('layouts.app')

@push('styles')
<style>
    :root {
        --primary-blue: #0000FF;      /* Vibrant blue from logo */
        --primary-yellow: #FFFF00;    /* Bright yellow from logo */
        --dark-text: #333333;         /* Dark grey for text */
        --light-bg: #f5f8ff;          /* Very light blue background */
        --border-color: #e0e6ff;      /* Light blue border */
        --accent-color: #0000cc;      /* Slightly darker blue for hover states */
        --card-shadow: 0 4px 12px rgba(0, 0, 255, 0.1);
    }
    
    .card {
        border: none;
        border-left: 3px solid var(--primary-blue);
        box-shadow: var(--card-shadow);
        border-radius: 0.75rem;
        overflow: hidden;
        border-right: 1px solid var(--border-color);
        border-top: 1px solid var(--border-color);
        border-bottom: 1px solid var(--border-color);
    }
    
    .card-header {
        background: var(--primary-blue);
        border-bottom: 3px solid var(--primary-yellow);
        padding: 1.25rem 1.5rem;
    }
    
    .card-title {
        font-weight: 700;
        margin: 0;
        color: white;
        font-size: 1.5rem;
        letter-spacing: 0.5px;
        text-shadow: 1px 1px 2px rgba(0,0,0,0.2);
    }
    
    .form-select, .form-control {
        border-radius: 0.5rem;
        padding: 0.625rem 1rem;
        border: 1px solid var(--border-color);
        transition: all 0.2s ease-in-out;
        background-color: white;
    }
    
    .btn {
        border-radius: 0.5rem;
        font-weight: 600;
        padding: 0.5rem 1.25rem;
        transition: all 0.2s ease-in-out;
    }
    
    .btn-primary {
        background-color: var(--primary-blue);
        border: 2px solid var(--primary-blue);
    }
    
    .btn-primary:hover, .btn-primary:focus {
        background-color: #0000cc;
        border-color: #0000cc;
        transform: translateY(-1px);
    }
    
    .btn-outline-primary {
        border: 2px solid var(--primary-blue);
        color: var(--primary-blue);
        background-color: white;
    }
    
    .btn-outline-primary:hover, .btn-outline-primary:focus {
        background-color: var(--primary-blue);
        color: white;
        border-color: var(--primary-blue);
        transform: translateY(-1px);
    }
    
    .report-option {
        transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        border: 1px solid var(--border-color);
        border-radius: 0.75rem;
        padding: 1.75rem 1.25rem;
        text-align: center;
        background: white;
        cursor: pointer;
        height: 100%;
        min-height: 200px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        position: relative;
        overflow: hidden;
        background: linear-gradient(145deg, #ffffff, #f8f9fa);
    }
    
    .report-option::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--primary-blue);
        transform: scaleX(0);
        transition: transform 0.3s ease;
    }
    
    .report-option:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        border-color: var(--primary-yellow) var(--border-color) var(--border-color) var(--border-color);
        border-width: 2px 1px 1px 1px;
    }
    
    .report-option:hover::before {
        transform: scaleX(1);
    }
    
    .report-option i {
        font-size: 2.25rem;
        margin-bottom: 1rem;
        color: var(--primary-blue);
        background: linear-gradient(135deg, rgba(0, 0, 255, 0.05), rgba(0, 0, 255, 0.15));
        width: 70px;
        height: 70px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
    }
    
    .report-option:hover i {
        transform: scale(1.05);
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1);
    }
    
    .report-option h5 {
        color: var(--dark-text);
        font-weight: 600;
        margin-bottom: 0.5rem;
        font-size: 1.1rem;
        transition: color 0.3s ease;
    }
    
    .report-option p {
        color: #6c757d;
        font-size: 0.9rem;
        line-height: 1.5;
        margin-bottom: 0;
        transition: color 0.3s ease;
    }
    
    .report-option:hover h5 {
        color: var(--primary-blue);
    }
    
    .print-options {
        background-color: var(--light-bg);
        border-radius: 0.75rem;
        padding: 1.25rem;
        border: 1px solid var(--border-color);
    }
    
    .form-check-input:checked {
        background-color: var(--primary-blue);
        border-color: var(--primary-blue);
    }
    
    .form-check-input:focus {
        box-shadow: 0 0 0 0.25rem rgba(0, 0, 255, 0.1);
        border-color: var(--primary-blue);
    }
    
    .form-label {
        font-weight: 600;
        color: var(--dark-text);
    }
    
    .card-body {
        padding: 2rem;
    }
</style>
@endpush

@section('content')
<div class="container-fluid py-4 px-4">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <!-- Compact Light Blue Header -->
                <div class="card-header" style="
                    background: linear-gradient(135deg, #e6f0ff, #cce0ff);
                    border-bottom: 2px solid var(--primary-yellow);
                    padding: 0.75rem 1.5rem;
                ">
                    <div class="d-flex align-items-center gap-2">
                        <i class="bi bi-file-earmark-text" style="font-size: 1.5rem; color: var(--primary-blue);"></i>
                        <h1 class="card-title mb-0" style="color: var(--primary-blue); font-size: 1.5rem;">Billing Summary</h1>
                    </div>
                    <p class="text-blue-150 mb-0 mt-2" style="font-size: 1rem;">
                        <i class="bi bi-info-circle-fill me-1"></i> 
                        View and manage billing summaries, generate reports, and export data
                    </p>
                </div>
                
                <!-- Body -->
                <div class="card-body p-4">
                    <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-3 mb-4">
                        <!-- Bulk Invoice Selection -->
                        <div class="flex-grow-1">
                            <label for="bulkInvoice" class="form-label fw-semibold mb-2">Bulk Invoice</label>
                            <select id="bulkInvoice" name="bulk_invoice" class="form-select form-select-sm">
                                @foreach($bulkInvoices as $bulkInvoice)
                                    <option value="{{ $bulkInvoice->BulkInvoiceID }}" {{ $bulkInvoice->BulkInvoiceID == $selectedBulkInvoice ? 'selected' : '' }}>
                                        {{ $bulkInvoice->BulkInvoiceID }} - {{ $bulkInvoice->BillingPeriod }}
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Print Options -->
                        <div class="d-flex align-items-end">
                            <div class="d-flex align-items-center gap-3">
                                <span class="fw-semibold mt-4">Export as:</span>
                                <div class="btn-group mt-4" role="group">
                                    <input type="radio" class="btn-check" name="print_to" id="previewRadio" value="preview" autocomplete="off" checked>
                                    <label class="btn btn-outline-primary" for="previewRadio">
                                        <i class="bi bi-printer me-1"></i> Preview
                                    </label>

                                    <input type="radio" class="btn-check" name="print_to" id="pdfRadio" value="pdf" autocomplete="off">
                                    <label class="btn btn-outline-primary" for="pdfRadio">
                                        <i class="bi bi-file-earmark-pdf me-1"></i> PDF
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Report Options -->
                    <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-4 mb-4">
                        <div class="col-md-4">
                            <div class="report-option h-100" id="summaryOption" data-action="summary">
                                <i class="bi bi-file-text"></i>
                                <h5 class="mb-1">Summary</h5>
                                <p class="text-muted small mb-0">View summary report</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="report-option h-100" id="varianceOption" data-action="variance">
                                <i class="bi bi-graph-up"></i>
                                <h5 class="mb-1">Variance</h5>
                                <p class="text-muted small mb-0">View variance analysis</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="report-option h-100" id="detailedOption" data-action="detailed">
                                <i class="bi bi-list-check"></i>
                                <h5 class="mb-1">Detailed</h5>
                                <p class="text-muted small mb-0">View detailed report</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="report-option h-100" id="detailReport2Option" data-action="detail-report-2">
                                <i class="bi bi-file-earmark-text"></i>
                                <h5 class="mb-1">Detail Report 2</h5>
                                <p class="mb-0">Detailed bill report with additional information</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="report-option h-100" id="vatSummaryOption" data-action="vat-summary">
                                <i class="bi bi-receipt"></i>
                                <h5 class="mb-1">VAT Summary</h5>
                                <p class="mb-0">View VAT summary for the selected period</p>
                            </div>
                        </div>
                       
                        <div class="col-md-4">
                            <div class="report-option h-100" id="printBillsOption" data-action="print-bills">
                                <i class="bi bi-printer"></i>
                                <h5 class="mb-1">Print Bills</h5>
                                <p class="text-muted small mb-0">Print selected bills in bulk</p>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <a href="#" onclick="event.preventDefault(); 
                                const bulkInvoiceSelect = document.getElementById('bulkInvoice');
                                const billingPeriod = bulkInvoiceSelect.options[bulkInvoiceSelect.selectedIndex].text.split(' - ')[1];
                                window.location.href = '{{ route('reports.viewPrintBillsPerCourt') }}/' + encodeURIComponent(billingPeriod);">
                                <div class="report-option h-100">
                                    <i class="bi bi-file-pdf"></i>
                                    <h5 class="mb-1">Print Bills PDF V2</h5>
                                    <p class="text-muted small mb-0">Generate PDF bills grouped by court (V2)</p>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">

<script>
// Function to initialize report options
function initializeReportOptions() {
    const reportOptions = document.querySelectorAll('.report-option[data-action]');
    const bulkInvoiceSelect = document.getElementById('bulkInvoice');
    
    // Function to update clickable state
    function updateReportOptions() {
        const isEnabled = bulkInvoiceSelect && bulkInvoiceSelect.value !== '';
        
        reportOptions.forEach(option => {
            // Skip setting up click handler for detail-report-2 as it has its own handler
            if (option.getAttribute('data-action') === 'detail-report-2') {
                return;
            }
            
            if (isEnabled) {
                option.style.cursor = 'pointer';
                option.style.opacity = '1';
                option.onclick = function() {
                    handleSummaryAction(this.getAttribute('data-action'));
                };
            } else {
                option.style.cursor = 'not-allowed';
                option.style.opacity = '0.6';
                option.onclick = null;
            }
        });
    }
    
    // Initial update
    updateReportOptions();
    
    // Update when bulk invoice changes
    if (bulkInvoiceSelect) {
        bulkInvoiceSelect.addEventListener('change', updateReportOptions);
    }
}

// Call the initialization function when the DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    initializeReportOptions();
    
    // Initialize the variance actual button state
    const bulkInvoiceSelect = document.getElementById('bulkInvoice');
    const varianceActualBtn = document.getElementById('varianceActualBtn');
    
    if (bulkInvoiceSelect && varianceActualBtn) {
        const isEnabled = bulkInvoiceSelect.value !== '';
        varianceActualBtn.disabled = !isEnabled;
        varianceActualBtn.className = isEnabled ? 
            'btn btn-outline-primary' : 
            'btn btn-outline-secondary';
            
        if (isEnabled) {
            varianceActualBtn.onclick = function() {
                handleSummaryAction('variance_actual');
            };
        }
    }
});

// Handle report actions
function handleSummaryAction(action) {
    const bulkInvoiceSelect = document.getElementById('bulkInvoice');
    if (!bulkInvoiceSelect || !bulkInvoiceSelect.value) {
        alert('Please select a bulk invoice first');
        return;
    }
    
    const printTo = document.querySelector('input[name="print_to"]:checked').value;
    const companySelect = document.querySelector('select[name="company"]');
    const companyId = companySelect ? companySelect.value : '';
    const bulkInvoiceId = bulkInvoiceSelect.value;
    
    let billingPeriod = '';
    if (bulkInvoiceId) {
        const selectedOption = bulkInvoiceSelect.options[bulkInvoiceSelect.selectedIndex];
        const optionText = selectedOption.text;
        if (optionText.includes(' - ')) {
            billingPeriod = optionText.split(' - ')[1];
        }
    } else if (bulkInvoiceSelect && bulkInvoiceSelect.options.length > 1) {
        const firstOption = bulkInvoiceSelect.options[1];
        const optionText = firstOption.text;
        if (optionText.includes(' - ')) {
            billingPeriod = optionText.split(' - ')[1];
        }
    }
    
    // Handle VAT Summary action
    if (action === 'vat-summary') {
        const url = '{{ route("reports.vat-summary") }}' + '?bulk_invoice_id=' + encodeURIComponent(bulkInvoiceId);
        window.location.href = url;
        return;
    }
    
    console.log('Action:', action, 'Print to:', printTo, 'Company:', companyId, 'Period:', billingPeriod);
    
    if (action === 'summary' && printTo === 'preview') {
        // Open PDF in new tab with the same parameters
        const params = new URLSearchParams({
            company: companyId,
            period: billingPeriod,
            action: 'summary',
            format: 'pdf',
            download: '0'  // 0 for view in browser
        });
        window.open(`/reports/bill-summary-view?${params}`, '_blank');
    } else if (action === 'variance') {
        // Open variance report in same tab
        const params = new URLSearchParams({
            company: companyId,
            period: billingPeriod,
            bulk_invoice_id: bulkInvoiceId,  // Add bulk_invoice_id to the URL parameters
            action: 'variance'
        });
        window.location.href = `/reports/variance-report?${params}`;
    } else if (action === 'detailed') {
        // Open detailed report in same tab
        const params = new URLSearchParams({
            company: companyId,
            period: billingPeriod,
            action: 'detailed'
        });
        window.location.href = `/reports/detail-report?${params}`;
    } else if (action === 'vat-summary') {
        // Open VAT summary in new tab
        const params = new URLSearchParams({
            company: companyId,
            period: billingPeriod,
            bulk_invoice_id: bulkInvoiceId,
            action: 'vat-summary',
            format: 'pdf',
            download: '0'  // 0 for view in browser
        });
        window.open(`/reports/vat-summary?${params}`, '_blank');
    } else if (action === 'print-bills') {
        // Open bill print view using the new view_bill_print_ex
        const params = new URLSearchParams({
            bulk_invoice_id: bulkInvoiceId,
            format: printTo === 'pdf' ? 'pdf' : 'html',
            download: '0'  // 0 for view in browser
        });
        window.open(`/reports/print-bills?${params}`, '_blank');
    } else {
        // Handle other actions
        alert(`${action} with ${printTo} for Company: ${companyId}, Period: ${billingPeriod}\n\nThis functionality will be implemented.`);
    }
}
</script>
@endpush



@push('scripts')
            <script>

                function updateModalWithCustomerId() {
                    const customerId = document.getElementById('selected_customer_id').value;

                    // Get the selected bulk invoice's billing period
                    const bulkInvoiceSelect = document.getElementById('bulkInvoiceSelect');
                    const selectedOption = bulkInvoiceSelect.options[bulkInvoiceSelect.selectedIndex];
                    const billingPeriod = selectedOption.getAttribute('data-billing-period') || '';

                    if (customerId) {
                        // Open PDF in a new tab with billing period
                        window.open(`/reports/bill-summary/${customerId}/pdf?print=true&billing_period=${encodeURIComponent(billingPeriod)}`, '_blank');
                        // Reset the selection
                        const allRows = document.querySelectorAll('.selectable-row');
                        allRows.forEach(row => row.classList.remove('selected-row'));
                        lastSelected = null;
                        updatePrintButtons(false);
                    }
                }


                // Add event listener for print button
                document.addEventListener('DOMContentLoaded', function () {
                    document.getElementById('printBillBtn').addEventListener('click', function (e) {
                        e.preventDefault();
                        const customerId = document.getElementById('selected_customer_id').value;

                        // Get the selected bulk invoice's billing period
                        const bulkInvoiceSelect = document.getElementById('bulkInvoiceSelect');
                        const selectedOption = bulkInvoiceSelect.options[bulkInvoiceSelect.selectedIndex];
                        const billingPeriod = selectedOption.getAttribute('data-billing-period') || '';

                        if (customerId) {
                            window.open(`/reports/bill-summary/${customerId}/pdf?print=true&billing_period=${encodeURIComponent(billingPeriod)}`, '_blank');
                        }
                    });
                });

                  const detailReport2Option = document.getElementById('detailReport2Option');
    function updateDetailReport2Visibility() {
        const bulkInvoiceSelect = document.getElementById('bulkInvoice');
        if (detailReport2Option && bulkInvoiceSelect) {
            const isVisible = bulkInvoiceSelect.value !== '';
            detailReport2Option.style.display = isVisible ? 'block' : 'none';
        }
    }

    // Initial update
    updateDetailReport2Visibility();

    // Update when bulk invoice changes
    const bulkInvoiceSelect = document.getElementById('bulkInvoice');
    if (bulkInvoiceSelect) {
        bulkInvoiceSelect.addEventListener('change', updateDetailReport2Visibility);
    }

    if (detailReport2Option) {
        detailReport2Option.addEventListener('click', function() {
            const bulkInvoiceId = document.getElementById('bulkInvoice').value;
            if (bulkInvoiceId) {
                const url = `{{ route('reports.detail-report-2', ['bulk_invoice_id' => '']) }}/${bulkInvoiceId}`;
                window.location.href = url;
            }
        });
    }
    
                let lastSelected = null;

                function selectRow(row) {
                    console.log("Clicked row:", row);

                    // Get the customer ID from the data attribute
                    const id = row.getAttribute('data-customer-id');
                    console.log("Customer ID:", id);

                    // Toggle off if same row
                    if (lastSelected === row) {
                        // Reset styles for all cells in the row
                        const cells = row.getElementsByTagName('td');
                        for (let cell of cells) {
                            cell.style.backgroundColor = '';
                            cell.style.color = '';
                        }
                        row.classList.remove('selected-row');
                        lastSelected = null;
                        document.getElementById('selected_customer_id').value = "";
                        return;
                    }

                    // Reset all rows
                    const allRows = document.querySelectorAll('.selectable-row');
                    allRows.forEach(r => {
                        r.classList.remove('selected-row');
                        const cells = r.getElementsByTagName('td');
                        for (let cell of cells) {
                            cell.style.backgroundColor = '';
                            cell.style.color = '';
                        }
                    });

                    // Set styles for the selected row
                    const cells = row.getElementsByTagName('td');
                    for (let cell of cells) {
                        cell.style.backgroundColor = '#1e40af';
                        cell.style.color = 'white';
                    }

                    row.classList.add('selected-row');
                    lastSelected = row;

                    // Update hidden inputs and enable/disable print buttons
                    const hiddenInput = document.getElementById('selected_customer_id');
                    const billingPeriodInput = document.getElementById('selected_billing_period');
                    if (hiddenInput) {
                        hiddenInput.value = id;
                        // Get billing period from the row's data attribute
                        const billingPeriod = row.getAttribute('data-billing-period') || '';
                        if (billingPeriodInput) {
                            billingPeriodInput.value = billingPeriod;
                        }
                        // Enable the print buttons
                        updatePrintButtons(true);
                    }

                    console.log("Selected customer ID:", id);
                }


                // Keyboard navigation
                document.addEventListener('keydown', function (e) {
                    const rows = Array.from(document.querySelectorAll('.selectable-row'));
                    if (rows.length === 0) return;

                    let index = rows.indexOf(lastSelected);

                    if (e.key === 'ArrowDown') {
                        e.preventDefault();
                        index = Math.min(index + 1, rows.length - 1);
                        selectRow(rows[index]);
                        rows[index].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }

                    if (e.key === 'ArrowUp') {
                        e.preventDefault();
                        index = Math.max(index - 1, 0);
                        selectRow(rows[index]);
                        rows[index].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }

                    // Enter key triggers double-click action
                    if (e.key === 'Enter' && lastSelected) {
                        lastSelected.dispatchEvent(new Event('dblclick'));
                    }
                });


                // Add event listener for print statement button
                document.getElementById('printStatementBtn').addEventListener('click', function (e) {
                    e.preventDefault();
                    const customerId = document.getElementById('selected_customer_id').value;

                    if (customerId) {
                        window.open(`/reports/customer-statement/${customerId}/pdf`, '_blank');
                    }
                });

                // Enable/disable print buttons when a row is selected
                function updatePrintButtons(enabled) {
                    const printBillBtn = document.getElementById('printBillBtn');
                    const printStatementBtn = document.getElementById('printStatementBtn');

                    if (printBillBtn) printBillBtn.disabled = !enabled;
                    if (printStatementBtn) printStatementBtn.disabled = !enabled;
                }
            </script>
        @endpush