@extends('layouts.app')

@section('title', 'Create Billing Period')

@push('styles')
<style>
    :root {
        --sulis-primary: #1E40AF;
        --sulis-primary-dark: #1E3A8A;
        --sulis-accent: #3B82F6;
        --sulis-light: #EFF6FF;
        --sulis-gray: #6B7280;
        --sulis-light-gray: #F9FAFB;
    }

    .period-card {
        border: none;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(30, 64, 175, 0.08);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
        overflow: hidden;
        border: 1px solid #E5E7EB;
    }
    
    .period-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(30, 64, 175, 0.12);
    }
    
    .card-header {
        background: linear-gradient(135deg, var(--sulis-primary) 0%, var(--sulis-primary-dark) 100%);
        border-radius: 0 !important;
        padding: 1.75rem 2rem;
        border: none;
    }
    
    .form-control, .form-select {
        border: 1px solid #D1D5DB;
        border-radius: 8px;
        padding: 0.75rem 1rem;
        transition: all 0.2s ease;
        font-size: 0.95rem;
    }
    
    .form-control:focus, .form-select:focus {
        border-color: var(--sulis-accent);
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
    }
    
    .btn-primary {
        background: linear-gradient(135deg, var(--sulis-primary) 0%, var(--sulis-primary-dark) 100%);
        border: none;
        padding: 0.7rem 1.75rem;
        font-weight: 500;
        letter-spacing: 0.3px;
        transition: all 0.2s ease;
    }
    
    .btn-primary:hover {
        background: linear-gradient(135deg, var(--sulis-primary-dark) 0%, #172554 100%);
        transform: translateY(-1px);
    }
    
    .btn-outline-secondary {
        border: 1px solid #D1D5DB;
        padding: 0.7rem 1.75rem;
        color: var(--sulis-gray);
        transition: all 0.2s ease;
    }
    
    .btn-outline-secondary:hover {
        background-color: #F3F4F6;
        border-color: #9CA3AF;
    }
    
    .form-label {
        color: #374151;
        font-weight: 600;
        margin-bottom: 0.5rem;
        font-size: 0.95rem;
    }
    
    .period-display {
        background-color: var(--sulis-light);
        border-left: 4px solid var(--sulis-primary);
        padding: 1rem 1.25rem;
        border-radius: 8px;
        color: var(--sulis-primary-dark);
    }
    
    .info-text {
        color: var(--sulis-gray);
        font-size: 0.875rem;
        line-height: 1.5;
    }
    
    .alert {
        border-radius: 8px;
        border: none;
    }
    
    .alert-success {
        background-color: #ECFDF5;
        color: #065F46;
    }
    
    .alert-danger {
        background-color: #FEF2F2;
        color: #B91C1C;
    }
</style>
@endpush

@section('content')
<div class="min-vh-100 bg-gray-50 py-8">
    <div class="container">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-5">
            <div>
                <h1 class="h3 mb-2 text-gray-800">Billing Period Management</h1>
                <p class="mb-0">Create and manage billing periods for your properties</p>
            </div>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createPeriodModal" @if(isset($needsProcessing) && $needsProcessing) disabled @endif>
                <i class="fas fa-plus-circle me-2"></i> Create New Billing Period
                @if(isset($needsProcessing) && $needsProcessing)
                    <span class="ms-2" data-bs-toggle="tooltip" title="Please process the current billing period first">
                        <i class="fas fa-info-circle"></i>
                    </span>
                @endif
            </button>
        </div>
        
        @if(isset($missingKplcInvoices) && $missingKplcInvoices)
        <div class="alert alert-warning d-flex align-items-center mb-4" role="alert">
            <i class="fas fa-file-invoice me-3 fs-4"></i>
            <div>
                <h5 class="alert-heading mb-2">KPLC Invoice Required</h5>
                <p class="mb-0">A KPLC invoice has not yet been created for the current billing period. Please create the KPLC invoice before proceeding with a new billing period.</p>
            </div>
        </div>
        @elseif(isset($needsProcessing) && $needsProcessing)
        <div class="alert alert-warning d-flex align-items-center mb-4" role="alert">
            <i class="fas fa-exclamation-triangle me-3 fs-4"></i>
            <div>
                <h5 class="alert-heading mb-2">Pending Billings Need Processing</h5>
                <p class="mb-0">You cannot create a new billing period until all meter readings for the current period have been processed. Please click the "Process Billings" button below to proceed.</p>
            </div>
        </div>
        @endif
        
        <div class="row justify-content-center">
            <div class="col-12">
                <!-- Meter Readings with Null Values -->
                @if(isset($nullReadings) && $nullReadings->count() > 0)
                <div class="period-card card shadow-sm border-0 overflow-hidden">
                    <div class="card-header border-bottom py-3">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <div class="bg-primary bg-opacity-10 p-1 rounded-circle me-2">
                                    <i class="fas fa-exclamation-triangle text-primary" style="font-size: 0.9rem;"></i>
                                </div>
                                <div>
                                    <h2 class="h6 mb-0 fw-semibold text-white">Billing Period: {{ $latestBillingPeriod ? \Carbon\Carbon::createFromFormat('Ym', $latestBillingPeriod)->format('F Y') : 'N/A' }}</h2>
                                    <p class="text-white small mb-0">Required readings to be uploaded via an app</p>
                                </div>
                            </div>
                            <span class="badge bg-danger bg-opacity-10 text-danger">{{ $totalIssues }} Issues</span>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead class="bg-light">
                                    <tr>
                                        <th class="px-4 py-3 text-uppercase text-xs font-weight-semibold text-gray-600 border-0">Customer Name</th>
                                        <th class="px-4 py-3 text-uppercase text-xs font-weight-semibold text-gray-600 border-0">Unit</th>
                                        <th class="px-4 py-3 text-uppercase text-xs font-weight-semibold text-gray-600 border-0">Billing Period</th>
                                        <th class="px-4 py-3 text-uppercase text-xs font-weight-semibold text-gray-600 border-0">Reading</th>
                                        <th class="px-4 py-3 text-uppercase text-xs font-weight-semibold text-gray-600 border-0">Previous Reading</th>
                                        <th class="px-4 py-3 text-uppercase text-xs font-weight-semibold text-gray-600 border-0">Cons.(Kwh)</th>
                                    </tr>
                                </thead>
                                <tbody class="border-top-0">
                                    @foreach($nullReadings as $reading)
                                    <tr class="border-bottom">
                                        <td class="px-4 py-3">
                                            <div class="d-flex align-items-center">
                                                <div class="bg-primary bg-opacity-10 p-2 rounded-circle me-3">
                                                    <i class="fas fa-user text-primary" style="font-size: 0.8rem;"></i>
                                                </div>
                                                <span class="fw-medium">{{ $reading->CustomerName ?? 'N/A' }}</span>
                                            </div>
                                        </td>
                                        <td class="px-4 py-3">
                                            <span class="badge bg-light text-dark">{{ $reading->UnitIdentity ?? ($reading->UnitID ?? 'N/A') }}</span>
                                        </td>
                                        <td class="px-4 py-3">
                                            <span class="text-muted">{{ $reading->BillingPeriod ? \Carbon\Carbon::createFromFormat('Ym', $reading->BillingPeriod)->format('M Y') : 'N/A' }}</span>
                                        </td>
                                        <td class="px-4 py-3">
                                            <span class="badge bg-danger bg-opacity-10 text-danger">
                                                <i class="fas fa-exclamation-circle me-1"></i>
                                                {{ $reading->Reading ?? 'Missing' }}
                                            </span>
                                        </td>
                                        <td class="px-4 py-3">
                                            <span class="text-muted">{{ $reading->PrvReading ?? 'N/A' }}</span>
                                        </td>
                                        <td class="px-4 py-3">
                                            <span class="text-muted">{{ $reading->Consumption ?? '0' }}</span>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        <div class="card-footer bg-white border-top d-flex justify-content-between align-items-center py-3">
                            <div class="text-muted small">
                                Showing <span class="fw-semibold">{{ $nullReadings->firstItem() }}</span> to <span class="fw-semibold">{{ $nullReadings->lastItem() }}</span> of <span class="fw-semibold">{{ $nullReadings->total() }}</span> entries
                            </div>
                            {{ $nullReadings->links() }}
                        </div>
                    </div>
                </div>
                @else
                <div class="text-center p-5 bg-white rounded-3 border">
                    <div class="mb-3">
                        <i class="fas fa-check-circle text-success" style="font-size: 3rem; opacity: 0.8;"></i>
                    </div>
                    <h5 class="text-muted mb-2">No Missing Readings</h5>
                    <p class="text-muted mb-4">All meter readings are up to date and valid.</p>
                    
                    @if(isset($missingKplcInvoices) && $missingKplcInvoices && $latestBillingPeriod)
                        <div class="mt-4">
                            <a href="{{ route('invoices.bulk.create', ['cons_type' => 'ENERGY']) }}" 
                               class="btn btn-primary">
                                <i class="fas fa-file-invoice me-2"></i> Create New KPLC Invoice
                            </a>
                            <p class="text-muted small mt-2">
                                Billing Period: {{ \Carbon\Carbon::createFromFormat('Ym', $latestBillingPeriod)->format('F Y') }}
                            </p>
                        </div>
                    @elseif(isset($needsProcessing) && $needsProcessing && $latestBillingPeriod)
                        <div class="mt-4">
                            <a href="{{ route('bills.utility.process', ['billing_period' => $latestBillingPeriod]) }}" class="btn btn-warning">
                                <i class="fas fa-sync-alt me-2"></i>Process Billings
                            </a>
                            <p class="text-muted small mt-2">
                                Billing Period: {{ \Carbon\Carbon::createFromFormat('Ym', $latestBillingPeriod)->format('F Y') }}
                                <br>
                                <small>Process meter readings to update billing records</small>
                            </p>
                        </div>
                    @endif
                </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Create Period Modal -->
    <div class="modal fade" id="createPeriodModal" tabindex="-1" aria-labelledby="createPeriodModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content border-0">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="createPeriodModalLabel">
                        <i class="fas fa-calendar-plus me-2"></i> Create New Billing Period
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    @if(session('success'))
                    <div class="alert alert-success d-flex align-items-center" role="alert">
                        <i class="fas fa-check-circle me-2"></i>
                        <div>{{ session('success') }}</div>
                    </div>
                    @endif
                    
                    @if($errors->any())
                    <div class="alert alert-danger" role="alert">
                        <div class="d-flex">
                            <i class="fas fa-exclamation-triangle me-3 mt-1"></i>
                            <div>
                                <h5 class="alert-heading mb-2">There was an error with your submission</h5>
                                <ul class="mb-0 ps-0">
                                    @foreach ($errors->all() as $error)
                                        <li class="mb-1">{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        </div>
                    </div>
                    @endif
                    
                    <form id="createPeriodForm" action="{{ route('periods.initPeriod') }}" method="POST">
                        @csrf
                        @method('POST')
                        
                        <!-- Current Period Selection -->
                        <div class="mb-4">
                            <label for="PrvBMonth" class="form-label">
                                Select Current Period <span class="text-danger">*</span>
                            </label>
                            <div class="input-group">
                                <select id="PrvBMonth" name="PrvBMonth" class="form-select form-select-lg">
                                    @foreach($billingPeriods as $period)
                                        <option value="{{ $period->BillingPeriod }}" {{ $period->BillingPeriod == $latestBillingPeriod ? 'selected' : '' }}>
                                            {{ \Carbon\Carbon::createFromFormat('Ym', $period->BillingPeriod)->format('F Y') }}
                                        </option>
                                    @endforeach
                                </select>
                                <span class="input-group-text bg-white">
                                    <i class="fas fa-chevron-down text-gray-400"></i>
                                </span>
                            </div>
                            <div class="form-text text-muted mt-1">
                                Select the most recent completed billing period
                            </div>
                        </div>

                        <!-- New Period Display -->
                        <div class="mb-4">
                            <label class="form-label">
                                New Billing Period
                            </label>
                            <div class="period-display mb-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="text-muted">Next Period:</span>
                                        <h4 class="mb-0 text-gray-800" id="BMonthDisplay">--</h4>
                                    </div>
                                    <div class="bg-white p-3 rounded">
                                        <i class="fas fa-calendar-alt text-primary fs-3"></i>
                                    </div>
                                </div>
                                <input type="hidden" id="BMonth" name="BMonth" value="">
                            </div>
                            <p class="info-text">
                                <i class="fas fa-info-circle me-1"></i> 
                                This will be the next billing period after the selected current period.
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div class="d-flex justify-content-end gap-3 pt-3 border-top">
                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-2"></i> Cancel
                            </button>
                            <button type="submit" class="btn btn-primary px-4">
                                <i class="fas fa-calendar-plus me-2"></i> Create Billing Period
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Initialize tooltips
    document.addEventListener('DOMContentLoaded', function() {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    });
</script>
<script>
    // Handle form submission
    $(document).ready(function() {
        const form = $('#createPeriodForm');
        const submitBtn = form.find('button[type="submit"]');
        const submitBtnText = submitBtn.html();
        
        form.on('submit', function(e) {
            e.preventDefault();
            
            // Show loading state
            submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span> Creating...');
            
            $.ajax({
                url: form.attr('action'),
                method: form.attr('method'),
                data: form.serialize(),
                success: function(response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: 'Billing period created successfully.',
                        confirmButtonColor: '#0d6efd',
                        customClass: {
                            confirmButton: 'btn btn-primary'
                        },
                        buttonsStyling: false
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.reload();
                        }
                    });
                },
                error: function(xhr) {
                    let errorMessage = 'An error occurred while creating the billing period.';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: errorMessage,
                        confirmButtonColor: '#dc3545',
                        customClass: {
                            confirmButton: 'btn btn-danger'
                        },
                        buttonsStyling: false
                    });
                },
                complete: function() {
                    submitBtn.prop('disabled', false).html(submitBtnText);
                }
            });
        });
    });

    function getNextPeriod(billingPeriod) {
        // Convert YYYYMM to date
        const year = parseInt(billingPeriod.substring(0, 4));
        const month = parseInt(billingPeriod.substring(4, 6));
        
        // Calculate next month
        let nextMonth = month + 1;
        let nextYear = year;
        
        if (nextMonth > 12) {
            nextMonth = 1;
            nextYear++;
        }
        
        // Format as YYYYMM with leading zero for month
        return nextYear.toString() + (nextMonth < 10 ? '0' + nextMonth : nextMonth.toString());
    }

    document.addEventListener('DOMContentLoaded', function() {
        const select = document.getElementById('PrvBMonth');
        const output = document.getElementById('BMonth');

        function updateNewPeriod() {
            if (!select || !output || select.selectedIndex < 0) {
                return;
            }

            const currentValue = select.value;
            if (currentValue && currentValue.length === 6) {
                const nextPeriod = getNextPeriod(currentValue);
                
                // Format for display (e.g., "December 2025")
                const year = nextPeriod.substring(0, 4);
                const month = parseInt(nextPeriod.substring(4, 6));
                const monthNames = ["January", "February", "March", "April", "May", "June",
                                  "July", "August", "September", "October", "November", "December"];
                const displayText = `${monthNames[month - 1]} ${year}`;
                
                output.value = nextPeriod;
                // Update the display text if needed (if you have a separate display field)
                const displayNode = document.getElementById('BMonthDisplay');
                if (displayNode) {
                    displayNode.textContent = displayText;
                }
            } else {
                output.value = '';
                const displayNode = document.getElementById('BMonthDisplay');
                if (displayNode) {
                    displayNode.textContent = '--';
                }
            }
        }

        // Initialize with the default selected value
        updateNewPeriod();
        
        // Update when selection changes
        if (select) {
            select.addEventListener('change', updateNewPeriod);
        }
    });
</script>
@endpush

@endsection