<?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 Data</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; ?>

        <!-- Carrier Selection -->
        <div class="section mt-2">
            <div class="section-title">Select Carrier</div>
            <div class="card">
                <div class="card-body py-2">
                    <div class="row" id="networkSelection">
                        <?php 
                        // US Mobile Carrier Colors
                        $network_colors = [
                            'att-data' => '#00A8E0',        // AT&T - Light Blue
                            'verizon-data' => '#CD040B',    // Verizon - Red
                            'tmobile-data' => '#E20074',    // T-Mobile - Magenta
                            'cricket-data' => '#00B140'     // Cricket - Green
                        ];
                        
                        // If no providers from DB, show default US carriers
                        if (empty($providers)):
                            $default_providers = [
                                (object)['id' => 1, 'slug' => 'att-data', 'name' => 'AT&T Data'],
                                (object)['id' => 2, 'slug' => 'verizon-data', 'name' => 'Verizon Data'],
                                (object)['id' => 3, 'slug' => 'tmobile-data', 'name' => 'T-Mobile Data'],
                                (object)['id' => 4, 'slug' => 'cricket-data', 'name' => 'Cricket Data']
                            ];
                            $providers = $default_providers;
                        endif;
                        
                        foreach ($providers as $provider): 
                        $color = isset($network_colors[$provider->slug]) ? $network_colors[$provider->slug] : '#1E74FD';
                        $display_name = str_replace(' Data', '', $provider->name);
                        ?>
                        <div class="col-3 mb-2">
                            <div class="network-option text-center" data-network="<?php echo $provider->id; ?>" data-slug="<?php echo $provider->slug; ?>" onclick="selectNetwork(this, '<?php echo $provider->id; ?>', '<?php echo $provider->slug; ?>')">
                                <div class="rounded-circle mx-auto d-flex align-items-center justify-content-center mb-1" 
                                     style="width: 56px; height: 56px; background-color: <?php echo $color; ?>; border: 3px solid transparent; transition: all 0.2s;">
                                    <ion-icon name="wifi-outline" style="font-size: 24px; color: #fff;"></ion-icon>
                                </div>
                                <span class="small text-muted" style="font-size: 11px;"><?php echo $display_name; ?></span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Data Form -->
        <form action="<?php echo base_url('bills/data'); ?>" method="POST" id="dataForm">
            <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="selectedNetwork" value="">
            <input type="hidden" name="product_id" id="selectedProduct" value="">
            <input type="hidden" name="amount" id="selectedAmount" value="">
            <input type="hidden" name="plan_name" id="planNameInput" 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>

            <!-- Data Plans -->
            <div class="section mt-2" id="dataPlansSection" style="display: none;">
                <div class="section-title">Select Data Plan</div>
                <div class="card">
                    <div class="card-body" id="dataPlansContainer">
                        <div class="text-center text-muted py-3">
                            Select a network to view data plans
                        </div>
                    </div>
                </div>
            </div>

            <!-- Selected Plan Summary -->
            <div class="section mt-2" id="planSummary" style="display: none;">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4 class="mb-0" id="selectedPlanName">-</h4>
                                <small id="selectedPlanValidity">-</small>
                            </div>
                            <div class="text-end">
                                <h3 class="mb-0" id="selectedPlanPrice">$0</h3>
                            </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="wifi-outline"></ion-icon>
                    Buy Data
                </button>
                <?php else: ?>
                <button type="submit" class="btn btn-primary btn-block btn-lg" id="submitBtn" disabled>
                    <ion-icon name="wifi-outline"></ion-icon>
                    Buy Data
                </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);
}
.data-plan {
    cursor: pointer;
    transition: all 0.2s;
    border: 2px solid transparent;
}
.data-plan:hover {
    border-color: #1E74FD;
}
.data-plan.selected {
    border-color: #1E74FD;
    background-color: rgba(30, 116, 253, 0.1);
}
</style>

<script>
// US Carrier Data Plans
var dataPlans = {
    'att-data': [
        { id: 1, name: '1GB', validity: '30 Days', price: 5 },
        { id: 2, name: '4GB', validity: '30 Days', price: 15 },
        { id: 3, name: '8GB', validity: '30 Days', price: 25 },
        { id: 4, name: '15GB', validity: '30 Days', price: 40 },
        { id: 5, name: 'Unlimited', validity: '30 Days', price: 30 },
        { id: 6, name: 'Unlimited+', validity: '30 Days', price: 40 }
    ],
    'verizon-data': [
        { id: 7, name: '2GB', validity: '30 Days', price: 8 },
        { id: 8, name: '5GB', validity: '30 Days', price: 16.5 },
        { id: 9, name: '10GB', validity: '30 Days', price: 24 },
        { id: 10, name: 'Unlimited', validity: '30 Days', price: 32 },
        { id: 11, name: 'Unlimited+', validity: '30 Days', price: 38 }
    ],
    'tmobile-data': [
        { id: 12, name: '2GB', validity: '30 Days', price: 8 },
        { id: 13, name: '6GB', validity: '30 Days', price: 16.5 },
        { id: 14, name: '10GB', validity: '30 Days', price: 24 },
        { id: 15, name: 'Unlimited', validity: '30 Days', price: 32 },
        { id: 16, name: 'Magenta', validity: '30 Days', price: 38 }
    ],
    'cricket-data': [
        { id: 18, name: '2GB', validity: '30 Days', price: 8 },
        { id: 19, name: '5GB', validity: '30 Days', price: 16.5 },
        { id: 20, name: '10GB', validity: '30 Days', price: 24 },
        { id: 21, name: 'Unlimited', validity: '30 Days', price: 32 }
    ]
};

function selectNetwork(element, providerId, providerSlug) {
    document.querySelectorAll('.network-option').forEach(function(el) {
        el.classList.remove('selected');
    });
    element.classList.add('selected');
    document.getElementById('selectedNetwork').value = providerId;
    
    // Load data plans using the slug
    loadDataPlans(providerSlug || providerId);
    validateForm();
}

function loadDataPlans(providerSlug) {
    var plans = dataPlans[providerSlug] || [];
    var container = document.getElementById('dataPlansContainer');
    
    if (plans.length === 0) {
        container.innerHTML = '<div class="text-center text-muted py-3">No plans available</div>';
        return;
    }
    
    var html = '<div class="row">';
    plans.forEach(function(plan) {
        html += '<div class="col-6 mb-2">' +
            '<div class="card data-plan" onclick="selectPlan(' + plan.id + ', \'' + plan.name + '\', \'' + plan.validity + '\', ' + plan.price + ')">' +
            '<div class="card-body text-center py-2">' +
            '<h5 class="mb-0">' + plan.name + '</h5>' +
            '<small class="text-muted">' + plan.validity + '</small>' +
            '<div class="text-primary fw-bold">$' + plan.price.toLocaleString() + '</div>' +
            '</div></div></div>';
    });
    html += '</div>';
    
    container.innerHTML = html;
    document.getElementById('dataPlansSection').style.display = 'block';
    document.getElementById('planSummary').style.display = 'none';
}

function selectPlan(planId, name, validity, price) {
    document.querySelectorAll('.data-plan').forEach(function(el) {
        el.classList.remove('selected');
    });
    event.currentTarget.classList.add('selected');
    
    document.getElementById('selectedProduct').value = planId;
    document.getElementById('selectedAmount').value = price;
    document.getElementById('planNameInput').value = name;
    document.getElementById('selectedPlanName').textContent = name;
    document.getElementById('selectedPlanValidity').textContent = validity;
    document.getElementById('selectedPlanPrice').textContent = '$' + price.toLocaleString();
    document.getElementById('planSummary').style.display = 'block';
    
    validateForm();
}

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

document.getElementById('phoneNumber').addEventListener('input', validateForm);
document.getElementById('sourceAccount').addEventListener('change', validateForm);

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

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

document.getElementById('dataForm').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'); ?>
