<?php
/**
 * AI API Settings
 * Configure Gemini and DeepSeek API keys
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/validation.php';
require_once '../../includes/ai-integration.php';

requireAdmin();

$pdo = getDB();
$error = '';
$success = '';

// Ensure settings table exists with AI keys
$pdo->exec("INSERT IGNORE INTO settings (setting_key, setting_value, setting_type) VALUES 
    ('gemini_api_key', '', 'text'),
    ('deepseek_api_key', '', 'text'),
    ('use_ai', '0', 'boolean'),
    ('ai_model', 'gemini', 'text'),
    ('ai_temperature', '0.7', 'number'),
    ('ai_max_tokens', '2048', 'number')");

// Load current settings
$stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN 
                    ('gemini_api_key', 'deepseek_api_key', 'use_ai', 'ai_model', 'ai_temperature', 'ai_max_tokens')");
$aiSettings = [];
while ($row = $stmt->fetch()) {
    $aiSettings[$row['setting_key']] = $row['setting_value'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = "Security token validation failed.";
    } else {
        $geminiApiKey = trim($_POST['gemini_api_key']);
        $deepseekApiKey = trim($_POST['deepseek_api_key']);
        $useAI = isset($_POST['use_ai']) ? 1 : 0;
        $aiModel = $_POST['ai_model'];
        $temperature = (float)$_POST['temperature'];
        $maxTokens = (int)$_POST['max_tokens'];
        
        $updateStmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
        $updateStmt->execute([$geminiApiKey, 'gemini_api_key']);
        $updateStmt->execute([$deepseekApiKey, 'deepseek_api_key']);
        $updateStmt->execute([$useAI, 'use_ai']);
        $updateStmt->execute([$aiModel, 'ai_model']);
        $updateStmt->execute([$temperature, 'ai_temperature']);
        $updateStmt->execute([$maxTokens, 'ai_max_tokens']);
        
        // Update constants for current session
        define('GEMINI_API_KEY', $geminiApiKey);
        define('DEEPSEEK_API_KEY', $deepseekApiKey);
        define('USE_AI', $useAI);
        
        $success = "AI settings saved successfully!";
        
        // Test API connection if enabled
        if ($useAI && !empty($geminiApiKey) && $aiModel == 'gemini') {
            $testResult = callGeminiAPI("Say 'API working' if you receive this.");
            if ($testResult) {
                $success .= "<br>✓ Gemini API test successful!";
            } else {
                $error = "Gemini API test failed. Please check your API key.";
            }
        } elseif ($useAI && !empty($deepseekApiKey) && $aiModel == 'deepseek') {
            $testResult = callDeepSeekAPI("Say 'API working' if you receive this.");
            if ($testResult) {
                $success .= "<br>✓ DeepSeek API test successful!";
            } else {
                $error = "DeepSeek API test failed. Please check your API key.";
            }
        }
        
        // Refresh settings
        $stmt = $pdo->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN 
                            ('gemini_api_key', 'deepseek_api_key', 'use_ai', 'ai_model', 'ai_temperature', 'ai_max_tokens')");
        $aiSettings = [];
        while ($row = $stmt->fetch()) {
            $aiSettings[$row['setting_key']] = $row['setting_value'];
        }
    }
}

// Get AI usage statistics
$aiStats = getAIStatistics();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Settings - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .api-key-status {
            font-size: 12px;
            margin-top: 5px;
        }
        .status-valid { color: #28a745; }
        .status-invalid { color: #dc3545; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">Dashboard</a>
                    <a class="nav-link" href="../doctors/index.php">Doctors</a>
                    <a class="nav-link" href="../subscriptions/index.php">Subscriptions</a>
                    <a class="nav-link" href="../rubrics/index.php">Rubrics</a>
                    <a class="nav-link" href="../remedies/index.php">Remedies</a>
                    <a class="nav-link active" href="index.php">Settings</a>
                    <a class="nav-link" href="ai-settings.php">AI Settings</a>
                    <a class="nav-link" href="backup.php">Backup</a>
                    <a class="nav-link" href="system-info.php">System Info</a>
                    <a class="nav-link" href="../profile.php">My Profile</a>
                    <hr>
                    <a class="nav-link" href="../../logout.php">Logout</a>
                </nav>
            </div>
            
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <h4 class="mb-0"><i class="fas fa-robot"></i> AI Configuration</h4>
                </div>
                
                <div class="p-4">
                    <?php if ($success): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger"><?php echo $error; ?></div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">AI Service Configuration</h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST">
                                        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                                        
                                        <div class="form-check form-switch mb-3">
                                            <input class="form-check-input" type="checkbox" id="use_ai" name="use_ai" 
                                                   <?php echo ($aiSettings['use_ai'] ?? '0') == '1' ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="use_ai">
                                                <strong>Enable AI Features</strong>
                                            </label>
                                            <small class="text-muted d-block">Enable AI-powered case analysis, remedy suggestions, and rubric extraction</small>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="ai_model" class="form-label">AI Model</label>
                                            <select class="form-control" id="ai_model" name="ai_model">
                                                <option value="gemini" <?php echo ($aiSettings['ai_model'] ?? 'gemini') == 'gemini' ? 'selected' : ''; ?>>Google Gemini</option>
                                                <option value="deepseek" <?php echo ($aiSettings['ai_model'] ?? 'gemini') == 'deepseek' ? 'selected' : ''; ?>>DeepSeek</option>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3" id="gemini-section">
                                            <label for="gemini_api_key" class="form-label">Gemini API Key</label>
                                            <input type="password" class="form-control" id="gemini_api_key" name="gemini_api_key" 
                                                   value="<?php echo escape($aiSettings['gemini_api_key'] ?? ''); ?>"
                                                   placeholder="Enter your Google Gemini API key">
                                            <div class="api-key-status">
                                                <?php if (!empty($aiSettings['gemini_api_key'])): ?>
                                                    <span class="status-valid"><i class="fas fa-check-circle"></i> API key configured</span>
                                                <?php else: ?>
                                                    <span class="status-invalid"><i class="fas fa-exclamation-circle"></i> No API key set</span>
                                                <?php endif; ?>
                                            </div>
                                            <small class="text-muted">Get your API key from <a href="https://makersuite.google.com/app/apikey" target="_blank">Google AI Studio</a></small>
                                        </div>
                                        
                                        <div class="mb-3" id="deepseek-section" style="display: none;">
                                            <label for="deepseek_api_key" class="form-label">DeepSeek API Key</label>
                                            <input type="password" class="form-control" id="deepseek_api_key" name="deepseek_api_key" 
                                                   value="<?php echo escape($aiSettings['deepseek_api_key'] ?? ''); ?>"
                                                   placeholder="Enter your DeepSeek API key">
                                            <div class="api-key-status">
                                                <?php if (!empty($aiSettings['deepseek_api_key'])): ?>
                                                    <span class="status-valid"><i class="fas fa-check-circle"></i> API key configured</span>
                                                <?php else: ?>
                                                    <span class="status-invalid"><i class="fas fa-exclamation-circle"></i> No API key set</span>
                                                <?php endif; ?>
                                            </div>
                                            <small class="text-muted">Get your API key from <a href="https://platform.deepseek.com/" target="_blank">DeepSeek Platform</a></small>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label for="temperature" class="form-label">Temperature (0-1)</label>
                                                <input type="number" class="form-control" id="temperature" name="temperature" 
                                                       value="<?php echo $aiSettings['ai_temperature'] ?? '0.7'; ?>" step="0.1" min="0" max="1">
                                                <small class="text-muted">Higher = more creative, Lower = more focused</small>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="max_tokens" class="form-label">Max Tokens</label>
                                                <input type="number" class="form-control" id="max_tokens" name="max_tokens" 
                                                       value="<?php echo $aiSettings['ai_max_tokens'] ?? '2048'; ?>" step="256" min="256" max="8192">
                                                <small class="text-muted">Maximum response length</small>
                                            </div>
                                        </div>
                                        
                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="fas fa-save"></i> Save AI Settings
                                            </button>
                                            <button type="button" class="btn btn-info" onclick="testAPI()">
                                                <i class="fas fa-vial"></i> Test Connection
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">AI Statistics</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <strong>Cache Files:</strong> <?php echo $aiStats['cache_files']; ?>
                                    </div>
                                    <div class="mb-3">
                                        <strong>Cache Size:</strong> <?php echo $aiStats['cache_size']; ?>
                                    </div>
                                    <div class="mb-3">
                                        <strong>API Status:</strong><br>
                                        Gemini: <?php echo $aiStats['api_configured']['gemini'] ? '<span class="text-success">✓ Configured</span>' : '<span class="text-danger">✗ Not configured</span>'; ?><br>
                                        DeepSeek: <?php echo $aiStats['api_configured']['deepseek'] ? '<span class="text-success">✓ Configured</span>' : '<span class="text-danger">✗ Not configured</span>'; ?>
                                    </div>
                                    <hr>
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle"></i>
                                        <strong>AI Features:</strong>
                                        <ul class="mb-0 mt-2">
                                            <li>Case Analysis</li>
                                            <li>Remedy Suggestions</li>
                                            <li>Rubric Extraction</li>
                                            <li>Remedy Comparison</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h5 class="mb-0">Quick Links</h5>
                                </div>
                                <div class="card-body">
                                    <a href="https://makersuite.google.com/app/apikey" target="_blank" class="btn btn-outline-primary btn-sm w-100 mb-2">
                                        <i class="fab fa-google"></i> Get Gemini API Key
                                    </a>
                                    <a href="https://platform.deepseek.com/" target="_blank" class="btn btn-outline-info btn-sm w-100">
                                        <i class="fas fa-database"></i> Get DeepSeek API Key
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Toggle between Gemini and DeepSeek sections
        function toggleAIModel() {
            const model = $('#ai_model').val();
            if (model === 'gemini') {
                $('#gemini-section').show();
                $('#deepseek-section').hide();
            } else {
                $('#gemini-section').hide();
                $('#deepseek-section').show();
            }
        }
        
        $('#ai_model').on('change', toggleAIModel);
        toggleAIModel();
        
        // Test API connection
        function testAPI() {
            const model = $('#ai_model').val();
            const apiKey = model === 'gemini' ? $('#gemini_api_key').val() : $('#deepseek_api_key').val();
            
            if (!apiKey) {
                alert('Please enter an API key first');
                return;
            }
            
            $.ajax({
                url: 'test-ai-api.php',
                method: 'POST',
                data: { model: model, api_key: apiKey },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        alert('API test successful! ' + response.message);
                    } else {
                        alert('API test failed: ' + response.error);
                    }
                },
                error: function() {
                    alert('Failed to test API connection');
                }
            });
        }
    </script>
</body>
</html>