<?php
// External API Pricing Management Page (Range-Based)
require_once '../config.php';
require_once '../app/classes/ExternalAPIPricingManager.php';

$page_title = 'External API Pricing';
$page_description = 'Manage pricing from external API using ranges (MTN only)';

$success_message = '';
$error_message = '';

use App\classes\ExternalAPIPricingManager;

$pricingManager = new ExternalAPIPricingManager($conn);

// Get all pricing
$externalPricing = $pricingManager->getAllExternalPricing('mtn');
$adminPricing = $pricingManager->getAllAdminPricing('mtn'); // Fetched from agent_pricing_rules
?>

<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">External API Pricing (Range-Based)</h3>
            <p class="text-dark-secondary">Set external API pricing ranges. Admin pricing is fetched from Agent Pricing Rules.</p>
        </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><strong>External API prices</strong> are what the other website charges you (set here)</li>
            <li><strong>Admin prices</strong> are fetched from Agent Pricing Rules (same as admin pricing for agents)</li>
            <li>Profit = Admin Price - External API Price</li>
            <li>Example: Range 0.5GB - 2.99GB at GH₵3.50/GB means 1GB = GH₵3.50, 2GB = GH₵7.00</li>
        </ul>
    </div>

    <!-- Two Column Layout: External API Pricing and Admin Pricing (Read-Only) -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <!-- External API Pricing Section -->
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <div class="flex items-center justify-between mb-4">
                <h4 class="text-lg font-bold text-white">
                    <i class="fas fa-download mr-2 text-blue-400"></i>External API Pricing
                </h4>
                <button onclick="openAddExternalPricingModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm">
                    <i class="fas fa-plus mr-2"></i>Add Range
                </button>
            </div>
            <p class="text-gray-400 text-sm mb-4">Prices as provided by the external API website</p>
            
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-gray-700">
                            <th class="text-left py-2 px-3 text-gray-300">Size Range</th>
                            <th class="text-right py-2 px-3 text-gray-300">Price/GB</th>
                            <th class="text-left py-2 px-3 text-gray-300">Status</th>
                            <th class="text-left py-2 px-3 text-gray-300">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($externalPricing)): ?>
                        <tr>
                            <td colspan="4" class="text-center py-4 text-gray-400">No external API pricing ranges set</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($externalPricing as $price): 
                            $exampleSize = ($price['min_size_gb'] + $price['max_size_gb']) / 2;
                            $examplePrice = $exampleSize * $price['price_per_gb'];
                        ?>
                        <tr class="border-b border-gray-700/50 hover:bg-gray-700/30">
                            <td class="py-2 px-3 text-white">
                                <?= number_format($price['min_size_gb'], 2) ?>GB - 
                                <?= number_format($price['max_size_gb'], 2) ?>GB
                            </td>
                            <td class="py-2 px-3 text-right text-blue-400 font-semibold">
                                GH₵ <?= number_format($price['price_per_gb'], 2) ?>/GB
                                <div class="text-xs text-gray-400 mt-1">
                                    (<?= number_format($exampleSize, 2) ?>GB = GH₵ <?= number_format($examplePrice, 2) ?>)
                                </div>
                            </td>
                            <td class="py-2 px-3">
                                <span class="px-2 py-1 rounded text-xs <?= $price['is_active'] ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300' ?>">
                                    <?= $price['is_active'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>
                            <td class="py-2 px-3">
                                <button onclick="editExternalPricing(<?= htmlspecialchars(json_encode($price)) ?>)" 
                                        class="text-blue-400 hover:text-blue-300 mr-2" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="deleteExternalPricing(<?= $price['id'] ?>)" 
                                        class="text-red-400 hover:text-red-300" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Admin Pricing Section (Read-Only from Agent Pricing Rules) -->
        <div class="bg-gray-800 border border-gray-700 rounded-lg p-6">
            <div class="flex items-center justify-between mb-4">
                <h4 class="text-lg font-bold text-white">
                    <i class="fas fa-tag mr-2 text-green-400"></i>Admin Pricing (Read-Only)
                </h4>
                <a href="index.php?page=pricing" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-colors text-sm">
                    <i class="fas fa-edit mr-2"></i>Edit in Pricing
                </a>
            </div>
            <p class="text-gray-400 text-sm mb-4">Fetched from Agent Pricing Rules. Click "Edit in Pricing" to modify.</p>
            
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead>
                        <tr class="border-b border-gray-700">
                            <th class="text-left py-2 px-3 text-gray-300">Size Range</th>
                            <th class="text-right py-2 px-3 text-gray-300">Price/GB</th>
                            <th class="text-left py-2 px-3 text-gray-300">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($adminPricing)): ?>
                        <tr>
                            <td colspan="3" class="text-center py-4 text-gray-400">
                                No admin pricing ranges found. 
                                <a href="index.php?page=pricing" class="text-blue-400 hover:underline">Add pricing rules here</a>
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($adminPricing as $price): 
                            $exampleSize = ($price['min_size_gb'] + $price['max_size_gb']) / 2;
                            $examplePrice = $exampleSize * $price['admin_price_per_gb'];
                        ?>
                        <tr class="border-b border-gray-700/50 hover:bg-gray-700/30">
                            <td class="py-2 px-3 text-white">
                                <?= number_format($price['min_size_gb'], 2) ?>GB - 
                                <?= number_format($price['max_size_gb'], 2) ?>GB
                            </td>
                            <td class="py-2 px-3 text-right text-green-400 font-semibold">
                                GH₵ <?= number_format($price['admin_price_per_gb'], 2) ?>/GB
                                <div class="text-xs text-gray-400 mt-1">
                                    (<?= number_format($exampleSize, 2) ?>GB = GH₵ <?= number_format($examplePrice, 2) ?>)
                                </div>
                            </td>
                            <td class="py-2 px-3">
                                <span class="px-2 py-1 rounded text-xs <?= $price['is_active'] ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300' ?>">
                                    <?= $price['is_active'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Profit Preview -->
    <?php if (!empty($externalPricing) && !empty($adminPricing)): ?>
    <div class="bg-gray-800 border border-gray-700 rounded-lg p-6 mt-6">
        <h4 class="text-lg font-bold text-white mb-4">
            <i class="fas fa-chart-line mr-2 text-purple-400"></i>Profit Preview
        </h4>
        <div class="overflow-x-auto">
            <table class="w-full text-sm">
                <thead>
                    <tr class="border-b border-gray-700">
                        <th class="text-left py-2 px-3 text-gray-300">Size Range</th>
                        <th class="text-right py-2 px-3 text-gray-300">External Price/GB</th>
                        <th class="text-right py-2 px-3 text-gray-300">Admin Price/GB</th>
                        <th class="text-right py-2 px-3 text-gray-300">Profit/GB</th>
                        <th class="text-right py-2 px-3 text-gray-300">Example (1GB)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    // Match ranges and calculate profit
                    foreach ($externalPricing as $extPrice): 
                        $matchingAdmin = null;
                        foreach ($adminPricing as $adminPrice) {
                            // Check if ranges overlap
                            if ($extPrice['min_size_gb'] <= $adminPrice['max_size_gb'] && 
                                $extPrice['max_size_gb'] >= $adminPrice['min_size_gb']) {
                                $matchingAdmin = $adminPrice;
                                break;
                            }
                        }
                        if ($matchingAdmin):
                            $profitPerGb = $matchingAdmin['admin_price_per_gb'] - $extPrice['price_per_gb'];
                            $exampleProfit = 1 * $profitPerGb; // For 1GB example
                    ?>
                    <tr class="border-b border-gray-700/50 hover:bg-gray-700/30">
                        <td class="py-2 px-3 text-white">
                            <?= number_format($extPrice['min_size_gb'], 2) ?>GB - 
                            <?= number_format($extPrice['max_size_gb'], 2) ?>GB
                        </td>
                        <td class="py-2 px-3 text-right text-red-400">GH₵ <?= number_format($extPrice['price_per_gb'], 2) ?></td>
                        <td class="py-2 px-3 text-right text-green-400">GH₵ <?= number_format($matchingAdmin['admin_price_per_gb'], 2) ?></td>
                        <td class="py-2 px-3 text-right font-bold <?= $profitPerGb >= 0 ? 'text-green-400' : 'text-red-400' ?>">
                            GH₵ <?= number_format($profitPerGb, 2) ?>
                        </td>
                        <td class="py-2 px-3 text-right <?= $exampleProfit >= 0 ? 'text-green-400' : 'text-red-400' ?>">
                            GH₵ <?= number_format($exampleProfit, 2) ?>
                        </td>
                    </tr>
                    <?php endif; endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Add External Pricing Modal -->
<div id="addExternalPricingModal" class="hidden 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-gray-800 rounded-lg p-6 w-full max-w-md border border-gray-700">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-white">Add External API Pricing Range</h3>
                <button onclick="closeAddExternalPricingModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <form id="addExternalPricingForm" class="space-y-4">
                <input type="hidden" name="pricing_type" value="external">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Min Size (GB)</label>
                    <input type="number" name="min_size_gb" step="0.01" min="0.1" required
                           class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Max Size (GB)</label>
                    <input type="number" name="max_size_gb" step="0.01" min="0.1" required
                           class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Price per GB (GHS)</label>
                    <input type="number" name="price_per_gb" step="0.01" min="0" required
                           class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                </div>
                <div class="flex items-center">
                    <input type="checkbox" name="is_active" id="add_external_active" value="1" checked
                           class="mr-2">
                    <label for="add_external_active" class="text-gray-300">Active</label>
                </div>
                <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg font-medium">
                    Add Range
                </button>
            </form>
        </div>
    </div>
</div>

<!-- Edit External Pricing Modal -->
<div id="editPricingModal" class="hidden 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-gray-800 rounded-lg p-6 w-full max-w-md border border-gray-700">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold text-white">Edit External API Pricing Range</h3>
                <button onclick="closeEditPricingModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <form id="editPricingForm" class="space-y-4">
                <input type="hidden" id="edit_id" name="id">
                <input type="hidden" id="edit_pricing_type" name="pricing_type" value="external">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Min Size (GB)</label>
                    <input type="number" id="edit_min_size_gb" name="min_size_gb" step="0.01" min="0.1" required
                           class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Max Size (GB)</label>
                    <input type="number" id="edit_max_size_gb" name="max_size_gb" step="0.01" min="0.1" required
                           class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Price per GB (GHS)</label>
                    <input type="number" id="edit_price_per_gb" name="price_per_gb" step="0.01" min="0" required
                           class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-4 py-2">
                </div>
                <div class="flex items-center">
                    <input type="checkbox" id="edit_is_active" name="is_active" value="1" class="mr-2">
                    <label for="edit_is_active" class="text-gray-300">Active</label>
                </div>
                <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2 rounded-lg font-medium">
                    Update Range
                </button>
            </form>
        </div>
    </div>
</div>

<script>
// Modal functions
function openAddExternalPricingModal() {
    document.getElementById('addExternalPricingModal').classList.remove('hidden');
}

function closeAddExternalPricingModal() {
    document.getElementById('addExternalPricingModal').classList.add('hidden');
    document.getElementById('addExternalPricingForm').reset();
}

function closeEditPricingModal() {
    document.getElementById('editPricingModal').classList.add('hidden');
    document.getElementById('editPricingForm').reset();
}

// Edit function
function editExternalPricing(price) {
    document.getElementById('edit_id').value = price.id;
    document.getElementById('edit_pricing_type').value = 'external';
    document.getElementById('edit_min_size_gb').value = price.min_size_gb;
    document.getElementById('edit_max_size_gb').value = price.max_size_gb;
    document.getElementById('edit_price_per_gb').value = price.price_per_gb;
    document.getElementById('edit_is_active').checked = price.is_active == 1;
    document.getElementById('editPricingModal').classList.remove('hidden');
}

// Delete function
function deleteExternalPricing(id) {
    if (!confirm('Are you sure you want to delete this external API pricing range?')) return;
    
    const formData = new FormData();
    formData.append('id', id);
    formData.append('pricing_type', 'external');
    
    fetch('pages/delete_external_api_pricing_range.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred');
    });
}

// Form submissions
document.getElementById('addExternalPricingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    formData.append('network_type', 'mtn');
    
    // Ensure checkbox value is properly set
    const isActiveCheckbox = document.getElementById('add_external_active');
    if (isActiveCheckbox.checked) {
        formData.set('is_active', '1');
    } else {
        // Remove if unchecked (or set to 0)
        formData.delete('is_active');
        formData.append('is_active', '0');
    }
    
    fetch('pages/add_external_api_pricing_range.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred');
    });
});

document.getElementById('editPricingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    formData.append('network_type', 'mtn');
    
    // Ensure checkbox value is properly set
    const isActiveCheckbox = document.getElementById('edit_is_active');
    if (isActiveCheckbox.checked) {
        formData.set('is_active', '1');
    } else {
        // Remove if unchecked (or set to 0)
        formData.delete('is_active');
        formData.append('is_active', '0');
    }
    
    fetch('pages/update_external_api_pricing_range.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred');
    });
});
</script>
