<?php
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';

$adminAuth = new AdminAuth($conn);
if (!$adminAuth->isAuthenticated()) {
    header('Location: admin_login.php');
    exit;
}

// Page metadata (used by header include via router)
$page_title = 'Admin Pricing Rules';
$page_description = 'Manage pricing rules using ranges (min_size_gb - max_size_gb)';
?>

<div class="cute-card mb-8">
    <div class="flex items-center justify-between mb-6">
        <div>
            <h3 class="text-xl font-bold text-dark-primary">Admin Pricing Rules (Range-Based)</h3>
            <p class="text-dark-secondary">Set pricing using size ranges (e.g., 0.5GB - 2.99GB at GH₵3.50/GB), just like store owners</p>
        </div>
        <div class="flex space-x-2">
            <button onclick="openAddPricingRuleModal()" class="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition-colors">
                <i class="fas fa-plus mr-2"></i>Add Pricing Range
            </button>
        </div>
    </div>

    <!-- Instructions -->
    <div class="bg-blue-900 border border-blue-700 text-blue-100 rounded-lg p-4 mb-6">
        <h3 class="font-bold mb-2"><i class="fas fa-info-circle mr-2"></i>How Range-Based Pricing Works</h3>
        <ul class="list-disc list-inside space-y-1 text-sm">
            <li>Set price per GB for different data size ranges (e.g., 0.5GB - 2.99GB, 3GB - 10GB)</li>
            <li>Store owners will see these prices as reference when setting their own pricing</li>
            <li>Example: Range 0.5GB - 2.99GB at GH₵3.50/GB means 1GB = GH₵3.50, 2GB = GH₵7.00</li>
            <li>Lower price per GB = smaller packages, Higher price per GB = bulk packages</li>
        </ul>
    </div>

    <!-- Network Tabs -->
    <div class="mb-6">
        <div class="flex space-x-2 border-b border-gray-700">
            <button onclick="filterByNetwork('all')" id="tab-all" class="px-4 py-2 font-medium text-gray-300 border-b-2 border-blue-500">
                All Networks
            </button>
            <button onclick="filterByNetwork('mtn')" id="tab-mtn" class="px-4 py-2 font-medium text-gray-400 hover:text-gray-300">
                MTN
            </button>
            <button onclick="filterByNetwork('telecel')" id="tab-telecel" class="px-4 py-2 font-medium text-gray-400 hover:text-gray-300">
                Telecel
            </button>
            <button onclick="filterByNetwork('airtel_tigo')" id="tab-airtel_tigo" class="px-4 py-2 font-medium text-gray-400 hover:text-gray-300">
                AirtelTigo
            </button>
        </div>
    </div>

    <div class="overflow-x-auto">
        <table id="agentPricingTable" class="min-w-full divide-y divide-dark-primary bg-dark-secondary text-dark-primary">
            <thead>
                <tr>
                    <th class="px-4 py-2 text-left text-dark-secondary">Network</th>
                    <th class="px-4 py-2 text-left text-dark-secondary">Size Range (GB)</th>
                    <th class="px-4 py-2 text-left text-dark-secondary">Price per GB (GHS)</th>
                    <th class="px-4 py-2 text-left text-dark-secondary">Example</th>
                    <th class="px-4 py-2 text-left text-dark-secondary">Status</th>
                    <th class="px-4 py-2 text-left text-dark-secondary">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-dark-primary">
                <?php 
                $pricing_rules_query = "SELECT * FROM agent_pricing_rules WHERE role = 'agent' ORDER BY network_type, min_size_gb";
                $pricing_rules_result = mysqli_query($conn, $pricing_rules_query);
                if ($pricing_rules_result && mysqli_num_rows($pricing_rules_result) > 0):
                    while ($rule = mysqli_fetch_assoc($pricing_rules_result)): 
                        $exampleSize = ($rule['min_size_gb'] + $rule['max_size_gb']) / 2;
                        $examplePrice = $exampleSize * $rule['price_per_gb'];
                ?>
                <tr class="pricing-row" data-network="<?= htmlspecialchars($rule['network_type']) ?>">
                    <td class="px-4 py-2">
                        <span class="px-2 py-1 rounded-full text-xs font-medium
                            <?php 
                            switch($rule['network_type']) {
                                case 'mtn': echo 'bg-yellow-100 text-yellow-800'; break;
                                case 'telecel': echo 'bg-red-100 text-red-800'; break;
                                case 'airtel_tigo': echo 'bg-orange-100 text-orange-800'; break;
                                default: echo 'bg-gray-100 text-gray-800';
                            }
                            ?>">
                            <?= strtoupper($rule['network_type']) ?>
                        </span>
                    </td>
                    <td class="px-4 py-2 text-white">
                        <?= number_format($rule['min_size_gb'], 2) ?>GB - 
                        <?= number_format($rule['max_size_gb'], 2) ?>GB
                    </td>
                    <td class="px-4 py-2">
                        <span class="text-green-400 font-bold">
                            GH₵ <?= number_format($rule['price_per_gb'], 2) ?>
                        </span>
                    </td>
                    <td class="px-4 py-2 text-gray-300 text-sm">
                        <?= number_format($exampleSize, 2) ?>GB = GH₵ <?= number_format($examplePrice, 2) ?>
                    </td>
                    <td class="px-4 py-2">
                        <span class="px-3 py-1 rounded-full text-xs 
                            <?= $rule['is_active'] ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300' ?>">
                            <?= $rule['is_active'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td class="px-4 py-2">
                        <button onclick="editPricingRule(<?= $rule['id'] ?>)" class="px-3 py-1 bg-blue-100 text-blue-800 rounded-lg text-sm hover:bg-blue-200 transition-all mr-2">
                            <i class="fas fa-edit mr-1"></i>Edit
                        </button>
                        <button onclick="togglePricingRuleStatus(<?= $rule['id'] ?>, <?= $rule['is_active'] ? 'false' : 'true' ?>)" 
                                class="px-3 py-1 <?= $rule['is_active'] ? 'bg-yellow-100 text-yellow-800 hover:bg-yellow-200' : 'bg-green-100 text-green-800 hover:bg-green-200' ?> rounded-lg text-sm transition-all mr-2">
                            <i class="fas fa-<?= $rule['is_active'] ? 'pause' : 'play' ?> mr-1"></i><?= $rule['is_active'] ? 'Deactivate' : 'Activate' ?>
                        </button>
                        <button onclick="deletePricingRule(<?= $rule['id'] ?>)" class="px-3 py-1 bg-red-100 text-red-800 rounded-lg text-sm hover:bg-red-200 transition-all">
                            <i class="fas fa-trash mr-1"></i>Delete
                        </button>
                    </td>
                </tr>
                <?php endwhile; else: ?>
                <tr>
                    <td colspan="6" class="px-4 py-8 text-center text-gray-400">
                        <i class="fas fa-info-circle mr-2"></i>No pricing rules found. Add your first pricing range above.
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
// Network filtering
let currentNetworkFilter = 'all';

function filterByNetwork(network) {
    currentNetworkFilter = network;
    
    // Update tab styles
    document.querySelectorAll('[id^="tab-"]').forEach(tab => {
        tab.classList.remove('border-blue-500', 'text-gray-300');
        tab.classList.add('text-gray-400');
    });
    
    const activeTab = document.getElementById('tab-' + network);
    if (activeTab) {
        activeTab.classList.add('border-blue-500', 'text-gray-300');
        activeTab.classList.remove('text-gray-400');
    }
    
    // Filter rows
    document.querySelectorAll('.pricing-row').forEach(row => {
        if (network === 'all' || row.dataset.network === network) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

// Add Pricing Rule Modal
function openAddPricingRuleModal() {
    const existingModal = document.getElementById('addPricingRuleModal');
    if (existingModal) existingModal.remove();
    
    const modalHTML = `
        <div id="addPricingRuleModal" class="fixed inset-0 bg-black bg-opacity-50 z-50">
            <div class="flex items-center justify-center min-h-screen p-4">
                <div class="bg-dark-secondary rounded-2xl p-6 w-full max-w-md border border-dark-primary">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-xl font-bold text-dark-primary">Add Pricing Range</h3>
                        <button onclick="closeAddPricingRuleModal()" class="text-dark-secondary hover:text-dark-primary">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    <form id="addPricingRuleForm" class="space-y-4">
                        <div class="bg-blue-900 border border-blue-700 text-blue-100 p-3 rounded-lg text-sm">
                            <i class="fas fa-info-circle mr-2"></i>
                            Create a price range (e.g., 0.5GB to 2.99GB at GH₵3.50/GB)
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium mb-2 text-dark-secondary">Network</label>
                            <select id="add_network_type" class="w-full rounded-xl p-3 bg-dark-tertiary border border-dark-primary text-dark-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500" required>
                                <option value="mtn">MTN</option>
                                <option value="telecel">Telecel</option>
                                <option value="airtel_tigo">AirtelTigo</option>
                            </select>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium mb-2 text-dark-secondary">Min Size (GB)</label>
                                <input type="number" id="add_min_size_gb" step="0.01" min="0.1" required
                                       class="w-full rounded-xl p-3 bg-dark-tertiary border border-dark-primary text-dark-primary placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                                       placeholder="0.5">
                            </div>
                            <div>
                                <label class="block text-sm font-medium mb-2 text-dark-secondary">Max Size (GB)</label>
                                <input type="number" id="add_max_size_gb" step="0.01" min="0.1" required
                                       class="w-full rounded-xl p-3 bg-dark-tertiary border border-dark-primary text-dark-primary placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                                       placeholder="2.99">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium mb-2 text-dark-secondary">Price per GB (GHS)</label>
                            <input type="number" id="add_price_per_gb" step="0.01" min="0.01" required
                                   class="w-full rounded-xl p-3 bg-dark-tertiary border border-dark-primary text-dark-primary placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                                   placeholder="3.50">
                        </div>
                        
                        <div class="bg-gray-900 p-3 rounded-lg">
                            <div class="text-xs text-gray-400 mb-1">Preview:</div>
                            <div class="text-sm text-white" id="add_preview">
                                Enter values to see preview
                            </div>
                        </div>
                        
                        <div class="flex space-x-3">
                            <button type="button" onclick="closeAddPricingRuleModal()" class="flex-1 bg-gray-600 text-white py-3 rounded-xl hover:bg-gray-700 transition-colors">
                                <i class="fas fa-times mr-2"></i>Cancel
                            </button>
                            <button type="button" onclick="addPricingRule()" class="flex-1 bg-green-600 text-white py-3 rounded-xl hover:bg-green-700 transition-colors">
                                <i class="fas fa-plus mr-2"></i>Add Range
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>`;
    document.body.insertAdjacentHTML('beforeend', modalHTML);
    
    // Preview calculation
    ['add_min_size_gb', 'add_max_size_gb', 'add_price_per_gb'].forEach(id => {
        const el = document.getElementById(id);
        if (el) {
            el.addEventListener('input', updateAddPreview);
        }
    });
}

function closeAddPricingRuleModal() {
    const modal = document.getElementById('addPricingRuleModal');
    if (modal) modal.remove();
}

function updateAddPreview() {
    const minSize = parseFloat(document.getElementById('add_min_size_gb')?.value) || 0;
    const maxSize = parseFloat(document.getElementById('add_max_size_gb')?.value) || 0;
    const pricePerGb = parseFloat(document.getElementById('add_price_per_gb')?.value) || 0;
    
    const preview = document.getElementById('add_preview');
    if (!preview) return;
    
    if (minSize > 0 && maxSize > 0 && pricePerGb > 0) {
        const exampleSize = (minSize + maxSize) / 2;
        const examplePrice = exampleSize * pricePerGb;
        preview.innerHTML = 
            `Range: ${minSize}GB - ${maxSize}GB<br>` +
            `Example: ${exampleSize.toFixed(2)}GB = GH₵${examplePrice.toFixed(2)}`;
    } else {
        preview.textContent = 'Enter values to see preview';
    }
}

function addPricingRule() {
    const formData = new FormData();
    formData.append('role', 'agent');
    formData.append('network_type', document.getElementById('add_network_type').value);
    formData.append('min_size_gb', document.getElementById('add_min_size_gb').value);
    formData.append('max_size_gb', document.getElementById('add_max_size_gb').value);
    formData.append('price_per_gb', document.getElementById('add_price_per_gb').value);
    formData.append('is_active', '1');
    
    fetch('pages/add_pricing_rule.php', {
        method: 'POST',
        body: formData
    })
    .then(async response => {
        const text = await response.text();
        try {
            return JSON.parse(text);
        } catch (e) {
            console.error('Response was not JSON:', text);
            throw new Error('Server returned invalid response: ' + text.substring(0, 100));
        }
    })
    .then(data => {
        if (data.success) {
            showMessage(data.message, 'success');
            closeAddPricingRuleModal();
            setTimeout(() => location.reload(), 1000);
        } else {
            showMessage(data.message || 'Failed to add pricing rule', 'error');
        }
    })
    .catch(error => {
        console.error('Error adding pricing rule:', error);
        showMessage('Error adding pricing rule: ' + error.message, 'error');
    });
}

// Edit Pricing Rule
function editPricingRule(id) {
    fetch('pages/get_pricing_rule_details.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'id=' + id
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            openEditPricingRuleModal(data.pricing_rule);
        } else {
            showMessage('Failed to fetch pricing rule details', 'error');
        }
    })
    .catch(error => {
        console.error('Error fetching pricing rule details:', error);
        showMessage('Error fetching pricing rule details', 'error');
    });
}

function openEditPricingRuleModal(rule) {
    const existingModal = document.getElementById('editPricingRuleModal');
    if (existingModal) existingModal.remove();
    
    const modalHTML = `
        <div id="editPricingRuleModal" class="fixed inset-0 bg-black bg-opacity-50 z-50">
            <div class="flex items-center justify-center min-h-screen p-4">
                <div class="bg-dark-secondary rounded-2xl p-6 w-full max-w-md border border-dark-primary">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-xl font-bold text-dark-primary">Edit Pricing Range</h3>
                        <button onclick="closeEditPricingRuleModal()" class="text-dark-secondary hover:text-dark-primary">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    <form id="editPricingRuleForm" class="space-y-4">
                        <input type="hidden" id="edit_pricing_rule_id" value="${rule.id}">
                        
                        <div>
                            <label class="block text-sm font-medium mb-2 text-dark-secondary">Network</label>
                            <select id="edit_network_type" class="w-full rounded-xl p-3 bg-dark-tertiary border border-dark-primary text-dark-primary focus:border-blue-500 focus:ring-1 focus:ring-blue-500" required>
                                <option value="mtn" ${rule.network_type === 'mtn' ? 'selected' : ''}>MTN</option>
                                <option value="telecel" ${rule.network_type === 'telecel' ? 'selected' : ''}>Telecel</option>
                                <option value="airtel_tigo" ${rule.network_type === 'airtel_tigo' ? 'selected' : ''}>AirtelTigo</option>
                            </select>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium mb-2 text-dark-secondary">Min Size (GB)</label>
                                <input type="number" id="edit_min_size_gb" step="0.01" min="0.1" value="${rule.min_size_gb}" required
                                       class="w-full rounded-xl p-3 bg-dark-tertiary border border-dark-primary text-dark-primary placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium mb-2 text-dark-secondary">Max Size (GB)</label>
                                <input type="number" id="edit_max_size_gb" step="0.01" min="0.1" value="${rule.max_size_gb}" required
                                       class="w-full rounded-xl p-3 bg-dark-tertiary border border-dark-primary text-dark-primary placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium mb-2 text-dark-secondary">Price per GB (GHS)</label>
                            <input type="number" id="edit_price_per_gb" step="0.01" min="0.01" value="${rule.price_per_gb}" required
                                   class="w-full rounded-xl p-3 bg-dark-tertiary border border-dark-primary text-dark-primary placeholder-gray-400 focus:border-blue-500 focus:ring-1 focus:ring-blue-500">
                        </div>
                        
                        <div>
                            <label class="flex items-center">
                                <input type="checkbox" id="edit_is_active" ${rule.is_active == 1 ? 'checked' : ''} 
                                       class="mr-2 rounded">
                                <span class="text-dark-secondary">Active</span>
                            </label>
                        </div>
                        
                        <div class="flex space-x-3">
                            <button type="button" onclick="closeEditPricingRuleModal()" class="flex-1 bg-gray-600 text-white py-3 rounded-xl hover:bg-gray-700 transition-colors">
                                <i class="fas fa-times mr-2"></i>Cancel
                            </button>
                            <button type="button" onclick="updatePricingRule()" class="flex-1 bg-blue-600 text-white py-3 rounded-xl hover:bg-blue-700 transition-colors">
                                <i class="fas fa-save mr-2"></i>Save Changes
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>`;
    document.body.insertAdjacentHTML('beforeend', modalHTML);
}

function closeEditPricingRuleModal() {
    const modal = document.getElementById('editPricingRuleModal');
    if (modal) modal.remove();
}

function updatePricingRule() {
    const formData = new FormData();
    formData.append('id', document.getElementById('edit_pricing_rule_id').value);
    formData.append('role', 'agent');
    formData.append('network_type', document.getElementById('edit_network_type').value);
    formData.append('min_size_gb', document.getElementById('edit_min_size_gb').value);
    formData.append('max_size_gb', document.getElementById('edit_max_size_gb').value);
    formData.append('price_per_gb', document.getElementById('edit_price_per_gb').value);
    formData.append('is_active', document.getElementById('edit_is_active').checked ? '1' : '0');
    
    fetch('pages/update_pricing_rule.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showMessage(data.message, 'success');
            closeEditPricingRuleModal();
            setTimeout(() => location.reload(), 1000);
        } else {
            showMessage(data.message || 'Failed to update pricing rule', 'error');
        }
    })
    .catch(error => {
        console.error('Error updating pricing rule:', error);
        showMessage('Error updating pricing rule', 'error');
    });
}

function togglePricingRuleStatus(id, newStatus) {
    if (confirm('Are you sure you want to ' + (newStatus === 'true' ? 'activate' : 'deactivate') + ' this pricing rule?')) {
        fetch('pages/update_pricing_rule_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: id, is_active: newStatus })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                showMessage(data.message, 'success');
                setTimeout(() => location.reload(), 1000);
            } else {
                showMessage(data.message, 'error');
            }
        })
        .catch(error => {
            showMessage('Error updating pricing rule status', 'error');
        });
    }
}

function deletePricingRule(id) {
    if (!confirm('Are you sure you want to delete this pricing rule? This action cannot be undone.')) return;
    
    const formData = new FormData();
    formData.append('id', id);
    
    fetch('pages/delete_pricing_rule.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showMessage(data.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showMessage(data.message || 'Failed to delete pricing rule', 'error');
        }
    })
    .catch(error => {
        console.error('Error deleting pricing rule:', error);
        showMessage('Error deleting pricing rule', 'error');
    });
}

// Message display function
function showMessage(message, type) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-md w-full mx-4`;
    messageDiv.innerHTML = `
        <div class="bg-${type === 'success' ? 'green' : 'red'}-50 border border-${type === 'success' ? 'green' : 'red'}-200 text-${type === 'success' ? 'green' : 'red'}-700 px-4 py-3 rounded-xl shadow-lg flex items-center">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-3"></i>
            <span>${message}</span>
        </div>
    `;
    
    document.body.appendChild(messageDiv);
    
    // Auto-hide after 5 seconds
    setTimeout(() => {
        messageDiv.style.opacity = '0';
        messageDiv.style.transform = 'translate(-50%, -100%)';
        setTimeout(() => messageDiv.remove(), 300);
    }, 5000);
}
</script>
