<?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">TV Subscription</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; ?>

        <!-- Provider Selection -->
        <div class="section mt-2">
            <div class="section-title">Select Provider</div>
            <div class="card">
                <div class="card-body py-2">
                    <div class="row" id="providerSelection">
                        <?php 
                        // US TV Provider Colors
                        $provider_colors = [
                            'directv' => '#00A3E0',       // DirecTV - Light Blue
                            'dish' => '#EC1C24',          // Dish Network - Red
                            'xfinity' => '#E31837',       // Xfinity - Red
                            'spectrum' => '#0066A4',      // Spectrum - Blue
                            'youtube-tv' => '#FF0000',    // YouTube TV - Red
                            'hulu' => '#1CE783'           // Hulu - Green
                        ];
                        
                        // If no providers from DB, show default US providers
                        if (empty($providers)):
                            $default_providers = [
                                (object)['id' => 1, 'slug' => 'directv', 'name' => 'DirecTV'],
                                (object)['id' => 2, 'slug' => 'dish', 'name' => 'Dish Network'],
                                (object)['id' => 3, 'slug' => 'xfinity', 'name' => 'Xfinity'],
                                (object)['id' => 4, 'slug' => 'spectrum', 'name' => 'Spectrum'],
                                (object)['id' => 5, 'slug' => 'youtube-tv', 'name' => 'YouTube TV'],
                                (object)['id' => 6, 'slug' => 'hulu', 'name' => 'Hulu']
                            ];
                            $providers = $default_providers;
                        endif;
                        
                        foreach ($providers as $provider): 
                        $color = isset($provider_colors[$provider->slug]) ? $provider_colors[$provider->slug] : '#1E74FD';
                        ?>
                        <div class="col-4 mb-2">
                            <div class="provider-option text-center" data-provider="<?php echo $provider->id; ?>" onclick="selectProvider(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="tv-outline" style="font-size: 24px; color: #fff;"></ion-icon>
                                </div>
                                <span class="small text-muted" style="font-size: 11px;"><?php echo $provider->name; ?></span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

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

            <!-- Account Number -->
            <div class="section mt-2">
                <div class="section-title">Account / Subscriber ID</div>
                <div class="card">
                    <div class="card-body">
                        <div class="form-group basic">
                            <div class="input-wrapper">
                                <input type="text" class="form-control" name="smartcard_number" id="smartcardNumber" 
                                       placeholder="Enter account number" maxlength="20" required>
                                <i class="clear-input">
                                    <ion-icon name="close-circle"></ion-icon>
                                </i>
                            </div>
                            <div class="input-info">Enter your account or subscriber ID</div>
                        </div>
                        <div id="customerInfo" 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="currentBouquet">Current Plan: -</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-outline-primary btn-sm mt-2" onclick="verifySmartcard()">
                            <ion-icon name="search-outline"></ion-icon> Verify Account
                        </button>
                    </div>
                </div>
            </div>

            <!-- Subscription Plans -->
            <div class="section mt-2" id="plansSection" style="display: none;">
                <div class="section-title">Select Plan</div>
                <div class="card">
                    <div class="card-body" id="plansContainer">
                        <div class="text-center text-muted py-3">
                            Select a provider to view 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>1 Month Subscription</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="tv-outline"></ion-icon>
                    Subscribe Now
                </button>
                <?php else: ?>
                <button type="submit" class="btn btn-primary btn-block btn-lg" id="submitBtn" disabled>
                    <ion-icon name="tv-outline"></ion-icon>
                    Subscribe Now
                </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);
}
.plan-option {
    cursor: pointer;
    transition: all 0.2s;
    border: 2px solid transparent;
}
.plan-option:hover {
    border-color: #1E74FD;
}
.plan-option.selected {
    border-color: #1E74FD;
    background-color: rgba(30, 116, 253, 0.1);
}
</style>

<script>
// US TV/Streaming Plans
var tvPlans = {
    'directv': [
        { id: 1, name: 'Entertainment', price: 65 },
        { id: 2, name: 'Choice', price: 85 },
        { id: 3, name: 'Ultimate', price: 105 },
        { id: 4, name: 'Premier', price: 155 }
    ],
    'dish': [
        { id: 5, name: 'America\'s Top 120', price: 65 },
        { id: 6, name: 'America\'s Top 120+', price: 75 },
        { id: 7, name: 'America\'s Top 200', price: 90 },
        { id: 8, name: 'America\'s Top 250', price: 100 }
    ],
    'xfinity': [
        { id: 9, name: 'Choice TV', price: 25 },
        { id: 10, name: 'Popular TV', price: 50 },
        { id: 11, name: 'Ultimate TV', price: 70 },
        { id: 12, name: 'Premier TV', price: 90 }
    ],
    'spectrum': [
        { id: 13, name: 'Spectrum TV Select', price: 60 },
        { id: 14, name: 'Spectrum TV Silver', price: 80 },
        { id: 15, name: 'Spectrum TV Gold', price: 100 }
    ],
    'youtube-tv': [
        { id: 16, name: 'Base Plan', price: 73 },
        { id: 17, name: '4K Plus Add-on', price: 83 },
        { id: 18, name: 'Spanish Plan', price: 35 }
    ],
    'hulu': [
        { id: 19, name: 'Hulu (With Ads)', price: 8 },
        { id: 20, name: 'Hulu (No Ads)', price: 18 },
        { id: 21, name: 'Hulu + Live TV', price: 77 },
        { id: 22, name: 'Hulu + Live TV (No Ads)', price: 90 }
    ]
};

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

function loadPlans(providerSlug) {
    var plans = tvPlans[providerSlug] || [];
    var container = document.getElementById('plansContainer');
    
    if (plans.length === 0) {
        container.innerHTML = '<div class="text-center text-muted py-3">No plans available</div>';
        return;
    }
    
    var html = '';
    plans.forEach(function(plan) {
        html += '<div class="card plan-option mb-2" onclick="selectPlan(' + plan.id + ', \'' + plan.name + '\', ' + plan.price + ')">' +
            '<div class="card-body py-2">' +
            '<div class="d-flex justify-content-between align-items-center">' +
            '<div>' +
            '<h6 class="mb-0">' + plan.name + '</h6>' +
            '</div>' +
            '<div class="text-primary fw-bold">$' + plan.price.toLocaleString() + '</div>' +
            '</div></div></div>';
    });
    
    container.innerHTML = html;
    document.getElementById('plansSection').style.display = 'block';
    document.getElementById('planSummary').style.display = 'none';
}

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

function verifySmartcard() {
    var smartcard = document.getElementById('smartcardNumber').value;
    var providerId = document.getElementById('selectedProvider').value;
    
    if (!smartcard || !providerId) {
        alert('Please select a provider and enter smart card number');
        return;
    }
    
    // Simulate verification
    document.getElementById('customerInfo').style.display = 'block';
    document.getElementById('customerName').textContent = 'Customer Name (Simulated)';
    document.getElementById('currentBouquet').textContent = 'Current: Basic Plan';
}

function validateForm() {
    var provider = document.getElementById('selectedProvider').value;
    var smartcard = document.getElementById('smartcardNumber').value;
    var product = document.getElementById('selectedProduct').value;
    var account = document.getElementById('sourceAccount').value;
    
    var valid = provider && smartcard.length >= 8 && product && account;
    document.getElementById('submitBtn').disabled = !valid;
}

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

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

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

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