<?php
// API Configuration Page Content

// Set page variables for header
$page_title = 'API Configuration';
$page_description = 'Configure API settings for different network providers';

$success_message = '';
$error_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_api_config'])) {
        $network_type = trim($_POST['network_type'] ?? '');
        $api_name = trim($_POST['api_name'] ?? '');
        $api_endpoint = trim($_POST['api_endpoint'] ?? '');
        $api_key = trim($_POST['api_key'] ?? '');
        $api_secret = trim($_POST['api_secret'] ?? '');
        $request_method = trim($_POST['request_method'] ?? 'POST');
        $request_headers = trim($_POST['request_headers'] ?? '');
        $request_body_template = trim($_POST['request_body_template'] ?? '');
        $response_success_field = trim($_POST['response_success_field'] ?? 'success');
        $response_data_field = trim($_POST['response_data_field'] ?? 'data');
        $response_error_field = trim($_POST['response_error_field'] ?? 'error');
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $timeout_seconds = intval($_POST['timeout_seconds'] ?? 30);
        $retry_attempts = intval($_POST['retry_attempts'] ?? 3);
    }
    
    // Handle toggle activation
    if (isset($_POST['toggle_active'])) {
        $network_type = trim($_POST['network_type'] ?? '');
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (!empty($network_type)) {
            try {
                $toggle_stmt = $conn->prepare("UPDATE api_config SET is_active = ? WHERE network_type = ?");
                $toggle_stmt->bind_param("is", $is_active, $network_type);
                
                if ($toggle_stmt->execute()) {
                    $success_message = 'API configuration ' . ($is_active ? 'activated' : 'deactivated') . ' successfully!';
                } else {
                    $error_message = 'Failed to update API status.';
                }
                $toggle_stmt->close();
            } catch (Exception $e) {
                $error_message = 'Error: ' . $e->getMessage();
            }
        }
    }
    
    if (isset($_POST['update_api_config'])) {
        
        if (empty($network_type) || empty($api_name) || empty($api_endpoint)) {
            $error_message = "Network type, API name, and endpoint are required.";
        } else {
            try {
                // Check if configuration exists
                $check_stmt = $conn->prepare("SELECT id FROM api_config WHERE network_type = ?");
                $check_stmt->bind_param("s", $network_type);
                $check_stmt->execute();
                $result = $check_stmt->get_result();
                $exists = $result->num_rows > 0;
                $check_stmt->close();
                
                if ($exists) {
                    // Update existing configuration
                    $update_stmt = $conn->prepare("UPDATE api_config SET 
                        api_name = ?, api_endpoint = ?, api_key = ?, api_secret = ?, 
                        request_method = ?, request_headers = ?, request_body_template = ?,
                        response_success_field = ?, response_data_field = ?, response_error_field = ?,
                        is_active = ?, timeout_seconds = ?, retry_attempts = ?
                        WHERE network_type = ?");
                    $update_stmt->bind_param("ssssssssssiiss", 
                        $api_name, $api_endpoint, $api_key, $api_secret,
                        $request_method, $request_headers, $request_body_template,
                        $response_success_field, $response_data_field, $response_error_field,
                        $is_active, $timeout_seconds, $retry_attempts, $network_type);
                } else {
                    // Insert new configuration
                    $insert_stmt = $conn->prepare("INSERT INTO api_config 
                        (network_type, api_name, api_endpoint, api_key, api_secret, 
                         request_method, request_headers, request_body_template,
                         response_success_field, response_data_field, response_error_field,
                         is_active, timeout_seconds, retry_attempts) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $insert_stmt->bind_param("sssssssssssiis", 
                        $network_type, $api_name, $api_endpoint, $api_key, $api_secret,
                        $request_method, $request_headers, $request_body_template,
                        $response_success_field, $response_data_field, $response_error_field,
                        $is_active, $timeout_seconds, $retry_attempts);
                }
                
                if (($exists && $update_stmt->execute()) || (!$exists && $insert_stmt->execute())) {
                    $success_message = 'API configuration saved successfully!';
                } else {
                    $error_message = 'Failed to save API configuration.';
                }
                
                if ($exists) {
                    $update_stmt->close();
                } else {
                    $insert_stmt->close();
                }
                
            } catch (Exception $e) {
                $error_message = 'Error: ' . $e->getMessage();
            }
        }
    }
}

// Get existing API configurations
$configs_query = "SELECT * FROM api_config ORDER BY network_type";
$configs_result = mysqli_query($conn, $configs_query);
$configs = [];
while ($row = mysqli_fetch_assoc($configs_result)) {
    $configs[$row['network_type']] = $row;
}

// Get configuration to edit (if specified)
$edit_config = null;
if (isset($_GET['edit']) && !empty($_GET['edit'])) {
    $edit_network = trim($_GET['edit']);
    if (isset($configs[$edit_network])) {
        $edit_config = $configs[$edit_network];
    }
}
?>


<!-- API Configuration Content -->
<div class="space-y-6">
    <?php if ($success_message): ?>
    <div class="p-4 rounded-lg bg-green-100 text-green-800 border border-green-200">
        <i class="fas fa-check-circle mr-2"></i>
        <?= htmlspecialchars($success_message) ?>
    </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
    <div class="p-4 rounded-lg bg-red-100 text-red-800 border border-red-200">
        <i class="fas fa-exclamation-circle mr-2"></i>
        <?= htmlspecialchars($error_message) ?>
    </div>
    <?php endif; ?>
    
    <!-- Add/Edit API Configuration -->
    <div class="dark-card rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-semibold dark-text-primary">
                <i class="fas fa-plug text-accent-blue mr-2"></i>
                <?= $edit_config ? 'Edit API Configuration' : 'Add New API Configuration' ?>
            </h2>
            <?php if ($edit_config): ?>
            <a href="index.php?page=api_config" class="text-sm text-accent-blue hover:text-blue-600">
                <i class="fas fa-plus mr-1"></i>Add New
            </a>
            <?php endif; ?>
        </div>
        
        <form method="POST" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">Network Type</label>
                    <select name="network_type" required class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent" <?= $edit_config ? 'disabled' : '' ?>>
                        <option value="">Select Network</option>
                        <option value="mtn" <?= ($edit_config && $edit_config['network_type'] === 'mtn') ? 'selected' : '' ?>>MTN</option>
                    </select>
                    <?php if ($edit_config): ?>
                    <input type="hidden" name="network_type" value="<?= htmlspecialchars($edit_config['network_type']) ?>">
                    <?php endif; ?>
                </div>
                
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">API Name</label>
                    <input type="text" name="api_name" required class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent" placeholder="API Provider Name" value="<?= $edit_config ? htmlspecialchars($edit_config['api_name']) : '' ?>">
                </div>
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium dark-text-secondary mb-2">API Endpoint</label>
                    <input type="url" name="api_endpoint" required class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent" placeholder="https://api.example.com/endpoint" value="<?= $edit_config ? htmlspecialchars($edit_config['api_endpoint']) : '' ?>">
                </div>
                
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">API Key</label>
                    <input type="password" name="api_key" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent" placeholder="API Key" value="<?= $edit_config ? htmlspecialchars($edit_config['api_key']) : '' ?>">
                </div>
                
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">API Secret</label>
                    <input type="password" name="api_secret" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent" placeholder="API Secret" value="<?= $edit_config ? htmlspecialchars($edit_config['api_secret']) : '' ?>">
                </div>
                
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">Request Method</label>
                    <select name="request_method" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent">
                        <option value="POST" <?= ($edit_config && $edit_config['request_method'] === 'POST') ? 'selected' : '' ?>>POST</option>
                        <option value="GET" <?= ($edit_config && $edit_config['request_method'] === 'GET') ? 'selected' : '' ?>>GET</option>
                        <option value="PUT" <?= ($edit_config && $edit_config['request_method'] === 'PUT') ? 'selected' : '' ?>>PUT</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">Timeout (seconds)</label>
                    <input type="number" name="timeout_seconds" value="<?= $edit_config ? $edit_config['timeout_seconds'] : '30' ?>" min="5" max="300" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent">
                </div>
                
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">Retry Attempts</label>
                    <input type="number" name="retry_attempts" value="<?= $edit_config ? $edit_config['retry_attempts'] : '3' ?>" min="0" max="10" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent">
                </div>
                
                <div class="flex items-center">
                    <input type="checkbox" name="is_active" id="is_active" class="h-4 w-4 text-accent-blue focus:ring-accent-blue dark-border-secondary rounded" <?= ($edit_config && $edit_config['is_active']) ? 'checked' : '' ?>>
                    <label for="is_active" class="ml-2 block text-sm dark-text-primary">Active</label>
                </div>
            </div>
            
            <div>
                <label class="block text-sm font-medium dark-text-secondary mb-2">Request Headers (JSON)</label>
                <textarea name="request_headers" rows="3" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent" placeholder='{"Content-Type": "application/json", "Authorization": "Bearer token"}'><?= $edit_config ? htmlspecialchars($edit_config['request_headers']) : '' ?></textarea>
            </div>
            
            <div>
                <label class="block text-sm font-medium dark-text-secondary mb-2">Request Body Template (JSON)</label>
                <textarea name="request_body_template" rows="4" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent" placeholder='{"phone": "{phone}", "amount": "{amount}", "package": "{package}"}'><?= $edit_config ? htmlspecialchars($edit_config['request_body_template']) : '' ?></textarea>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">Success Field</label>
                    <input type="text" name="response_success_field" value="<?= $edit_config ? htmlspecialchars($edit_config['response_success_field']) : 'success' ?>" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent">
                </div>
                
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">Data Field</label>
                    <input type="text" name="response_data_field" value="<?= $edit_config ? htmlspecialchars($edit_config['response_data_field']) : 'data' ?>" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent">
                </div>
                
                <div>
                    <label class="block text-sm font-medium dark-text-secondary mb-2">Error Field</label>
                    <input type="text" name="response_error_field" value="<?= $edit_config ? htmlspecialchars($edit_config['response_error_field']) : 'error' ?>" class="dark-input w-full rounded-lg px-3 py-2 focus:ring-2 focus:ring-accent-blue focus:border-transparent">
                </div>
            </div>
            
            <div class="flex justify-end">
                <button type="submit" name="update_api_config" class="bg-accent-blue text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors">
                    <i class="fas fa-save mr-2"></i>Save Configuration
                </button>
            </div>
        </form>
    </div>
    
    <!-- Current API Configurations -->
    <div class="dark-card rounded-lg shadow-md p-6">
        <h3 class="text-lg font-semibold dark-text-primary mb-4">
            <i class="fas fa-list dark-text-muted mr-2"></i>Current API Configurations
        </h3>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <?php foreach ($configs as $network => $config): ?>
            <div class="bg-dark-primary rounded-lg p-4 dark-border">
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-medium dark-text-primary"><?= ucfirst(str_replace('_', ' ', $network)) ?></h4>
                    <div class="flex items-center space-x-2">
                        <form method="POST" class="inline">
                            <input type="hidden" name="network_type" value="<?= htmlspecialchars($config['network_type']) ?>">
                            <input type="hidden" name="is_active" value="<?= $config['is_active'] ? '0' : '1' ?>">
                            <button type="submit" name="toggle_active" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium transition-colors <?= $config['is_active'] ? 'bg-green-100 text-green-800 hover:bg-green-200' : 'bg-red-100 text-red-800 hover:bg-red-200' ?>">
                                <i class="fas fa-power-off mr-1"></i>
                                <?= $config['is_active'] ? 'Active' : 'Inactive' ?>
                            </button>
                        </form>
                    </div>
                </div>
                <p class="text-sm dark-text-muted"><strong>API:</strong> <?= htmlspecialchars($config['api_name']) ?></p>
                <p class="text-sm dark-text-muted"><strong>Endpoint:</strong> <?= htmlspecialchars(substr($config['api_endpoint'], 0, 30)) ?>...</p>
                <p class="text-sm dark-text-muted"><strong>Method:</strong> <?= htmlspecialchars($config['request_method']) ?></p>
                <p class="text-sm dark-text-muted"><strong>Timeout:</strong> <?= $config['timeout_seconds'] ?>s</p>
                
                <div class="mt-3 flex space-x-2">
                    <a href="index.php?page=api_config&edit=<?= urlencode($config['network_type']) ?>" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-accent-blue hover:text-blue-600 transition-colors">
                        <i class="fas fa-edit mr-1"></i>Edit
                    </a>
                    <span class="text-xs dark-text-muted">Updated: <?= date('M j, Y', strtotime($config['updated_at'])) ?></span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle toggle buttons with confirmation
    const toggleButtons = document.querySelectorAll('button[name="toggle_active"]');
    toggleButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            const isActive = this.querySelector('input[name="is_active"]').value === '1';
            const network = this.querySelector('input[name="network_type"]').value;
            const action = isActive ? 'activate' : 'deactivate';
            
            if (!confirm(`Are you sure you want to ${action} the ${network} API configuration?`)) {
                e.preventDefault();
            }
        });
    });
    
    // Auto-save toggle state changes
    const toggleForms = document.querySelectorAll('form[method="POST"]');
    toggleForms.forEach(form => {
        if (form.querySelector('button[name="toggle_active"]')) {
            form.addEventListener('submit', function(e) {
                // Add loading state
                const button = this.querySelector('button[name="toggle_active"]');
                const originalText = button.innerHTML;
                button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Updating...';
                button.disabled = true;
                
                // Re-enable after a delay (in case of error)
                setTimeout(() => {
                    button.innerHTML = originalText;
                    button.disabled = false;
                }, 3000);
            });
        }
    });
});
</script>


