<?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">Buy Airtime</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; ?>

        <!-- Network Selection -->
        <div class="section mt-2">
            <div class="section-title">Select Carrier</div>
            <div class="card">
                <div class="card-body">
                    <div class="row" id="networkSelection">
                        <?php 
                        // US Mobile Carrier Colors
                        $network_colors = [
                            'att' => '#00A8E0',        // AT&T - Light Blue
                            'verizon' => '#CD040B',    // Verizon - Red
                            'tmobile' => '#E20074',    // T-Mobile - Magenta
                            'sprint' => '#FFCE00',     // Sprint - Yellow
                            'metro' => '#6D2077',      // Metro - Purple
                            'cricket' => '#00B140',    // Cricket - Green
                            'boost' => '#F26522',      // Boost - Orange
                            'visible' => '#1B1464'     // Visible - Navy
                        ];
                        
                        // If no providers from DB, show default US carriers
                        if (empty($providers)):
                            $default_providers = [
                                (object)['id' => 1, 'slug' => 'att', 'name' => 'AT&T'],
                                (object)['id' => 2, 'slug' => 'verizon', 'name' => 'Verizon'],
                                (object)['id' => 3, 'slug' => 'tmobile', 'name' => 'T-Mobile'],
                                (object)['id' => 4, 'slug' => 'cricket', 'name' => 'Cricket']
                            ];
                            $providers = $default_providers;
                        endif;
                        
                        foreach ($providers as $provider): 
                        $color = isset($network_colors[$provider->slug]) ? $network_colors[$provider->slug] : '#1E74FD';
                        ?>
                        <div class="col-3 mb-2">
                            <div class="network-option text-center" data-network="<?php echo $provider->slug; ?>" onclick="selectNetwork(this, '<?php echo $provider->slug; ?>')">
                                <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="phone-portrait-outline" style="font-size: 24px; color: #fff;"></ion-icon>
                                </div>
                                <span class="small text-muted"><?php echo $provider->name; ?></span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Airtime Form -->
        <form action="<?php echo base_url('bills/airtime'); ?>" method="POST" id="airtimeForm">
            <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
            <input type="hidden" name="network" id="selectedNetwork" value="">

            <!-- Phone Number -->
            <div class="section mt-2">
                <div class="section-title">Phone Number</div>
                <div class="card">
                    <div class="card-body">
                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <input type="tel" class="form-control" name="phone" id="phoneNumber" 
                                       placeholder="Enter phone number" maxlength="11" required
                                       pattern="[0-9]{10,11}">
                                <i class="clear-input">
                                    <ion-icon name="close-circle"></ion-icon>
                                </i>
                            </div>
                            <div class="input-info">Enter the phone number to recharge</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Amount Selection -->
            <div class="section mt-2">
                <div class="section-title">Select Amount</div>
                <div class="card">
                    <div class="card-body">
                        <div class="row mb-3" id="quickAmounts">
                            <?php 
                            $amounts = [5, 10, 15, 20, 25, 50, 75, 100];
                            foreach ($amounts as $amt): 
                            ?>
                            <div class="col-3 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="airtimeAmount" 
                                       placeholder="0.00" min="5" step="1" required>
                            </div>
                            <div class="input-info">Minimum: $5</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>

            <!-- 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="phone-portrait-outline"></ion-icon>
                    Buy Airtime
                </button>
                <?php else: ?>
                <button type="submit" class="btn btn-primary btn-block btn-lg" id="submitBtn" disabled>
                    <ion-icon name="phone-portrait-outline"></ion-icon>
                    Buy Airtime
                </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>
.network-option {
    cursor: pointer;
    transition: transform 0.2s;
}
.network-option:hover {
    transform: scale(1.05);
}
.network-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>
var selectedNetwork = '';
var selectedAmount = 0;

function selectNetwork(element, network) {
    // Remove selection from all
    document.querySelectorAll('.network-option').forEach(function(el) {
        el.classList.remove('selected');
    });
    
    // Add selection to clicked
    element.classList.add('selected');
    selectedNetwork = network;
    document.getElementById('selectedNetwork').value = network;
    
    validateForm();
}

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

function validateForm() {
    var network = document.getElementById('selectedNetwork').value;
    var phone = document.getElementById('phoneNumber').value;
    var amount = document.getElementById('airtimeAmount').value;
    var account = document.getElementById('sourceAccount').value;
    
    var valid = network && phone.length >= 10 && amount >= 5 && account;
    document.getElementById('submitBtn').disabled = !valid;
}

// Add event listeners
document.getElementById('phoneNumber').addEventListener('input', validateForm);
document.getElementById('airtimeAmount').addEventListener('input', function() {
    // Remove active class from quick amounts if manually typing
    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('airtimeForm', 'bill_payment', function() {
            document.getElementById('airtimeForm').submit();
        });
    }
});

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

// Form submission (for admin users)
document.getElementById('airtimeForm').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'); ?>
