<?php
/**
 * Store Customer Pricing Management - For Store Owners to set package-specific prices for regular customers
 * Different from store_pricing.php which handles range-based pricing for sub-agents
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/StoreCustomerPricingManager.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 customer pricing
$customerPricingManager = new StoreCustomerPricingManager($conn);
$mtnPricing = $customerPricingManager->getStoreCustomerPricing($store['id'], 'mtn');

// Get maximum package size from admin rules (for validation)
$maxAdminSize = $customerPricingManager->getMaxAdminPackageSize('mtn');

// Create a map of existing pricing by package size
$pricingMap = [];
foreach ($mtnPricing as $pricing) {
    $key = sprintf('%.4f', floatval($pricing['package_size_gb']));
    $pricingMap[$key] = $pricing;
}

// CSRF Protection
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

$csrfToken = generateCSRFToken();

// 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>Customer 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, 'customer_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-users mr-2"></i>
                        <?php echo htmlspecialchars($store['store_name']); ?> - Customer Pricing
                    </h2>
                    <p class="text-blue-200">
                        <i class="fas fa-info-circle mr-2"></i>
                        Set package-specific prices for <strong>regular customers</strong> (not agents)
                    </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>Customer Pricing (Package-Specific)</h3>
            <ul class="list-disc list-inside space-y-1 text-sm">
                <li><strong>This is for regular customers</strong> who buy from your store page</li>
                <li><strong>Different from Agent Pricing:</strong> Agents use range-based pricing, customers use package-specific pricing</li>
                <li><strong>Package-Specific:</strong> Set exact price for each package (e.g., 1GB = GH₵5.00, 2GB = GH₵10.00)</li>
                <li><strong>Maximum Size:</strong> You can set prices up to <?php echo $maxAdminSize ? number_format($maxAdminSize, 2) : 'N/A'; ?>GB (highest admin range)</li>
                <li><strong>Example:</strong> 1GB = GH₵5.00, 2GB = GH₵10.00, 5GB = GH₵45.00</li>
                <li><strong>Network:</strong> MTN only</li>
            </ul>
        </div>

        <!-- Add New Pricing Button -->
        <div class="mb-6">
            <button onclick="openAddPricingModal()" 
                    class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg font-semibold flex items-center gap-2">
                <i class="fas fa-plus"></i>
                Add Customer Price
            </button>
        </div>

        <!-- MTN Customer 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 Customer Pricing - <?php echo htmlspecialchars($store['store_name']); ?>
                    </h2>
                    <p class="text-sm text-gray-400 mt-1">
                        <i class="fas fa-users mr-1"></i>
                        Package-specific prices for regular customers
                    </p>
                </div>
            </div>
            
            <?php if (empty($mtnPricing)): ?>
                <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 customer pricing set yet. Click "Add Customer Price" to get started.
                </div>
            <?php else: ?>
                <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">Package Size</th>
                                <th class="pb-3 text-left text-gray-400">Package Label</th>
                                <th class="pb-3 text-left text-gray-400">Price</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 ($mtnPricing as $pricing): ?>
                            <tr class="border-b border-gray-700">
                                <td class="py-3 text-white font-semibold">
                                    <?php echo number_format($pricing['package_size_gb'], 2); ?>GB
                                </td>
                                <td class="py-3 text-gray-300">
                                    <?php echo htmlspecialchars($pricing['package_label']); ?>
                                </td>
                                <td class="py-3">
                                    <span class="text-green-400 font-bold text-lg">
                                        GH₵ <?php echo number_format($pricing['price'], 2); ?>
                                    </span>
                                </td>
                                <td class="py-3">
                                    <span class="px-3 py-1 rounded-full text-xs 
                                        <?php echo $pricing['is_active'] ? 'bg-green-900 text-green-300' : 'bg-red-900 text-red-300'; ?>">
                                        <?php echo $pricing['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td class="py-3">
                                    <div class="flex items-center gap-2">
                                        <button onclick="editPricing(<?php echo $pricing['id']; ?>, <?php echo $pricing['package_size_gb']; ?>, '<?php echo htmlspecialchars($pricing['package_label']); ?>', <?php echo $pricing['price']; ?>, <?php echo $pricing['is_active']; ?>)" 
                                                class="px-3 py-2 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>
                                        <button onclick="deletePricing(<?php echo $pricing['id']; ?>, '<?php echo htmlspecialchars($pricing['package_label']); ?>')" 
                                                class="px-3 py-2 bg-red-600 hover:bg-red-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="Delete pricing">
                                            <i class="fas fa-trash"></i>
                                            <span class="md:hidden">Delete</span>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

    </div>

    <!-- Add Pricing Modal -->
    <div id="addPricingModal" 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">Add Customer Price</h3>
                <button onclick="closeAddPricingModal()" class="text-gray-400 hover:text-white">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form id="addPricingForm" class="space-y-4">
                <input type="hidden" id="add_network" name="network" value="mtn">
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Package Size (GB)</label>
                    <input type="number" id="add_package_size" name="package_size_gb" 
                           step="0.01" min="0.01" max="<?php echo $maxAdminSize ? $maxAdminSize : 1000; ?>" 
                           inputmode="decimal" pattern="[0-9]+(\.[0-9]{1,2})?" required
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600"
                           placeholder="1.0">
                    <p class="text-xs text-yellow-400 mt-1">
                        <i class="fas fa-info-circle"></i> 
                        Maximum: <?php echo $maxAdminSize ? number_format($maxAdminSize, 2) : 'N/A'; ?>GB
                    </p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Package Label</label>
                    <input type="text" id="add_package_label" name="package_label" 
                           pattern="[0-9]+(\.?[0-9]+)?\s*(GB|MB|gb|mb)?" 
                           inputmode="text" maxlength="20" required
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600"
                           placeholder="1GB">
                    <p class="text-xs text-gray-500 mt-1">Display label (e.g., "1GB", "2GB", "5GB")</p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Price (GH₵)</label>
                    <input type="number" id="add_price" name="price" 
                           step="0.01" min="0.01" inputmode="decimal" 
                           pattern="[0-9]+(\.[0-9]{1,2})?" required
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600"
                           placeholder="5.00">
                </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>Add 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 Customer Price</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" value="mtn">
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Package Size (GB)</label>
                    <input type="number" id="edit_package_size" name="package_size_gb" 
                           step="0.01" min="0.01" max="<?php echo $maxAdminSize ? $maxAdminSize : 1000; ?>" 
                           inputmode="decimal" pattern="[0-9]+(\.[0-9]{1,2})?" 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> 
                        Maximum: <?php echo $maxAdminSize ? number_format($maxAdminSize, 2) : 'N/A'; ?>GB
                    </p>
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Package Label</label>
                    <input type="text" id="edit_package_label" name="package_label" 
                           pattern="[0-9]+(\.?[0-9]+)?\s*(GB|MB|gb|mb)?" 
                           inputmode="text" maxlength="20" required
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                </div>
                
                <div>
                    <label class="block text-sm text-gray-400 mb-2">Price (GH₵)</label>
                    <input type="number" id="edit_price" name="price" 
                           step="0.01" min="0.01" inputmode="decimal" 
                           pattern="[0-9]+(\.[0-9]{1,2})?" required
                           class="w-full bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                </div>
                
                <div>
                    <label class="flex items-center gap-2 text-gray-400">
                        <input type="checkbox" id="edit_is_active" name="is_active" value="1" checked
                               class="w-4 h-4 bg-gray-700 border-gray-600 rounded">
                        <span>Active</span>
                    </label>
                </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 Price
                </button>
            </form>
        </div>
    </div>

    <script>
        function openAddPricingModal() {
            document.getElementById('addPricingModal').classList.remove('hidden');
            document.getElementById('addPricingForm').reset();
        }
        
        function closeAddPricingModal() {
            document.getElementById('addPricingModal').classList.add('hidden');
        }
        
        function editPricing(id, packageSize, packageLabel, price, isActive) {
            document.getElementById('edit_pricing_id').value = id;
            document.getElementById('edit_package_size').value = packageSize;
            document.getElementById('edit_package_label').value = packageLabel;
            document.getElementById('edit_price').value = price;
            document.getElementById('edit_is_active').checked = isActive == 1;
            document.getElementById('editPricingModal').classList.remove('hidden');
        }
        
        function closeEditPricingModal() {
            document.getElementById('editPricingModal').classList.add('hidden');
        }
        
        // CSRF Token
        const csrfToken = '<?php echo $csrfToken; ?>';
        
        // Add pricing form submission
        document.getElementById('addPricingForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            formData.append('store_id', <?php echo $store['id']; ?>);
            formData.append('csrf_token', csrfToken);
            
            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>Adding...';
            
            fetch('add_store_customer_pricing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Price added 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;
            });
        });
        
        // 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']; ?>);
            formData.append('is_active', document.getElementById('edit_is_active').checked ? '1' : '0');
            formData.append('csrf_token', csrfToken);
            
            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_customer_pricing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Price 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;
            });
        });
        
        // Delete pricing function
        function deletePricing(pricingId, packageLabel) {
            if (!confirm(`Are you sure you want to delete the pricing for "${packageLabel}"? This action cannot be undone.`)) {
                return;
            }
            
            const formData = new FormData();
            formData.append('pricing_id', pricingId);
            formData.append('store_id', <?php echo $store['id']; ?>);
            formData.append('csrf_token', csrfToken);
            
            fetch('delete_store_customer_pricing.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Pricing deleted successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred while deleting the pricing');
            });
        }
        
        // Mobile menu toggle
        document.getElementById('mobileMenuBtn').addEventListener('click', function() {
            const menu = document.getElementById('mobileMenu');
            menu.classList.toggle('hidden');
        });
    </script>
    
    <style>
        .btn-touch {
            min-height: 44px;
            min-width: 44px;
        }
    </style>
</body>
</html>

