<?php
/**
 * Store Paystack Settings - Allow store owners to configure their own Paystack credentials
 */

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

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

$userId = $_SESSION['user_id'];

// Verify user is a store owner
$storeManager = new StoreManager($conn);
$verification = $storeManager->verifyStoreOwner($userId);

if (!$verification['valid']) {
    header("Location: store_dashboard.php");
    exit();
}

$store = $storeManager->getStoreByOwnerId($userId);

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

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

$message = '';
$messageType = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save') {
        $publicKey = trim($_POST['public_key'] ?? '');
        $secretKey = trim($_POST['secret_key'] ?? '');
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        
        // Check if credentials already exist
        $checkStmt = $conn->prepare("SELECT id, secret_key FROM store_paystack_credentials WHERE store_id = ?");
        $checkStmt->bind_param("i", $store['id']);
        $checkStmt->execute();
        $existing = $checkStmt->get_result()->fetch_assoc();
        $checkStmt->close();
        
        if ($existing) {
            // Updating existing credentials
            // If secret key is empty, keep the existing one
            if (empty($secretKey)) {
                $secretKey = $existing['secret_key'];
            }
            
            // If public key is empty but credentials exist, require it (can't disable without public key)
            if (empty($publicKey)) {
                $message = 'Public Key is required';
                $messageType = 'error';
            } else {
                // Update existing
                $updateStmt = $conn->prepare("
                    UPDATE store_paystack_credentials 
                    SET public_key = ?, secret_key = ?, is_active = ?, updated_at = NOW()
                    WHERE store_id = ?
                ");
                $updateStmt->bind_param("ssii", $publicKey, $secretKey, $isActive, $store['id']);
                
                if ($updateStmt->execute()) {
                    $message = $isActive ? 'Paystack enabled successfully!' : 'Paystack disabled successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Failed to update credentials: ' . $updateStmt->error;
                    $messageType = 'error';
                }
                $updateStmt->close();
            }
        } else {
            // Inserting new credentials - both keys are required
            if (empty($publicKey) || empty($secretKey)) {
                $message = 'Both Public Key and Secret Key are required to set up Paystack';
                $messageType = 'error';
            } else {
                // Insert new
                $insertStmt = $conn->prepare("
                    INSERT INTO store_paystack_credentials (store_id, public_key, secret_key, is_active)
                    VALUES (?, ?, ?, ?)
                ");
                $insertStmt->bind_param("issi", $store['id'], $publicKey, $secretKey, $isActive);
                
                if ($insertStmt->execute()) {
                    $message = 'Paystack credentials saved successfully!';
                    $messageType = 'success';
                } else {
                    $message = 'Failed to save credentials: ' . $insertStmt->error;
                    $messageType = 'error';
                }
                $insertStmt->close();
            }
        }
    } else if ($action === 'delete') {
        $deleteStmt = $conn->prepare("DELETE FROM store_paystack_credentials WHERE store_id = ?");
        $deleteStmt->bind_param("i", $store['id']);
        
        if ($deleteStmt->execute()) {
            $message = 'Paystack credentials removed successfully!';
            $messageType = 'success';
        } else {
            $message = 'Failed to remove credentials: ' . $deleteStmt->error;
            $messageType = 'error';
        }
        $deleteStmt->close();
    }
}

// Get current credentials
$credStmt = $conn->prepare("SELECT public_key, secret_key, is_active FROM store_paystack_credentials WHERE store_id = ?");
$credStmt->bind_param("i", $store['id']);
$credStmt->execute();
$credResult = $credStmt->get_result();
$credentials = $credResult->fetch_assoc();
$credStmt->close();

// Mask secret key for display
$maskedSecretKey = '';
if ($credentials && !empty($credentials['secret_key'])) {
    $secretKey = $credentials['secret_key'];
    if (strlen($secretKey) > 8) {
        $maskedSecretKey = substr($secretKey, 0, 4) . str_repeat('*', strlen($secretKey) - 8) . substr($secretKey, -4);
    } else {
        $maskedSecretKey = str_repeat('*', strlen($secretKey));
    }
}

// Get store statistics for header
$stats = $storeManager->getStoreStats($store['id']);
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];
$storeUrl = $baseUrl . "/store.php?slug=" . urlencode($store['store_slug']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Paystack Settings - <?php echo htmlspecialchars($store['store_name']); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <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>
    <?php renderStoreNav($store, 'paystack'); ?>

<div class="container mx-auto px-3 sm:px-4 py-6 sm:py-8">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="mb-6 sm:mb-8">
            <h1 class="text-xl sm:text-3xl font-bold text-white mb-2 truncate">Paystack Payment Settings</h1>
            <p class="text-sm sm:text-base text-gray-400">
                Configure your store's Paystack credentials to accept payments directly to your account.
                When customers pay via Paystack, funds will go to your Paystack account.
            </p>
        </div>

        <!-- Message -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-xl <?php echo $messageType === 'success' ? 'bg-green-900/50 text-green-300 border border-green-700' : 'bg-red-900/50 text-red-300 border border-red-700'; ?>">
            <div class="flex items-center">
                <i class="fas <?php echo $messageType === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
                <span><?php echo htmlspecialchars($message); ?></span>
            </div>
        </div>
        <?php endif; ?>

        <!-- Info Box -->
        <div class="mb-6 bg-blue-900/30 border border-blue-700/50 rounded-xl p-4 sm:p-5">
            <div class="flex items-start">
                <i class="fas fa-info-circle text-blue-400 mt-1 mr-3 flex-shrink-0"></i>
                <div class="text-sm text-blue-200">
                    <p class="font-semibold mb-2 text-blue-100">How it works:</p>
                    <ul class="list-disc list-inside space-y-1.5 ml-2">
                        <li>Add your Paystack Public and Secret Keys from your Paystack dashboard</li>
                        <li>When customers choose Paystack payment, they'll pay directly to your Paystack account</li>
                        <li>Orders will be automatically processed when payment is confirmed</li>
                        <li>If Paystack is disabled or not configured, customers will use Mobile Money</li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Settings Form -->
        <div class="bg-gray-800 rounded-xl shadow-lg border border-gray-700 p-4 sm:p-6">
            <form method="POST" id="paystackForm">
                <input type="hidden" name="action" value="save">
                
                <div class="space-y-6">
                    <!-- Public Key -->
                    <div>
                        <label for="public_key" class="block text-sm font-medium text-gray-300 mb-2">
                            Paystack Public Key <span class="text-red-400">*</span>
                        </label>
                        <input 
                            type="text" 
                            id="public_key" 
                            name="public_key" 
                            value="<?php echo htmlspecialchars($credentials['public_key'] ?? ''); ?>"
                            required
                            class="w-full px-4 py-2.5 bg-gray-700 border border-gray-600 text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-500"
                            placeholder="pk_test_xxxxxxxxxxxxx or pk_live_xxxxxxxxxxxxx"
                        >
                        <p class="mt-1.5 text-xs text-gray-400">Get this from your Paystack Dashboard → Settings → API Keys & Webhooks</p>
                    </div>

                    <!-- Secret Key -->
                    <div>
                        <label for="secret_key" class="block text-sm font-medium text-gray-300 mb-2">
                            Paystack Secret Key 
                            <?php if (!$credentials): ?>
                            <span class="text-red-400">*</span>
                            <?php else: ?>
                            <span class="text-gray-500 text-xs">(Optional - leave blank to keep current)</span>
                            <?php endif; ?>
                        </label>
                        <input 
                            type="password" 
                            id="secret_key" 
                            name="secret_key" 
                            value=""
                            class="w-full px-4 py-2.5 bg-gray-700 border border-gray-600 text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-500"
                            placeholder="<?php echo $credentials ? 'Leave blank to keep current key' : 'sk_test_xxxxxxxxxxxxx or sk_live_xxxxxxxxxxxxx'; ?>"
                            <?php echo $credentials ? '' : 'required'; ?>
                        >
                        <?php if ($credentials && $maskedSecretKey): ?>
                        <p class="mt-1.5 text-xs text-gray-400">Current key: <span class="font-mono text-gray-300"><?php echo htmlspecialchars($maskedSecretKey); ?></span></p>
                        <p class="mt-1 text-xs text-blue-400"><i class="fas fa-info-circle mr-1"></i>You can disable Paystack without changing the secret key</p>
                        <?php else: ?>
                        <p class="mt-1.5 text-xs text-gray-400">Get this from your Paystack Dashboard → Settings → API Keys & Webhooks</p>
                        <?php endif; ?>
                    </div>

                    <!-- Active Toggle -->
                    <div class="flex items-center p-3 bg-gray-700/50 rounded-lg border border-gray-600">
                        <input 
                            type="checkbox" 
                            id="is_active" 
                            name="is_active" 
                            value="1"
                            <?php echo ($credentials && $credentials['is_active'] == 1) ? 'checked' : ''; ?>
                            class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-500 rounded bg-gray-700"
                        >
                        <label for="is_active" class="ml-3 block text-sm text-gray-300">
                            Enable Paystack payments for this store
                        </label>
                    </div>

                    <!-- Buttons -->
                    <div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 pt-4 border-t border-gray-700">
                        <div>
                            <?php if ($credentials): ?>
                            <button 
                                type="button"
                                onclick="if(confirm('Are you sure you want to remove Paystack credentials? Customers will only be able to use Mobile Money.')) { document.getElementById('deleteForm').submit(); }"
                                class="w-full sm:w-auto px-4 py-2.5 text-sm font-medium text-red-300 bg-red-900/30 border border-red-700 rounded-lg hover:bg-red-900/50 transition-colors"
                            >
                                <i class="fas fa-trash mr-2"></i>Remove Credentials
                            </button>
                            <?php endif; ?>
                        </div>
                        <div class="flex flex-col sm:flex-row gap-3">
                            <a 
                                href="store_dashboard.php" 
                                class="px-6 py-2.5 text-sm font-medium text-gray-300 bg-gray-700 rounded-lg hover:bg-gray-600 transition-colors text-center"
                            >
                                Cancel
                            </a>
                            <button 
                                type="submit"
                                class="px-6 py-2.5 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 transition-colors"
                            >
                                <i class="fas fa-save mr-2"></i>Save Settings
                            </button>
                        </div>
                    </div>
                </div>
            </form>

            <!-- Delete Form (hidden) -->
            <?php if ($credentials): ?>
            <form method="POST" id="deleteForm" class="hidden">
                <input type="hidden" name="action" value="delete">
            </form>
            <?php endif; ?>
        </div>

        <!-- Status Card -->
        <?php if ($credentials): ?>
        <div class="mt-6 bg-gray-800 rounded-xl shadow-lg border border-gray-700 p-4 sm:p-6">
            <h3 class="text-lg font-semibold text-white mb-4 flex items-center">
                <i class="fas fa-info-circle text-blue-400 mr-2"></i>Current Status
            </h3>
            <div class="space-y-3">
                <div class="flex items-center justify-between p-3 bg-gray-700/50 rounded-lg">
                    <span class="text-sm text-gray-300">Paystack Configured:</span>
                    <span class="px-3 py-1 text-xs font-semibold rounded-full bg-green-900/50 text-green-300 border border-green-700">
                        <i class="fas fa-check-circle mr-1"></i>Yes
                    </span>
                </div>
                <div class="flex items-center justify-between p-3 bg-gray-700/50 rounded-lg">
                    <span class="text-sm text-gray-300">Status:</span>
                    <span class="px-3 py-1 text-xs font-semibold rounded-full <?php echo $credentials['is_active'] ? 'bg-green-900/50 text-green-300 border border-green-700' : 'bg-gray-700 text-gray-400 border border-gray-600'; ?>">
                        <?php echo $credentials['is_active'] ? 'Active' : 'Inactive'; ?>
                    </span>
                </div>
                <div class="flex items-center justify-between p-3 bg-gray-700/50 rounded-lg">
                    <span class="text-sm text-gray-300">Last Updated:</span>
                    <span class="text-sm text-white font-medium">
                        <?php 
                        $updateStmt = $conn->prepare("SELECT updated_at FROM store_paystack_credentials WHERE store_id = ?");
                        $updateStmt->bind_param("i", $store['id']);
                        $updateStmt->execute();
                        $updateResult = $updateStmt->get_result();
                        $updateData = $updateResult->fetch_assoc();
                        $updateStmt->close();
                        echo $updateData ? date('M d, Y H:i', strtotime($updateData['updated_at'])) : 'N/A';
                        ?>
                    </span>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
    // Mobile menu toggle
    document.getElementById('mobileMenuBtn').addEventListener('click', function() {
        const menu = document.getElementById('mobileMenu');
        menu.classList.toggle('hidden');
        const icon = this.querySelector('i');
        if (menu.classList.contains('hidden')) {
            icon.classList.remove('fa-times');
            icon.classList.add('fa-bars');
        } else {
            icon.classList.remove('fa-bars');
            icon.classList.add('fa-times');
        }
    });

    // 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');
            const icon = btn.querySelector('i');
            icon.classList.remove('fa-times');
            icon.classList.add('fa-bars');
        }
    });
</script>
</body>
</html>

