<?php
/**
 * Store Pricing Management - For Store Owners to set their own prices
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/StorePricingManager.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit();
}

$userId = $_SESSION['user_id'];

// Load store
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreByOwnerId($userId);

if (!$store) {
    header("Location: store_dashboard.php");
    exit();
}

// Load pricing
$pricingManager = new StorePricingManager($conn);
$mtnPricing = $pricingManager->getStorePricing($store['id'], 'mtn');

// Load admin pricing rules (these are the ranges store owners must use)
$adminPricingRules = [];
$adminRulesStmt = $conn->prepare("SELECT id, min_size_gb, max_size_gb, price_per_gb FROM agent_pricing_rules WHERE network_type = 'mtn' AND role = 'agent' AND is_active = 1 ORDER BY min_size_gb");
if ($adminRulesStmt) {
    $adminRulesStmt->execute();
    $adminRulesResult = $adminRulesStmt->get_result();
    while ($row = $adminRulesResult->fetch_assoc()) {
        $adminPricingRules[] = $row;
    }
    $adminRulesStmt->close();
}

// Create a map of store pricing by range (for quick lookup)
// Use formatted keys to avoid floating-point precision issues
$storePricingMap = [];
foreach ($mtnPricing as $pricing) {
    // Format to 4 decimal places to ensure consistent matching with admin ranges
    $key = sprintf('%.4f-%.4f', floatval($pricing['min_size_gb']), floatval($pricing['max_size_gb']));
    $storePricingMap[$key] = $pricing;
}

// Include reusable navigation
require_once 'includes/store_nav.php';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>Store Pricing - <?php echo htmlspecialchars($store['store_name']); ?></title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
        }
    </style>
</head>

<body class="bg-gray-900">
    <?php renderStoreNav($store, 'pricing'); ?>
    
    <!-- Back to Dashboard Button (Mobile) -->
    <div class="md:hidden bg-gray-800 border-b border-gray-700 px-3 py-2">
        <a href="store_dashboard.php" class="inline-flex items-center gap-2 text-blue-400 hover:text-blue-300 text-sm font-medium btn-touch">
            <i class="fas fa-arrow-left"></i>
            <span>Back to Dashboard</span>
        </a>
    </div>

    <div class="container mx-auto px-4 py-8">
        <!-- Store Identification Banner -->
        <div class="bg-gradient-to-r from-blue-900 to-purple-900 border border-blue-700 rounded-lg p-6 mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-white mb-2">
                        <i class="fas fa-store mr-2"></i>
                        <?php echo htmlspecialchars($store['store_name']); ?> - Pricing Control
                    </h2>
                    <p class="text-blue-200">
                        <i class="fas fa-shield-alt mr-2"></i>
                        These prices are <strong>ONLY for YOUR store</strong>. 
                    </p>
                </div>
                <div class="text-right">
                    <div class="text-sm text-blue-300">Store ID</div>
                    <div class="text-3xl font-bold">#<?php echo $store['id']; ?></div>
                </div>
            </div>
        </div>
      

        <!-- Instructions -->
        <div class="bg-blue-900 border border-blue-700 text-blue-100 rounded-lg p-4 mb-8">
            <h3 class="font-bold mb-2"><i class="fas fa-info-circle mr-2"></i>Agent Pricing (Range-Based)</h3>
            <ul class="list-disc list-inside space-y-1 text-sm">
                <li><strong>This is for SUB-AGENTS</strong> who place orders through the dashboard/API</li>
                <li><strong>Different from Customer Pricing:</strong> Agents use range-based pricing, customers use package-specific pricing</li>
                <li><strong>You must use the same package ranges as set by admin</strong> - You can only change the prices</li>
                <li>Set your price per GB for each range shown below</li>
                <li><strong class="text-red-300">Warning:</strong> Setting prices below admin base pricing will result in losses</li>
                <li>Example: 1GB at GH₵3.50/GB = Agent pays GH₵3.50</li>
                <li><strong>For Customer Pricing:</strong> Go to <a href="store_customer_pricing.php" class="text-blue-300 underline">Customer Pricing</a> page</li>
                <li><strong>Network:</strong> MTN only</li>
            </ul>
        </div>

        <!-- MTN Pricing -->
        <div class="bg-gray-800 rounded-lg p-6 mb-8 border border-gray-700">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h2 class="text-2xl font-bold text-white">
                        <i class="fas fa-mobile-alt mr-2 text-yellow-400"></i>
                        MTN Pricing - <?php echo htmlspecialchars($store['store_name']); ?>
                    </h2>
                    <p class="text-sm text-gray-400 mt-1">
                        <i class="fas fa-store mr-1"></i>
                        Set your prices for each admin-defined range
                    </p>
                </div>
            </div>
            
            <?php if (empty($adminPricingRules)): ?>
                <div class="bg-yellow-900 border border-yellow-600 rounded-lg p-4 text-yellow-200">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    No admin pricing ranges found. Please contact administrator to set up pricing ranges.
                </div>
            <?php else: ?>
                <!-- Quick Pricing Examples -->
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6 bg-gray-900 p-4 rounded-lg">
                    <?php 
                    $exampleSizes = [1, 2, 5, 10];
                    foreach ($exampleSizes as $size) {
                        $found = false;
                        foreach ($adminPricingRules as $adminRule) {
                            if ($size >= $adminRule['min_size_gb'] && $size <= $adminRule['max_size_gb']) {
                                $key = sprintf('%.4f-%.4f', floatval($adminRule['min_size_gb']), floatval($adminRule['max_size_gb']));
                                if (isset($storePricingMap[$key])) {
                                    $price = $size * $storePricingMap[$key]['price_per_gb'];
                                } else {
                                    $price = $size * $adminRule['price_per_gb'];
                                }
                                echo '<div class="text-center">';
                                echo '<div class="text-lg font-bold text-white">' . $size . 'GB</div>';
                                echo '<div class="text-green-400 font-bold">GH₵ ' . number_format($price, 2) . '</div>';
                                echo '</div>';
                                $found = true;
                                break;
                            }
                        }
                    }
                    ?>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="border-b border-gray-700">
                                <th class="pb-3 text-left text-gray-400">Size Range (GB)</th>
                                <th class="pb-3 text-left text-gray-400">Admin Base Price</th>
                                <th class="pb-3 text-left text-gray-400">Your Price per GB</th>
                                <th class="pb-3 text-left text-gray-400">Example</th>
                                <th class="pb-3 text-left text-gray-400">Status</th>
                                <th class="pb-3 text-left text-gray-400">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($adminPricingRules as $adminRule): 
                                // Format key consistently to match store pricing map (4 decimal places for precision)
                                $key = sprintf('%.4f-%.4f', floatval($adminRule['min_size_gb']), floatval($adminRule['max_size_gb']));
                                $storePricing = isset($storePricingMap[$key]) ? $storePricingMap[$key] : null;
                                
                                if ($storePricing) {
                                    $pricePerGb = $storePricing['price_per_gb'];
                                    $isActive = $storePricing['is_active'];
                                    $pricingId = $storePricing['id'];
                                    $hasPrice = true;
                                } else {
                                    $pricePerGb = $adminRule['price_per_gb'];
                                    $isActive = 0;
                                    $pricingId = null;
                                    $hasPrice = false;
                                }
                                
                                $isBelowAdmin = $pricePerGb < $adminRule['price_per_gb'];
                            ?>
                            <tr class="border-b border-gray-700 <?php echo $isBelowAdmin ? 'bg-red-900/30' : ''; ?> <?php echo !$hasPrice ? 'bg-gray-900/50' : ''; ?>">
                                <td class="py-3 text-white">
                                    <?php echo number_format($adminRule['min_size_gb'], 2); ?>GB - 
                                    <?php echo number_format($adminRule['max_size_gb'], 2); ?>GB
                                </td>
                                <td class="py-3">
                                    <span class="text-yellow-400 font-semibold">GH₵ <?php echo number_format($adminRule['price_per_gb'], 2); ?>/GB</span>
                                    <div class="text-xs text-yellow-500 mt-1">Admin Base</div>
                                </td>
                                <td class="py-3">
                                    <?php if ($hasPrice): ?>
                                        <span class="text-green-400 font-bold <?php echo $isBelowAdmin ? 'text-red-400' : ''; ?>">
                                            GH₵ <?php echo number_format($pricePerGb, 2); ?>
                                        </span>
                                        <?php if ($isBelowAdmin): ?>
                                            <div class="text-xs text-red-400 mt-1">
                                                <i class="fas fa-exclamation-triangle"></i> Below Admin!
                                            </div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-gray-500 text-sm italic">Not set</span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-3 text-gray-300 text-sm">
                                    <?php if ($hasPrice): ?>
                                        1GB = GH₵ <?php echo number_format($pricePerGb, 2); ?>
                                    <?php else: ?>
                                        <span class="text-gray-500">Set price to see example</span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-3">
                                    <?php if ($hasPrice): ?>
                                        <span class="px-3 py-1 rounded-full text-xs 
                                            <?php echo $isActive ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300'; ?>">
                                            <?php echo $isActive ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="px-3 py-1 rounded-full text-xs bg-gray-700 text-gray-400">
                                            Not Set
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-3">
                                    <?php if ($hasPrice): ?>
                                        <button onclick="editPricing(<?php echo $pricingId; ?>, 'mtn', <?php echo $adminRule['min_size_gb']; ?>, <?php echo $adminRule['max_size_gb']; ?>, <?php echo $pricePerGb; ?>)" 
                                                class="px-3 py-2 md:px-2 md:py-1 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-semibold min-h-[44px] md:min-h-0 flex items-center justify-center gap-1.5 transition-colors"
                                                title="Edit pricing">
                                            <i class="fas fa-edit"></i>
                                            <span class="md:hidden">Edit</span>
                                        </button>
                                    <?php else: ?>
                                        <button onclick="setPricing('mtn', <?php echo $adminRule['min_size_gb']; ?>, <?php echo $adminRule['max_size_gb']; ?>, <?php echo $adminRule['price_per_gb']; ?>)" 
                                                class="px-3 py-2 md:px-2 md:py-1 bg-green-600 hover:bg-green-700 text-white rounded-lg text-sm font-semibold min-h-[44px] md:min-h-0 flex items-center justify-center gap-1.5 transition-colors"
                                                title="Set price for this range">
                                            <i class="fas fa-plus"></i>
                                            <span>Set Price</span>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

    </div>

    <!-- Set Pricing Modal (for ranges without prices) -->
    <div id="setPricingModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-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">Set Price for Range</h3>
                <button onclick="closeSetPricingModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="setPricingForm" class="space-y-4">
                <input type="hidden" id="set_min_size" name="min_size_gb">
                <input type="hidden" id="set_max_size" name="max_size_gb">
                <input type="hidden" id="set_network" name="network">
                
                <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>
                    Set your price per GB for the admin-defined range shown below.
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Size Range</label>
                    <p class="text-white font-semibold" id="set_range_display"></p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Admin Base Price</label>
                    <p class="text-yellow-400 font-semibold" id="set_admin_price_display"></p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Your Price per GB (GH₵)</label>
                    <input type="number" id="set_price_per_gb" name="price_per_gb" step="0.01" min="0.01" required
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600"
                           placeholder="3.50">
                    <p class="text-xs text-yellow-400 mt-1">
                        <i class="fas fa-info-circle"></i> 
                        Setting below admin base price will result in losses.
                    </p>
                </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="set_preview">
                        Enter price to see preview
                    </div>
                </div>
                
                <button type="submit" 
                        class="w-full bg-green-600 text-white py-3 rounded-lg hover:bg-green-700">
                    <i class="fas fa-save mr-2"></i>Set Price
                </button>
            </form>
        </div>
    </div>

    <!-- Edit Pricing Modal -->
    <div id="editPricingModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 px-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 Pricing</h3>
                <button onclick="closeEditPricingModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="editPricingForm" class="space-y-4">
                <input type="hidden" id="edit_pricing_id" name="pricing_id">
                <input type="hidden" id="edit_network" name="network">
                <input type="hidden" id="edit_min_size" name="min_size_gb">
                <input type="hidden" id="edit_max_size" name="max_size_gb">
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Size Range</label>
                    <p class="text-white" id="edit_size_display"></p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Price per GB (GH₵)</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 text-white px-4 py-2 rounded-lg border border-gray-600">
                    <p class="text-xs text-yellow-400 mt-1">
                        <i class="fas fa-info-circle"></i> 
                        Check admin base pricing above. Setting below admin price will result in losses.
                    </p>
                </div>
                
                <button type="submit" 
                        class="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-save mr-2"></i>Update Pricing
                </button>
            </form>
        </div>
    </div>

    <script>
        function setPricing(network, minSize, maxSize, adminPrice) {
            document.getElementById('set_min_size').value = minSize;
            document.getElementById('set_max_size').value = maxSize;
            document.getElementById('set_network').value = network;
            document.getElementById('set_range_display').textContent = minSize + 'GB - ' + maxSize + 'GB';
            document.getElementById('set_admin_price_display').textContent = 'GH₵ ' + parseFloat(adminPrice).toFixed(2) + '/GB';
            document.getElementById('set_price_per_gb').value = adminPrice;
            document.getElementById('setPricingModal').classList.remove('hidden');
            updateSetPreview();
        }
        
        function closeSetPricingModal() {
            document.getElementById('setPricingModal').classList.add('hidden');
            document.getElementById('setPricingForm').reset();
            document.getElementById('set_preview').textContent = 'Enter price to see preview';
        }
        
        function updateSetPreview() {
            const minSize = parseFloat(document.getElementById('set_min_size').value) || 0;
            const maxSize = parseFloat(document.getElementById('set_max_size').value) || 0;
            const pricePerGb = parseFloat(document.getElementById('set_price_per_gb').value) || 0;
            
            const preview = document.getElementById('set_preview');
            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 price to see preview';
            }
        }
        
        function editPricing(id, network, minSize, maxSize, pricePerGb) {
            document.getElementById('edit_pricing_id').value = id;
            document.getElementById('edit_network').value = network;
            document.getElementById('edit_min_size').value = minSize;
            document.getElementById('edit_max_size').value = maxSize;
            document.getElementById('edit_price_per_gb').value = pricePerGb;
            document.getElementById('edit_size_display').textContent = minSize + 'GB - ' + maxSize + 'GB';
            document.getElementById('editPricingModal').classList.remove('hidden');
        }
        
        function closeEditPricingModal() {
            document.getElementById('editPricingModal').classList.add('hidden');
        }
        
        // Set pricing form submission (for ranges without prices)
        document.getElementById('setPricingForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            formData.append('store_id', <?php echo $store['id']; ?>);
            
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Setting...';
            
            fetch('add_store_pricing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Price set successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unknown error'));
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });
        
        // Preview for set pricing form
        document.getElementById('set_price_per_gb').addEventListener('input', updateSetPreview);
        
        // Edit pricing form submission
        document.getElementById('editPricingForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            formData.append('store_id', <?php echo $store['id']; ?>);
            
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Updating...';
            
            fetch('update_store_pricing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Pricing updated successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unknown error'));
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalText;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred');
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        });
        
        // Preview for add pricing form
        ['add_min_size', 'add_max_size', 'add_price_per_gb'].forEach(id => {
            document.getElementById(id).addEventListener('input', function() {
                const minSize = parseFloat(document.getElementById('add_min_size').value) || 0;
                const maxSize = parseFloat(document.getElementById('add_max_size').value) || 0;
                const pricePerGb = parseFloat(document.getElementById('add_price_per_gb').value) || 0;
                
                if (minSize > 0 && maxSize > 0 && pricePerGb > 0) {
                    const exampleSize = (minSize + maxSize) / 2;
                    const examplePrice = exampleSize * pricePerGb;
                    document.getElementById('add_preview').innerHTML = 
                        `Range: ${minSize}GB - ${maxSize}GB<br>` +
                        `Example: ${exampleSize.toFixed(2)}GB = GH₵${examplePrice.toFixed(2)}`;
                } else {
                    document.getElementById('add_preview').textContent = 'Enter values to see preview';
                }
            });
        });
        
    </script>
    
    <script>
        // Mobile menu toggle
        document.getElementById('mobileMenuBtn').addEventListener('click', function() {
            const menu = document.getElementById('mobileMenu');
            menu.classList.toggle('hidden');
        });
        
        // Close mobile menu when clicking outside
        document.addEventListener('click', function(e) {
            const menu = document.getElementById('mobileMenu');
            const btn = document.getElementById('mobileMenuBtn');
            if (!menu.contains(e.target) && !btn.contains(e.target)) {
                menu.classList.add('hidden');
            }
        });
    </script>
    
    <style>
        .btn-touch {
            min-height: 44px;
            min-width: 44px;
        }
        
        /* Mobile table improvements */
        @media (max-width: 768px) {
            .overflow-x-auto {
                -webkit-overflow-scrolling: touch;
            }
            
            table {
                font-size: 0.875rem;
            }
            
            table th,
            table td {
                padding: 0.75rem 0.5rem;
            }
            
            /* Make action buttons full width on mobile */
            table td:last-child {
                padding: 0.75rem;
            }
            
            table td:last-child button {
                width: 100%;
            }
        }
    </style>
</body>
</html>



