<?php 
$this->load->view('layouts/header');
$this->load->helper('layout');
?>

    <!-- App Header -->
    <div class="appHeader">
        <div class="left">
            <a href="<?php echo base_url('bills'); ?>" class="headerButton">
                <ion-icon name="chevron-back-outline"></ion-icon>
            </a>
        </div>
        <div class="pageTitle">Pay Electricity</div>
        <div class="right"></div>
    </div>

    <!-- App Capsule -->
    <div id="appCapsule">
        
        <?php if ($this->session->flashdata('error')): ?>
        <div class="section mt-2">
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $this->session->flashdata('error'); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
        <?php endif; ?>

        <?php if ($this->session->flashdata('success')): ?>
        <div class="section mt-2">
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $this->session->flashdata('success'); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
        <?php endif; ?>

        <!-- Provider Selection -->
        <div class="section mt-2">
            <div class="section-title">Select Provider</div>
            <div class="card">
                <div class="card-body">
                    <div class="row" id="providerSelection">
                        <?php 
                        // US Electricity Provider Colors
                        $provider_colors = [
                            'pge' => '#007934',           // PG&E - Green
                            'sce' => '#FF6B00',           // SCE - Orange
                            'duke-energy' => '#00529B',   // Duke Energy - Blue
                            'fpl' => '#0072CE',           // FPL - Light Blue
                            'dominion' => '#00263A',      // Dominion - Dark Blue
                            'coned' => '#0078D7',         // Con Edison - Blue
                            'comed' => '#E21836',         // ComEd - Red
                            'xcel' => '#00843D',          // Xcel Energy - Green
                            'georgia-power' => '#004B87', // Georgia Power - Blue
                            'aps' => '#B8860B'            // APS - Gold
                        ];
                        
                        // If no providers from DB, show default US providers
                        if (empty($providers)):
                            $default_providers = [
                                (object)['id' => 1, 'slug' => 'pge', 'name' => 'PG&E'],
                                (object)['id' => 2, 'slug' => 'sce', 'name' => 'SCE'],
                                (object)['id' => 3, 'slug' => 'duke-energy', 'name' => 'Duke Energy'],
                                (object)['id' => 4, 'slug' => 'fpl', 'name' => 'FPL'],
                                (object)['id' => 5, 'slug' => 'coned', 'name' => 'Con Edison'],
                                (object)['id' => 6, 'slug' => 'comed', 'name' => 'ComEd']
                            ];
                            $providers = $default_providers;
                        endif;
                        
                        foreach ($providers as $provider): 
                        $color = isset($provider_colors[$provider->slug]) ? $provider_colors[$provider->slug] : '#1E74FD';
                        ?>
                        <div class="col-4 mb-3">
                            <div class="provider-option text-center" data-provider="<?php echo $provider->id; ?>" onclick="selectProvider(this, '<?php echo $provider->id; ?>', '<?php echo $provider->name; ?>')">
                                <div class="rounded-circle mx-auto d-flex align-items-center justify-content-center mb-1" 
                                     style="width: 60px; height: 60px; background-color: <?php echo $color; ?>; border: 3px solid transparent; transition: all 0.2s;">
                                    <ion-icon name="flash-outline" style="font-size: 26px; color: #fff;"></ion-icon>
                                </div>
                                <span class="small text-muted"><?php echo $provider->name; ?></span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Electricity Form -->
        <form action="<?php echo base_url('bills/electricity'); ?>" method="POST" id="electricityForm">
            <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
            <input type="hidden" name="provider_id" id="selectedProvider" value="">

            <!-- Meter Type -->
            <div class="section mt-2">
                <div class="section-title">Meter Type</div>
                <div class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="meter_type" id="prepaid" value="prepaid" checked>
                                    <label class="form-check-label" for="prepaid">
                                        <strong>Prepaid</strong>
                                        <p class="text-muted small mb-0">Token will be generated</p>
                                    </label>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="meter_type" id="postpaid" value="postpaid">
                                    <label class="form-check-label" for="postpaid">
                                        <strong>Postpaid</strong>
                                        <p class="text-muted small mb-0">Pay existing bill</p>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Meter Number -->
            <div class="section mt-2">
                <div class="section-title">Meter Number</div>
                <div class="card">
                    <div class="card-body">
                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <input type="text" class="form-control" name="meter_number" id="meterNumber" 
                                       placeholder="Enter meter number" maxlength="20" required>
                                <i class="clear-input">
                                    <ion-icon name="close-circle"></ion-icon>
                                </i>
                            </div>
                        </div>
                        <div id="meterInfo" class="mt-2" style="display: none;">
                            <div class="alert alert-outline-primary mb-0">
                                <div class="d-flex align-items-center">
                                    <ion-icon name="person-outline" class="me-2" style="font-size: 20px;"></ion-icon>
                                    <div>
                                        <div id="customerName" class="fw-bold">-</div>
                                        <small class="text-muted" id="customerAddress">-</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-outline-primary btn-sm mt-2" onclick="verifyMeter()">
                            <ion-icon name="search-outline"></ion-icon> Verify Meter
                        </button>
                    </div>
                </div>
            </div>

            <!-- Amount -->
            <div class="section mt-2">
                <div class="section-title">Amount</div>
                <div class="card">
                    <div class="card-body">
                        <div class="row mb-3">
                            <?php 
                            $amounts = [1, 5, 10, 20, 50, 100];
                            foreach ($amounts as $amt): 
                            ?>
                            <div class="col-4 mb-2">
                                <button type="button" class="btn btn-outline-primary btn-block btn-sm quick-amount" 
                                        onclick="setAmount(<?php echo $amt; ?>)">
                                    $<?php echo number_format($amt); ?>
                                </button>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="form-group basic">
                            <label class="label">Or Enter Amount</label>
                            <div class="input-group mb-2">
                                <span class="input-group-text">$</span>
                                <input type="number" class="form-control" name="amount" id="electricityAmount" 
                                       placeholder="0.00" min="100" step="1" required>
                            </div>
                            <div class="input-info">Minimum: $100</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Source Account -->
            <div class="section mt-2">
                <div class="section-title">Pay From</div>
                <div class="card">
                    <div class="card-body">
                        <div class="form-group basic">
                            <select class="form-control" name="account_id" id="sourceAccount" required>
                                <option value="">Select Account</option>
                                <?php foreach ($accounts as $account): ?>
                                <option value="<?php echo $account->id; ?>" 
                                        data-balance="<?php echo $account->available_balance; ?>">
                                    <?php echo $account->account_number; ?> - <?php echo $account->account_type; ?>
                                    (<?php echo format_money($account->available_balance, $account->currency); ?>)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Save Biller Option -->
            <div class="section mt-2">
                <div class="card">
                    <div class="card-body">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="save_biller" id="saveBiller" value="1">
                            <label class="form-check-label" for="saveBiller">
                                Save this biller for quick payments
                            </label>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Submit -->
            <div class="section mt-3 mb-3">
                <?php if ($user->user_type !== 'admin'): ?>
                <button type="button" class="btn btn-primary btn-block btn-lg" id="submitBtn" onclick="initiatePayment()" disabled>
                    <ion-icon name="flash-outline"></ion-icon>
                    Pay Electricity Bill
                </button>
                <?php else: ?>
                <button type="submit" class="btn btn-primary btn-block btn-lg" id="submitBtn" disabled>
                    <ion-icon name="flash-outline"></ion-icon>
                    Pay Electricity Bill
                </button>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- OTP Verification Modal -->
    <?php if ($user->user_type !== 'admin'): ?>
    <?php $this->load->view('partials/otp_modal'); ?>
    <?php endif; ?>

    <!-- App Bottom Menu -->
    <?php echo get_bottom_menu(''); ?>

<style>
.provider-option {
    cursor: pointer;
    transition: transform 0.2s;
}
.provider-option:hover {
    transform: scale(1.05);
}
.provider-option.selected .rounded-circle {
    border-color: #1E74FD !important;
    box-shadow: 0 0 10px rgba(30, 116, 253, 0.5);
}
.quick-amount.active {
    background-color: #1E74FD;
    color: #fff;
    border-color: #1E74FD;
}
</style>

<script>
function selectProvider(element, providerId, providerName) {
    document.querySelectorAll('.provider-option').forEach(function(el) {
        el.classList.remove('selected');
    });
    element.classList.add('selected');
    document.getElementById('selectedProvider').value = providerId;
    validateForm();
}

function setAmount(amount) {
    document.getElementById('electricityAmount').value = amount;
    document.querySelectorAll('.quick-amount').forEach(function(btn) {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
    validateForm();
}

function verifyMeter() {
    var meterNumber = document.getElementById('meterNumber').value;
    var providerId = document.getElementById('selectedProvider').value;
    
    if (!meterNumber || !providerId) {
        alert('Please select a provider and enter meter number');
        return;
    }
    
    // Simulate meter verification
    document.getElementById('meterInfo').style.display = 'block';
    document.getElementById('customerName').textContent = 'Customer Name (Simulated)';
    document.getElementById('customerAddress').textContent = 'Customer Address';
}

function validateForm() {
    var provider = document.getElementById('selectedProvider').value;
    var meter = document.getElementById('meterNumber').value;
    var amount = document.getElementById('electricityAmount').value;
    var account = document.getElementById('sourceAccount').value;
    
    var valid = provider && meter.length >= 5 && amount >= 100 && account;
    document.getElementById('submitBtn').disabled = !valid;
}

document.getElementById('meterNumber').addEventListener('input', validateForm);
document.getElementById('electricityAmount').addEventListener('input', function() {
    document.querySelectorAll('.quick-amount').forEach(function(btn) {
        btn.classList.remove('active');
    });
    validateForm();
});
document.getElementById('sourceAccount').addEventListener('change', validateForm);

// Initialize OTP verification
document.addEventListener('DOMContentLoaded', function() {
    if (typeof initOtpVerification === 'function') {
        initOtpVerification('electricityForm', 'bill_payment', function() {
            document.getElementById('electricityForm').submit();
        });
    }
});

// Initiate payment with OTP verification
function initiatePayment() {
    if (typeof requestOtpVerification === 'function') {
        requestOtpVerification();
    } else {
        document.getElementById('electricityForm').submit();
    }
}

document.getElementById('electricityForm').addEventListener('submit', function(e) {
    var btn = document.getElementById('submitBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Processing...';
});
</script>

<?php $this->load->view('layouts/footer'); ?>
