<?php
/**
 * Store Owner Top-up Page
 * Allows store owners to top up their account balance using Paystack
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/MinimumTopupManager.php';
require_once '../app/classes/PaystackChargeManager.php';
require_once '../app/classes/SessionManager.php';
use App\classes\SessionManager;

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

$userId = $_SESSION['user_id'];

// SECURITY: Validate session to prevent session hijacking
$sessionManager = new SessionManager($conn);
$sessionValidation = $sessionManager->validateSession($userId);

if (!$sessionValidation['valid']) {
    error_log("Invalid session detected - User ID: $userId, Reason: " . $sessionValidation['reason']);
    $sessionManager->forceLogout();
    header("Location: ../login.php?error=session_invalid");
    exit();
}

// MULTI-LAYER SECURITY CHECK: Verify user is actually a store owner
$storeManager = new StoreManager($conn);
$verification = $storeManager->verifyStoreOwner($userId);

// If user is not a legitimate store owner, redirect to agent dashboard
if (!$verification['valid']) {
    error_log("Store Top-up Access Denied - User ID: $userId, Reason: " . $verification['reason']);
    header("Location: ../user_index.php");
    exit();
}

// Load store and user info
$store = $storeManager->getStoreByOwnerId($userId);
$userStmt = $conn->prepare("SELECT email, balance FROM agents WHERE id = ?");
$userStmt->bind_param("i", $userId);
$userStmt->execute();
$userResult = $userStmt->get_result();
$user = $userResult->fetch_assoc();
$userStmt->close();

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

$currentBalance = floatval($user['balance'] ?? 0);
$userEmail = $user['email'] ?? '';

// Initialize managers
$minimumTopupManager = new MinimumTopupManager($conn);
$chargeManager = new PaystackChargeManager($conn);

// Get minimum top-up amount
$minimumAmount = $minimumTopupManager->getMinimumAmount();
$isMinimumEnabled = $minimumTopupManager->isMinimumTopupEnabled();

// Get charge info
$chargeDescription = $chargeManager->getChargeDescription();

// Fetch MoMo configuration
$momoConfig = [];
$momoStmt = $conn->prepare("SELECT config_key, config_value FROM payment_config WHERE config_key IN ('payment_phone_number', 'payment_name')");
$momoStmt->execute();
$momoResult = $momoStmt->get_result();
while ($row = $momoResult->fetch_assoc()) {
    $momoConfig[$row['config_key']] = $row['config_value'];
}
$momoStmt->close();

$momoPhone = $momoConfig['payment_phone_number'] ?? 'Not Configured';
$momoName = $momoConfig['payment_name'] ?? 'Not Configured';

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

$csrfToken = generateCSRFToken();

// Handle success/error messages
$successMessage = '';
$errorMessage = '';

if (isset($_GET['topup'])) {
    if ($_GET['topup'] === 'success' && isset($_GET['amount'])) {
        $topupAmount = floatval($_GET['amount']);
        // SECURITY: Validate amount is reasonable
        if ($topupAmount > 0 && $topupAmount <= 100000) {
            $successMessage = "Top-up successful! Your account has been credited with GHS " . number_format($topupAmount, 2);
        } else {
            $errorMessage = "Invalid top-up amount received.";
        }
    } elseif ($_GET['topup'] === 'already_processed') {
        $ref = isset($_GET['ref']) ? htmlspecialchars($_GET['ref'], ENT_QUOTES, 'UTF-8') : 'N/A';
        // SECURITY: Validate reference format
        if (preg_match('/^[A-Z0-9_]+$/', $ref)) {
            $errorMessage = "⚠️ Payment Already Processed: This payment has already been credited to your account. Reference: $ref. If you believe this is an error, please contact support.";
        } else {
            $errorMessage = "Invalid payment reference.";
        }
    }
}

?>
<!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>Top Up Account - <?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;
        }
        
        .btn-touch {
            min-height: 44px;
            min-width: 44px;
        }
    </style>
</head>
<body class="bg-gray-900">
    <?php renderStoreNav($store, 'topup'); ?>

    <div class="container mx-auto px-3 sm:px-4 py-4 sm:py-6">
        <!-- Success/Error Messages -->
        <?php if ($successMessage): ?>
        <div class="bg-gradient-to-r from-green-800 to-green-900 border-2 border-green-600 text-green-100 rounded-xl p-4 sm:p-6 mb-6 shadow-lg">
            <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                <div class="flex items-center gap-3 flex-1">
                    <div class="w-12 h-12 sm:w-16 sm:h-16 bg-green-700 rounded-full flex items-center justify-center flex-shrink-0">
                        <i class="fas fa-check-circle text-2xl sm:text-3xl text-green-200"></i>
                    </div>
                    <div>
                        <h3 class="text-lg sm:text-xl font-bold text-white mb-1">Payment Successful!</h3>
                        <p class="text-green-200"><?php echo htmlspecialchars($successMessage); ?></p>
                    </div>
                </div>
                <div class="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
                    <a href="store_dashboard.php" 
                       class="inline-flex items-center justify-center px-4 sm:px-6 py-2 sm:py-3 bg-white text-green-800 rounded-xl hover:bg-green-50 font-semibold transition-all btn-touch">
                        <i class="fas fa-home mr-2"></i>
                        <span>Go to Dashboard</span>
                    </a>
                    <a href="store_topup.php" 
                       class="inline-flex items-center justify-center px-4 sm:px-6 py-2 sm:py-3 bg-green-700 text-white rounded-xl hover:bg-green-600 font-semibold transition-all btn-touch">
                        <i class="fas fa-credit-card mr-2"></i>
                        <span>Top Up Again</span>
                    </a>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <?php if ($errorMessage): ?>
        <div class="bg-red-900 border border-red-700 text-red-100 rounded-xl p-4 mb-6">
            <div class="flex items-center gap-2">
                <i class="fas fa-exclamation-circle text-xl"></i>
                <p><?php echo htmlspecialchars($errorMessage); ?></p>
            </div>
            <div class="mt-4 flex gap-2">
                <a href="store_dashboard.php" 
                   class="inline-flex items-center justify-center px-4 py-2 bg-white text-red-800 rounded-lg hover:bg-red-50 font-semibold transition-all btn-touch">
                    <i class="fas fa-home mr-2"></i>
                    <span>Go to Dashboard</span>
                </a>
            </div>
        </div>
        <?php endif; ?>

        <!-- Current Balance Card -->
        <div class="bg-gradient-to-r from-green-800 to-green-900 rounded-xl p-4 sm:p-6 mb-6 border border-green-700">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-green-200 text-sm mb-1">Current Balance</p>
                    <p class="text-3xl sm:text-4xl font-bold text-white">GH₵ <?php echo number_format($currentBalance, 2); ?></p>
                </div>
                <div class="w-16 h-16 bg-green-700 rounded-xl flex items-center justify-center">
                    <i class="fas fa-wallet text-green-200 text-3xl"></i>
                </div>
            </div>
        </div>

        <!-- Top-up Form -->
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700">
            <h2 class="text-xl sm:text-2xl font-bold text-white mb-4 sm:mb-6">
                <i class="fas fa-credit-card text-blue-400 mr-2"></i>
                Top Up Your Account
            </h2>
            
            <form id="topupForm" class="space-y-4 sm:space-y-6">
                <!-- SECURITY: CSRF Token -->
                <input type="hidden" id="csrf_token" name="csrf_token" value="<?php echo htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8'); ?>">
                
                <div>
                    <label for="amount" class="block text-sm font-medium text-gray-300 mb-2">
                        Amount to Top Up (GH₵) <span class="text-red-400">*</span>
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                            <span class="text-gray-400">GH₵</span>
                        </div>
                        <input type="number" 
                               id="amount" 
                               name="amount" 
                               step="0.01" 
                               min="<?php echo $isMinimumEnabled ? number_format($minimumAmount, 2) : '1'; ?>"
                               max="100000"
                               required
                               class="w-full bg-gray-700 text-white pl-16 pr-4 py-3 rounded-xl border border-gray-600 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 text-lg"
                               placeholder="0.00">
                    </div>
                    <?php if ($isMinimumEnabled): ?>
                    <p class="text-xs text-gray-400 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Minimum top-up amount: GH₵ <?php echo number_format($minimumAmount, 2); ?>
                    </p>
                    <?php endif; ?>
    <p class="text-xs text-gray-500 mt-1">
                        <i class="fas fa-shield-alt mr-1"></i>
                        Paystack Limit: GH₵ 100.00 (Use MoMo for larger amounts)
                    </p>
                </div>

                <!-- Charge Information -->
                <?php if ($chargeManager->isChargeEnabled()): ?>
                <div class="bg-blue-900/30 border border-blue-700 rounded-xl p-4">
                    <div class="flex items-start gap-3">
                        <i class="fas fa-info-circle text-blue-400 mt-1"></i>
                        <div class="flex-1">
                            <p class="text-sm font-medium text-blue-200 mb-1">Payment Charge</p>
                            <p class="text-xs text-blue-300">
                                <?php echo htmlspecialchars($chargeDescription); ?> will be added to your payment.
                                <span id="chargeBreakdown" class="block mt-1"></span>
                            </p>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Payment Summary (Dynamic) -->
                <div id="paymentSummary" class="hidden bg-gray-900 rounded-xl p-4 border border-gray-700">
                    <h3 class="text-sm font-medium text-gray-300 mb-3">Payment Summary</h3>
                    <div class="space-y-2 text-sm">
                        <div class="flex justify-between text-gray-400">
                            <span>Top-up Amount:</span>
                            <span id="summaryBaseAmount" class="text-white">GH₵ 0.00</span>
                        </div>
                        <div id="summaryChargeRow" class="hidden flex justify-between text-gray-400">
                            <span>Charge:</span>
                            <span id="summaryChargeAmount" class="text-white">GH₵ 0.00</span>
                        </div>
                        <div class="flex justify-between text-lg font-bold text-white pt-2 border-t border-gray-700">
                            <span>Total to Pay:</span>
                            <span id="summaryTotalAmount" class="text-green-400">GH₵ 0.00</span>
                        </div>
                    </div>
                </div>

                <div id="errorMessage" class="hidden bg-red-900 border border-red-700 text-red-100 rounded-xl p-4"></div>

                <div id="momoInstructions" class="hidden bg-yellow-900/30 border border-yellow-700 rounded-xl p-4 sm:p-6 mb-6">
                    <h3 class="text-lg font-bold text-yellow-500 mb-3">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        Manual Payment Required
                    </h3>
                    <p class="text-gray-300 mb-4">
                        For amounts greater than GH₵ 100.00, please send Mobile Money directly to the number below.
                    </p>
                    <div class="bg-gray-700/50 rounded-lg p-4 border border-gray-600">
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <p class="text-xs text-gray-400 uppercase">Provider</p>
                                <p class="text-white font-medium">Mobile Money</p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-400 uppercase">Number</p>
                                <p class="text-white font-medium text-lg tracking-wider"><?php echo htmlspecialchars($momoPhone); ?></p>
                            </div>
                            <div class="sm:col-span-2">
                                <p class="text-xs text-gray-400 uppercase">Account Name</p>
                                <p class="text-white font-medium"><?php echo htmlspecialchars($momoName); ?></p>
                            </div>
                        </div>
                    </div>
                    <p class="text-sm text-gray-400 mt-4">
                        <i class="fas fa-info-circle mr-1"></i>
                        Please contact support with your transaction ID after payment for manual crediting.
                    </p>
                </div>

                <button type="submit" 
                        id="submitBtn"
                        class="w-full bg-blue-600 text-white py-3 sm:py-4 rounded-xl hover:bg-blue-700 active:scale-95 btn-touch font-semibold text-lg">
                    <i class="fas fa-credit-card mr-2"></i>
                    Proceed to Payment
                </button>
            </form>
        </div>

        <!-- Info Card -->
        <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700 mt-6">
            <h3 class="text-lg font-bold text-white mb-3">
                <i class="fas fa-info-circle text-blue-400 mr-2"></i>
                Payment Information
            </h3>
            <ul class="space-y-2 text-sm text-gray-300">
                <li class="flex items-start gap-2">
                    <i class="fas fa-check text-green-400 mt-1"></i>
                    <span>Secure payment via Paystack</span>
                </li>
                <li class="flex items-start gap-2">
                    <i class="fas fa-check text-green-400 mt-1"></i>
                    <span>Your balance will be updated immediately after successful payment</span>
                </li>
                <li class="flex items-start gap-2">
                    <i class="fas fa-check text-green-400 mt-1"></i>
                    <span>You can use your topped-up balance to process orders from your store</span>
                </li>
            </ul>
        </div>
    </div>

    <script>
        const minimumAmount = <?php echo $isMinimumEnabled ? $minimumAmount : 0; ?>;
        const isMinimumEnabled = <?php echo $isMinimumEnabled ? 'true' : 'false'; ?>;
        const chargeEnabled = <?php echo $chargeManager->isChargeEnabled() ? 'true' : 'false'; ?>;
        
        const amountInput = document.getElementById('amount');
        const paymentSummary = document.getElementById('paymentSummary');
        const summaryBaseAmount = document.getElementById('summaryBaseAmount');
        const summaryChargeAmount = document.getElementById('summaryChargeAmount');
        const summaryChargeRow = document.getElementById('summaryChargeRow');
        const summaryTotalAmount = document.getElementById('summaryTotalAmount');
        const chargeBreakdown = document.getElementById('chargeBreakdown');
        const errorMessage = document.getElementById('errorMessage');
        const submitBtn = document.getElementById('submitBtn');
        const momoInstructions = document.getElementById('momoInstructions');
        
        // Calculate and display payment summary
        function updatePaymentSummary() {
            const amount = parseFloat(amountInput.value) || 0;
            
            // Hide summary if amount is 0 or invalid
            if (amount <= 0) {
                paymentSummary.classList.add('hidden');
                momoInstructions.classList.add('hidden');
                submitBtn.classList.remove('hidden');
                return;
            }

            // Check if amount > 100 (Paystack Limit)
            if (amount > 100) {
                momoInstructions.classList.remove('hidden');
                submitBtn.classList.add('hidden');
                paymentSummary.classList.add('hidden');
                errorMessage.classList.add('hidden'); // clear any previous errors
                return; // Stop further processing as we are showing MoMo instructions
            } else {
                momoInstructions.classList.add('hidden');
                submitBtn.classList.remove('hidden');
            }
            
            // Validate minimum amount
            if (isMinimumEnabled && amount < minimumAmount) {
                errorMessage.textContent = `Minimum top-up amount is GH₵ ${minimumAmount.toFixed(2)}`;
                errorMessage.classList.remove('hidden');
                paymentSummary.classList.add('hidden');
                return;
            } else {
                errorMessage.classList.add('hidden');
            }
            
            // Calculate charge via AJAX
            if (chargeEnabled) {
                fetch('../api/calculate_charge.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ amount: amount })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const baseAmount = parseFloat(data.base_amount);
                        const chargeAmount = parseFloat(data.charge_amount);
                        const totalAmount = parseFloat(data.total_amount);
                        
                        summaryBaseAmount.textContent = 'GH₵ ' + baseAmount.toFixed(2);
                        
                        if (chargeAmount > 0) {
                            summaryChargeAmount.textContent = 'GH₵ ' + chargeAmount.toFixed(2);
                            summaryChargeRow.classList.remove('hidden');
                            chargeBreakdown.textContent = `You will be credited GH₵ ${baseAmount.toFixed(2)}, but Paystack will charge GH₵ ${totalAmount.toFixed(2)} (including GH₵ ${chargeAmount.toFixed(2)} charge).`;
                        } else {
                            summaryChargeRow.classList.add('hidden');
                            chargeBreakdown.textContent = '';
                        }
                        
                        summaryTotalAmount.textContent = 'GH₵ ' + totalAmount.toFixed(2);
                        paymentSummary.classList.remove('hidden');
                    }
                })
                .catch(error => {
                    console.error('Error calculating charge:', error);
                });
            } else {
                // No charge, just show base amount
                summaryBaseAmount.textContent = 'GH₵ ' + amount.toFixed(2);
                summaryChargeRow.classList.add('hidden');
                chargeBreakdown.textContent = '';
                summaryTotalAmount.textContent = 'GH₵ ' + amount.toFixed(2);
                paymentSummary.classList.remove('hidden');
            }
        }
        
        // Update summary on amount input
        amountInput.addEventListener('input', updatePaymentSummary);
        
        // Handle form submission
        document.getElementById('topupForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const amount = parseFloat(amountInput.value);
            const csrfToken = document.getElementById('csrf_token').value;
            
            // SECURITY: Client-side validation
            if (!amount || amount <= 0) {
                errorMessage.textContent = 'Please enter a valid amount';
                errorMessage.classList.remove('hidden');
                return;
            }
            
            if (amount > 100000) {
                errorMessage.textContent = 'Maximum top-up amount is GH₵ 100,000.00';
                errorMessage.classList.remove('hidden');
                return;
            }
            
            if (isMinimumEnabled && amount < minimumAmount) {
                errorMessage.textContent = `Minimum top-up amount is GH₵ ${minimumAmount.toFixed(2)}`;
                errorMessage.classList.remove('hidden');
                return;
            }
            
            // SECURITY: Validate amount precision
            if (Math.round(amount * 100) / 100 !== amount) {
                errorMessage.textContent = 'Amount can only have up to 2 decimal places';
                errorMessage.classList.remove('hidden');
                return;
            }
            
            // Disable submit button
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';
            
            try {
                const response = await fetch('../api/store_owner_topup.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        amount: amount,
                        csrf_token: csrfToken
                    })
                });
                
                const data = await response.json();
                
                if (data.success && data.redirect_url) {
                    // Redirect to Paystack
                    window.location.href = data.redirect_url;
                } else {
                    errorMessage.textContent = data.message || 'Failed to initialize payment. Please try again.';
                    errorMessage.classList.remove('hidden');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fas fa-credit-card mr-2"></i>Proceed to Payment';
                }
            } catch (error) {
                console.error('Error:', error);
                errorMessage.textContent = 'An error occurred. Please try again.';
                errorMessage.classList.remove('hidden');
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-credit-card mr-2"></i>Proceed to Payment';
            }
        });
    </script>
</body>
</html>

