<?php 
// Include session handling
include 'services/session.php'; 

// Check if user is logged in
if (!$_SESSION['user'] || !isset($_SESSION['user'])) {
    header('Location: auth-login.php?error=session_expired');
    exit();
}

// Get user details
$user_role = $_SESSION['role_name'] ?? 'Customer';
$user_id = $_SESSION['user_id'] ?? 0;
$user_name = $_SESSION['full_name'] ?? $_SESSION['user'];

// Include database connection
require_once 'layouts/dbconn.php';

// Function to safely execute queries
function safeQuery($conn, $query, $params = []) {
    try {
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        if (!empty($params)) {
            $types = str_repeat('s', count($params));
            $stmt->bind_param($types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        $data = $result->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
        
        return $data;
    } catch (Exception $e) {
        error_log("Query error: " . $e->getMessage());
        return [];
    }
}

// Get user's sandbox apps
$sandbox_apps = safeQuery($conn, "
    SELECT app_id, app_name, app_type, description, status, created_at, last_used_at,
           (SELECT COUNT(*) FROM sandbox_transactions st WHERE st.app_id = sa.app_id) as transaction_count
    FROM sandbox_apps sa
    WHERE user_id = ?
    ORDER BY last_used_at DESC, created_at DESC
", [$user_id]);

// Predefined sandbox environments
$environments = [
    [
        'id' => 'mtn_momo',
        'name' => 'MTN Mobile Money',
        'description' => 'Test MTN MoMo Collection and Disbursement APIs',
        'icon' => 'fas fa-mobile-alt',
        'color' => 'primary',
        'features' => ['Collection API', 'Disbursement API', 'Account Balance', 'Transaction Status'],
        'status' => 'Available'
    ],
    [
        'id' => 'mgurush',
        'name' => 'm-GURUSH (Zain)',
        'description' => 'Zain m-GURUSH payment gateway integration testing',
        'icon' => 'fas fa-credit-card',
        'color' => 'success',
        'features' => ['Payment Processing', 'Refunds', 'Transaction Inquiry', 'Webhook Testing'],
        'status' => 'Available'
    ],
    [
        'id' => 'nilepay',
        'name' => 'Nilepay Gateway',
        'description' => 'Nilepay payment processing and wallet management',
        'icon' => 'fas fa-wallet',
        'color' => 'warning',
        'features' => ['Payment Gateway', 'Wallet Operations', 'Currency Exchange', 'Payment Links'],
        'status' => 'Beta'
    ],
    [
        'id' => 'airtel_money',
        'name' => 'Airtel Money',
        'description' => 'Airtel Money API integration testing',
        'icon' => 'fas fa-coins',
        'color' => 'danger',
        'features' => ['Money Transfer', 'Bill Payments', 'Merchant Payments', 'Balance Inquiry'],
        'status' => 'Coming Soon'
    ],
    [
        'id' => 'orange_money',
        'name' => 'Orange Money',
        'description' => 'Orange Money payment API testing environment',
        'icon' => 'fas fa-money-bill-wave',
        'color' => 'orange',
        'features' => ['P2P Transfer', 'Merchant Payment', 'Cash In/Out', 'Transaction History'],
        'status' => 'Coming Soon'
    ],
    [
        'id' => 'custom_api',
        'name' => 'Custom API Testing',
        'description' => 'Build and test your own payment integrations',
        'icon' => 'fas fa-code',
        'color' => 'info',
        'features' => ['API Builder', 'Request Testing', 'Response Mocking', 'Documentation'],
        'status' => 'Available'
    ]
];
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php $title = "Sandbox Playground";
    include 'partials/title-meta.php'; ?>
    
    <?php include 'partials/head-css.php'; ?>
    
    <style>
        .sandbox-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .environment-card {
            border: 1px solid #e9ecef;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            transition: all 0.3s ease;
            background: white;
            height: 100%;
        }
        
        .environment-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border-color: #007bff;
        }
        
        .environment-icon {
            width: 80px;
            height: 80px;
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            color: white;
            margin-bottom: 1.5rem;
        }
        
        .bg-orange {
            background: linear-gradient(45deg, #ff9500, #ff6b00);
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 0.5rem 0;
            border-bottom: 1px solid #f1f3f4;
        }
        
        .feature-list li:last-child {
            border-bottom: none;
        }
        
        .status-available {
            background: #d4edda;
            color: #155724;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-beta {
            background: #fff3cd;
            color: #856404;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .status-coming-soon {
            background: #f8d7da;
            color: #721c24;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .sandbox-stats {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        
        .my-apps-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }
        
        .app-item {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .app-item:hover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }
        
        .quick-start {
            background: #e7f3ff;
            border: 1px solid #b3d9ff;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .code-example {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            font-family: 'Monaco', 'Consolas', monospace;
            font-size: 0.875rem;
            margin: 1rem 0;
        }
        
        .api-endpoint {
            background: #fff;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .method-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 600;
            margin-right: 0.5rem;
        }
        
        .method-get { background: #d4edda; color: #155724; }
        .method-post { background: #cce5ff; color: #004085; }
        .method-put { background: #fff3cd; color: #856404; }
        .method-delete { background: #f8d7da; color: #721c24; }
    </style>
</head>

<?php include 'partials/body.php'; ?>

<div id="wrapper">
    <?php $pagetitle = "Sandbox Playground"; include 'partials/menu.php'; ?>

    <div class="content-page">
        <div class="content">
            <div class="container-fluid">
                
                <!-- Page Title -->
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <div class="page-title-right">
                                <ol class="breadcrumb m-0">
                                    <li class="breadcrumb-item"><a href="customer-dashboard.php">Dashboard</a></li>
                                    <li class="breadcrumb-item active">Sandbox Playground</li>
                                </ol>
                            </div>
                            <h4 class="page-title">
                                <i class="fas fa-flask me-2"></i>
                                Sandbox Playground
                            </h4>
                        </div>
                    </div>
                </div>

                <!-- Sandbox Header -->
                <div class="row">
                    <div class="col-12">
                        <div class="sandbox-header">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <h3 class="mb-3">
                                        <i class="fas fa-code me-2"></i>
                                        Test & Integrate Payment APIs
                                    </h3>
                                    <p class="mb-0 opacity-75">
                                        Experiment with mobile money and payment gateway APIs in a safe sandbox environment. 
                                        Test your integrations before going live.
                                    </p>
                                </div>
                                <div class="col-md-4 text-md-end">
                                    <div class="text-white">
                                        <h5 class="mb-1">
                                            <i class="fas fa-shield-alt me-2"></i>
                                            Safe Testing
                                        </h5>
                                        <p class="mb-0">No real transactions</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Quick Start Guide -->
                <div class="row">
                    <div class="col-12">
                        <div class="quick-start">
                            <h5 class="mb-3">
                                <i class="fas fa-rocket me-2"></i>
                                Quick Start Guide
                            </h5>
                            <div class="row">
                                <div class="col-md-8">
                                    <ol class="mb-0">
                                        <li><strong>Choose an environment</strong> from the options below</li>
                                        <li><strong>Get your test credentials</strong> and API endpoints</li>
                                        <li><strong>Test API calls</strong> using our interactive tools</li>
                                        <li><strong>View responses</strong> and debug your integration</li>
                                        <li><strong>Generate code samples</strong> for your programming language</li>
                                    </ol>
                                </div>
                                <div class="col-md-4 text-md-end">
                                    <a href="api-documentation.php" class="btn btn-primary">
                                        <i class="fas fa-book me-1"></i>
                                        API Documentation
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Sandbox Statistics -->
                <div class="row">
                    <div class="col-12">
                        <div class="sandbox-stats">
                            <div class="row text-center">
                                <div class="col-md-3">
                                    <h4 class="text-primary mb-1"><?php echo count($sandbox_apps); ?></h4>
                                    <small class="text-muted">My Sandbox Apps</small>
                                </div>
                                <div class="col-md-3">
                                    <h4 class="text-success mb-1">
                                        <?php echo array_sum(array_column($sandbox_apps, 'transaction_count')); ?>
                                    </h4>
                                    <small class="text-muted">Test Transactions</small>
                                </div>
                                <div class="col-md-3">
                                    <h4 class="text-info mb-1"><?php echo count($environments); ?></h4>
                                    <small class="text-muted">Available Environments</small>
                                </div>
                                <div class="col-md-3">
                                    <h4 class="text-warning mb-1">24/7</h4>
                                    <small class="text-muted">Sandbox Availability</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Sandbox Environments -->
                <div class="row">
                    <div class="col-12">
                        <h5 class="mb-4">
                            <i class="fas fa-server me-2"></i>
                            Available Testing Environments
                        </h5>
                    </div>
                    
                    <?php foreach ($environments as $env): ?>
                    <div class="col-xl-4 col-md-6">
                        <div class="environment-card">
                            <div class="text-center">
                                <div class="environment-icon bg-<?php echo $env['color']; ?>">
                                    <i class="<?php echo $env['icon']; ?>"></i>
                                </div>
                                
                                <h5 class="mb-2"><?php echo $env['name']; ?></h5>
                                <p class="text-muted mb-3"><?php echo $env['description']; ?></p>
                                
                                <div class="mb-3">
                                    <span class="status-<?php echo strtolower(str_replace(' ', '-', $env['status'])); ?>">
                                        <?php echo $env['status']; ?>
                                    </span>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <h6 class="mb-2">Features:</h6>
                                <ul class="feature-list">
                                    <?php foreach ($env['features'] as $feature): ?>
                                    <li>
                                        <i class="fas fa-check text-success me-2"></i>
                                        <?php echo $feature; ?>
                                    </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                            
                            <div class="text-center">
                                <?php if ($env['status'] === 'Available'): ?>
                                <a href="sandbox-<?php echo $env['id']; ?>.php" class="btn btn-<?php echo $env['color']; ?> mb-2">
                                    <i class="fas fa-play me-1"></i>
                                    Launch Environment
                                </a>
                                <br>
                                <a href="api-docs-<?php echo $env['id']; ?>.php" class="btn btn-sm btn-outline-secondary">
                                    <i class="fas fa-book me-1"></i>
                                    View API Docs
                                </a>
                                <?php elseif ($env['status'] === 'Beta'): ?>
                                <a href="sandbox-<?php echo $env['id']; ?>.php" class="btn btn-warning mb-2">
                                    <i class="fas fa-flask me-1"></i>
                                    Try Beta
                                </a>
                                <br>
                                <small class="text-muted">Beta - May have limitations</small>
                                <?php else: ?>
                                <button class="btn btn-secondary mb-2" disabled>
                                    <i class="fas fa-clock me-1"></i>
                                    Coming Soon
                                </button>
                                <br>
                                <a href="notify-availability.php?env=<?php echo $env['id']; ?>" class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-bell me-1"></i>
                                    Notify Me
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- My Sandbox Apps -->
                <?php if (!empty($sandbox_apps)): ?>
                <div class="row">
                    <div class="col-12">
                        <div class="my-apps-card">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h5 class="mb-0">
                                    <i class="fas fa-cogs me-2"></i>
                                    My Sandbox Applications
                                </h5>
                                <a href="create-sandbox-app.php" class="btn btn-sm btn-primary">
                                    <i class="fas fa-plus me-1"></i>
                                    Create New App
                                </a>
                            </div>
                            
                            <?php foreach ($sandbox_apps as $app): ?>
                            <div class="app-item">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1"><?php echo htmlspecialchars($app['app_name']); ?></h6>
                                        <p class="text-muted mb-2"><?php echo htmlspecialchars($app['description']); ?></p>
                                        <div class="d-flex align-items-center">
                                            <span class="badge bg-<?php echo $app['status'] === 'ACTIVE' ? 'success' : 'secondary'; ?> me-2">
                                                <?php echo ucfirst(strtolower($app['status'])); ?>
                                            </span>
                                            <small class="text-muted me-3">
                                                Type: <?php echo ucfirst(str_replace('_', ' ', strtolower($app['app_type']))); ?>
                                            </small>
                                            <small class="text-muted">
                                                <?php echo $app['transaction_count']; ?> test transactions
                                            </small>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <a href="sandbox-app.php?id=<?php echo $app['app_id']; ?>" class="btn btn-sm btn-outline-primary me-1">
                                            <i class="fas fa-eye me-1"></i>
                                            View
                                        </a>
                                        <a href="sandbox-app-settings.php?id=<?php echo $app['app_id']; ?>" class="btn btn-sm btn-outline-secondary">
                                            <i class="fas fa-cog me-1"></i>
                                            Settings
                                        </a>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- API Testing Tools -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="fas fa-tools me-2"></i>
                                    API Testing Tools
                                </h5>
                                <p class="card-text">
                                    Interactive tools to test API endpoints, inspect responses, and debug your integrations.
                                </p>
                                
                                <div class="api-endpoint">
                                    <div class="d-flex align-items-center mb-2">
                                        <span class="method-badge method-post">POST</span>
                                        <code>/api/v1/collection/request-to-pay</code>
                                    </div>
                                    <p class="mb-0 text-muted">Initiate a collection request</p>
                                </div>
                                
                                <div class="api-endpoint">
                                    <div class="d-flex align-items-center mb-2">
                                        <span class="method-badge method-get">GET</span>
                                        <code>/api/v1/collection/status/{referenceId}</code>
                                    </div>
                                    <p class="mb-0 text-muted">Check transaction status</p>
                                </div>
                                
                                <a href="api-tester.php" class="btn btn-primary">
                                    <i class="fas fa-play me-1"></i>
                                    Launch API Tester
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <i class="fas fa-code me-2"></i>
                                    Code Generation
                                </h5>
                                <p class="card-text">
                                    Generate ready-to-use code snippets in your preferred programming language.
                                </p>
                                
                                <div class="code-example">
<pre>// PHP Example
$response = $client->post('/collection/request-to-pay', [
    'amount' => '100',
    'currency' => 'SSP',
    'externalId' => '123456',
    'payer' => [
        'partyIdType' => 'MSISDN',
        'partyId' => '211123456789'
    ]
]);</pre>
                                </div>
                                
                                <a href="code-generator.php" class="btn btn-success">
                                    <i class="fas fa-download me-1"></i>
                                    Generate Code
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Webhook Testing -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <h5 class="mb-2">
                                            <i class="fas fa-webhook me-2"></i>
                                            Webhook Testing
                                        </h5>
                                        <p class="mb-0">
                                            Test webhook endpoints, inspect payloads, and simulate callback events 
                                            to ensure your integration handles all scenarios correctly.
                                        </p>
                                    </div>
                                    <div class="col-md-4 text-md-end">
                                        <a href="webhook-tester.php" class="btn btn-outline-primary">
                                            <i class="fas fa-satellite-dish me-1"></i>
                                            Test Webhooks
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Learning Resources -->
                <div class="row">
                    <div class="col-md-4">
                        <div class="card text-center">
                            <div class="card-body">
                                <i class="fas fa-graduation-cap fa-3x mb-3 text-primary"></i>
                                <h5>Learning Center</h5>
                                <p class="text-muted">
                                    Tutorials, guides, and best practices for mobile money integration.
                                </p>
                                <a href="learning-center.php" class="btn btn-outline-primary">
                                    <i class="fas fa-external-link-alt me-1"></i>
                                    Explore
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card text-center">
                            <div class="card-body">
                                <i class="fas fa-comments fa-3x mb-3 text-success"></i>
                                <h5>Community Forum</h5>
                                <p class="text-muted">
                                    Connect with other developers and share integration experiences.
                                </p>
                                <a href="community-forum.php" class="btn btn-outline-success">
                                    <i class="fas fa-external-link-alt me-1"></i>
                                    Join Discussion
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card text-center">
                            <div class="card-body">
                                <i class="fas fa-headphones fa-3x mb-3 text-info"></i>
                                <h5>Developer Support</h5>
                                <p class="text-muted">
                                    Get technical assistance from our developer support team.
                                </p>
                                <a href="developer-support.php" class="btn btn-outline-info">
                                    <i class="fas fa-external-link-alt me-1"></i>
                                    Get Help
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <?php include 'partials/footer.php'; ?>
    </div>
</div>

<?php include 'partials/footer-scripts.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Environment card interactions
    const envCards = document.querySelectorAll('.environment-card');
    
    envCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px) scale(1.02)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });
    
    // Notification for coming soon environments
    const notifyButtons = document.querySelectorAll('a[href*="notify-availability"]');
    
    notifyButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Simple notification signup
            const envName = this.closest('.environment-card').querySelector('h5').textContent;
            
            if (confirm(`Get notified when ${envName} becomes available?`)) {
                // Here you would typically make an AJAX call to save the notification preference
                alert('Great! We\'ll notify you when this environment is ready.');
            }
        });
    });
    
    // Copy code snippets
    const codeBlocks = document.querySelectorAll('.code-example pre');
    
    codeBlocks.forEach(block => {
        block.style.cursor = 'pointer';
        block.title = 'Click to copy';
        
        block.addEventListener('click', function() {
            const text = this.textContent;
            navigator.clipboard.writeText(text).then(() => {
                // Show copied feedback
                const originalBg = this.style.backgroundColor;
                this.style.backgroundColor = '#d4edda';
                this.style.transition = 'background-color 0.3s ease';
                
                setTimeout(() => {
                    this.style.backgroundColor = originalBg;
                }, 1000);
            });
        });
    });
});

// Initialize tooltips if Bootstrap is available
if (typeof bootstrap !== 'undefined') {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}
</script>

</body>
</html>