@extends('layouts.app')

@section('content')
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h3 class="card-title mb-0"><i class="fas fa-tint mr-2"></i>Process Water Bills</h3>
                </div>
                <div class="card-body">
                    @if(session('success'))
                        <div class="alert alert-success">
                            {{ session('success') }}
                        </div>
                    @endif

                    @if($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    @if(empty($latestBillingPeriod))
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle"></i>
                            There are no unbilled water periods available for processing.
                        </div>
                    @else
                        <form id="processBillsForm" action="{{ route('bills.water.store') }}" method="POST" class="needs-validation" novalidate>
                            @csrf
                            <input type="hidden" name="company_id" value="{{ $companyID ?? '' }}">
                            <input type="hidden" name="billing_period" value="{{ $latestBillingPeriod ?? '' }}">

                            <div class="alert alert-info mb-4">
                                <strong>Water Billing Period:</strong> {{ $latestBillingPeriod ?? 'N/A' }}
                            </div>

                            <div class="table-responsive mb-4">
                                <table class="table table-bordered table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Select</th>
                                            <th>Invoice #</th>
                                            <th>Company Name</th>
                                            <th>Billing Period</th>
                                            <th>Consumption Type</th>
                                        </tr>
                                    </thead>
                                    <tbody id="invoicesTableBody">
                                        @if(isset($pendingBills) && count($pendingBills) > 0)
                                            @foreach($pendingBills as $bill)
                                                <tr>
                                                    <td>
                                                        <div class="form-check">
                                                            <input class="form-check-input invoice-checkbox"
                                                                   type="checkbox"
                                                                   name="bulk_invoices[]"
                                                                   value="{{ $bill->invoice_id ?? '' }}"
                                                                   checked>
                                                        </div>
                                                    </td>
                                                    <td>{{ $bill->invoice_id ?? 'N/A' }}</td>
                                                    <td>{{ $bill->company_name ?? 'N/A' }}</td>
                                                    <td>{{ $bill->BillingPeriod ?? 'N/A' }}</td>
                                                    <td><span class="badge badge-info">{{ $bill->ConsType ?? 'Water' }}</span></td>
                                                </tr>
                                            @endforeach
                                        @else
                                            <tr>
                                                <td colspan="5" class="text-center">No pending water bills found</td>
                                            </tr>
                                        @endif
                                    </tbody>
                                </table>
                            </div>

                            <div class="form-group row mb-4">
                                <label for="bill_date" class="col-sm-3 col-form-label">Billing Date:</label>
                                <div class="col-sm-4">
                                    <input type="date"
                                           name="bill_date"
                                           id="bill_date"
                                           class="form-control"
                                           value="{{ old('bill_date', \Carbon\Carbon::now()->format('Y-m-d')) }}"
                                           required>
                                </div>
                            </div>

                            <div class="form-group row mb-4">
                                <div class="col-sm-12">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="is_draft" id="is_draft" value="1">
                                        <label class="form-check-label" for="is_draft">
                                            Save as draft (bills will not be finalized)
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="d-flex justify-content-end gap-2">
                                <a href="{{ route('bills.water.index') }}" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> Close
                                </a>
                                <button type="submit" class="btn btn-primary" id="processButton">
                                    <i class="fas fa-cogs"></i> Process Water Bills
                                </button>
                            </div>
                        </form>
                        <div id="processingIndicator" class="d-none text-center mt-3">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Processing...</span>
                            </div>
                            <p class="mt-2">Processing water bills, please wait...</p>
                        </div>

                        @if(session('processed_count'))
                            <div class="alert alert-primary mt-3" role="alert">
                                {{ session('processed_count') }} water bills processed successfully
                            </div>
                        @endif
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .table thead th {
        background-color: #f8f9fa;
        border-bottom: 2px solid #dee2e6;
    }
    .table tbody tr:hover {
        background-color: #f8f9fa;
    }
    .card {
        border: 1px solid rgba(0,0,0,.125);
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,.075);
    }
    .card-header {
        border-bottom: 1px solid rgba(0,0,0,.125);
        border-radius: 0.5rem 0.5rem 0 0 !important;
    }
    .badge-info {
        background-color: #17a2b8;
        color: white;
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('processBillsForm');
    const processButton = document.getElementById('processButton');
    const processingIndicator = document.getElementById('processingIndicator');
    const billingPeriodSelect = document.getElementById('billing_period');
    const invoicesTableBody = document.getElementById('invoicesTableBody');

    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();

            // Check if at least one invoice is selected
            const checkboxes = document.querySelectorAll('.invoice-checkbox:checked');
            if (checkboxes.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No Selection',
                    text: 'Please select at least one water invoice to process.',
                    confirmButtonColor: '#2c3e50'
                });
                return false;
            }

            // Show processing indicator
            if (processButton) processButton.disabled = true;
            if (processingIndicator) processingIndicator.classList.remove('d-none');

            // Submit form via AJAX
            const formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                // Hide processing indicator
                if (processingIndicator) processingIndicator.classList.add('d-none');
                if (processButton) processButton.disabled = false;

                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        html: `
                            <div class="text-left">
                                <p>${data.alert.message}</p>
                                <div class="mt-3">
                                    <p class="mb-1"><strong>Billing Period:</strong> ${data.alert.details.billing_period}</p>
                                    <p class="mb-1"><strong>Processed:</strong> ${data.alert.details.total_processed} water invoice(s)</p>
                                    <p class="mb-0"><strong>Failed:</strong> ${data.alert.details.total_failed}</p>
                                </div>
                            </div>
                        `,
                        confirmButtonColor: '#2c3e50',
                        willClose: () => {
                            // Reload the page after showing success message
                            window.location.reload();
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: data.message || 'An error occurred while processing the water bills.',
                        confirmButtonColor: '#2c3e50'
                    });
                }
            })
            .catch(error => {
                console.error('Error:', error);
                if (processingIndicator) processingIndicator.classList.add('d-none');
                if (processButton) processButton.disabled = false;

                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while processing your water bill request. Please try again.',
                    confirmButtonColor: '#2c3e50'
                });
            });

            return false;
        });
    }

    // Update invoices table when billing period changes
    if (billingPeriodSelect) {
        billingPeriodSelect.addEventListener('change', function() {
            const selectedPeriod = this.value;

            // In a real app, you would fetch the invoices for the selected period via AJAX
            if (invoicesTableBody) {
                invoicesTableBody.innerHTML = `
                    <tr>
                        <td colspan="5" class="text-center">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            Loading water invoices...
                        </td>
                    </tr>`;
            }

            // Simulate loading (replace with actual AJAX call)
            setTimeout(() => {
                window.location.href = `?period=${selectedPeriod}`;
            }, 500);
        });
    }
});
</script>
@endpush
