<?php
// Data Integration Configuration Page Content

// Set page variables for header
$page_title = 'Data Integration Configuration';
$page_description = 'Configure integration with external data website';

require_once '../app/classes/DataIntegrationConfig.php';

use App\classes\DataIntegrationConfig;

// Initialize config manager
$configManager = new DataIntegrationConfig($conn);

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'update_config':
                $data_website_url = trim($_POST['data_website_url']);
                $data_website_api_key = trim($_POST['data_website_api_key']);
                $webhook_url = trim($_POST['webhook_url']);
                $enabled = isset($_POST['enabled']) ? 1 : 0;
                
                // Update or insert configuration
                $stmt = $conn->prepare("
                    INSERT INTO data_integration_config (id, data_website_url, data_website_api_key, webhook_url, enabled, updated_at) 
                    VALUES (1, ?, ?, ?, ?, NOW())
                    ON DUPLICATE KEY UPDATE 
                    data_website_url = VALUES(data_website_url),
                    data_website_api_key = VALUES(data_website_api_key),
                    webhook_url = VALUES(webhook_url),
                    enabled = VALUES(enabled),
                    updated_at = NOW()
                ");
                
                $stmt->bind_param("sssi", $data_website_url, $data_website_api_key, $webhook_url, $enabled);
                
                if ($stmt->execute()) {
                    $message = 'Configuration updated successfully';
                    $messageType = 'success';
                    // Reload config after update
                    $config = $configManager->getConfig();
                } else {
                    $message = 'Failed to update configuration';
                    $messageType = 'error';
                }
                $stmt->close();
                break;
                
            case 'test_connection':
                $data_website_url = trim($_POST['data_website_url']);
                $data_website_api_key = trim($_POST['data_website_api_key']);
                
                if ($data_website_url && $data_website_api_key) {
                    // Test connection by checking a non-existent order
                    $test_url = rtrim($data_website_url, '/') . '/api/check_order_status.php?order_id=999999&api_key=' . urlencode($data_website_api_key);
                    $response = @file_get_contents($test_url);
                    
                    if ($response !== false) {
                        $data = json_decode($response, true);
                        if ($data && isset($data['success'])) {
                            $message = 'Connection test successful - API is responding';
                            $messageType = 'success';
                        } else {
                            $message = 'Connection test failed - Invalid API response';
                            $messageType = 'error';
                        }
                    } else {
                        $message = 'Connection test failed - Cannot reach data website';
                        $messageType = 'error';
                    }
                } else {
                    $message = 'Please provide both URL and API key to test connection';
                    $messageType = 'error';
                }
                break;
        }
    }
}
// Get current configuration
$config = $configManager->getConfig();

// If no config exists, create default values for the form
if (!$config) {
    // Generate webhook URL based on current domain
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'];
    $webhook_url = $protocol . '://' . $host . '/bunleshub/api/webhook/data_status_update.php';
    
    $config = [
        'data_website_url' => '',
        'data_website_api_key' => '',
        'webhook_url' => $webhook_url,
        'enabled' => 0
    ];
}
?>

            <?php if ($message): ?>
                <div class="mb-6 p-4 rounded-md <?= $messageType === 'success' ? 'bg-green-50 text-green-800 border border-green-200' : 'bg-red-50 text-red-800 border border-red-200' ?>">
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <div class="bg-white shadow rounded-lg">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-lg font-semibold text-gray-900">
                        <i class="fas fa-cog mr-2"></i>Configuration
                    </h2>
                </div>
                <div class="p-6">
                    <form method="POST" class="space-y-6">
                        <input type="hidden" name="action" value="update_config">
                        
                        <div>
                            <label for="data_website_url" class="block text-sm font-medium text-gray-700">Data Website URL</label>
                            <input type="url" id="data_website_url" name="data_website_url" value="<?= htmlspecialchars($config['data_website_url']) ?>" 
                                   class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500" required>
                            <p class="mt-1 text-sm text-gray-500">Base URL of the data website (e.g., http://localhost/data)</p>
                        </div>
                        
                        <div>
                            <label for="data_website_api_key" class="block text-sm font-medium text-gray-700">API Key</label>
                            <input type="text" id="data_website_api_key" name="data_website_api_key" value="<?= htmlspecialchars($config['data_website_api_key']) ?>" 
                                   class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                            <p class="mt-1 text-sm text-gray-500">API key from the data website admin panel</p>
                        </div>
                        
                        <div>
                            <label for="webhook_url" class="block text-sm font-medium text-gray-700">Webhook URL</label>
                            <input type="url" id="webhook_url" name="webhook_url" value="<?= htmlspecialchars($config['webhook_url']) ?>" 
                                   class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500" required>
                            <p class="mt-1 text-sm text-gray-500">This URL should be configured in the data website admin panel</p>
                        </div>
                        
                        <div class="flex items-center">
                            <input type="checkbox" id="enabled" name="enabled" <?= $config['enabled'] ? 'checked' : '' ?> 
                                   class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                            <label for="enabled" class="ml-2 block text-sm text-gray-900">Enable Data Integration</label>
                        </div>
                        
                        <div class="flex space-x-4">
                            <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                                <i class="fas fa-save mr-2"></i>Save Configuration
                            </button>
                            
                            <button type="button" onclick="testConnection()" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
                                <i class="fas fa-plug mr-2"></i>Test Connection
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Instructions -->
            <div class="mt-6 bg-white shadow rounded-lg">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-lg font-semibold text-gray-900">
                        <i class="fas fa-list-ol mr-2"></i>Setup Instructions
                    </h2>
                </div>
                <div class="p-6">
                    <ol class="list-decimal list-inside space-y-2 text-sm text-gray-700">
                        <li>Get an API key from the data website admin panel</li>
                        <li>Configure the data website URL and API key above</li>
                        <li>Copy the webhook URL and configure it in the data website admin panel</li>
                        <li>Enable the integration</li>
                        <li>Set up a cron job to run the status checker every 5 minutes:
                            <code class="block mt-2 p-2 bg-gray-100 rounded text-xs">
                                */5 * * * * /usr/bin/php /path/to/bunleshub/api/check_data_order_status.php
                            </code>
                        </li>
                    </ol>
                </div>
            </div>
        </div>

    <script>
        function testConnection() {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="test_connection">
                <input type="hidden" name="data_website_url" value="${document.getElementById('data_website_url').value}">
                <input type="hidden" name="data_website_api_key" value="${document.getElementById('data_website_api_key').value}">
            `;
            document.body.appendChild(form);
            form.submit();
        }
    </script>
