<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/ai.php';
require_once '../includes/functions.php';

requireLogin();

// Check if user is admin
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_openai_settings'])) {
        // Update OpenAI settings
        $openai_key = trim($_POST['openai_api_key'] ?? '');
        $model = trim($_POST['openai_model'] ?? OPENAI_MODEL);
        $max_tokens = (int)($_POST['max_tokens'] ?? OPENAI_MAX_TOKENS);
        $temperature = (float)($_POST['temperature'] ?? OPENAI_TEMPERATURE);

        // Validate inputs
        if (empty($openai_key)) {
            $error = 'OpenAI API key is required.';
        } elseif (!preg_match('/^sk-/', $openai_key)) {
            $error = 'Invalid OpenAI API key format.';
        } elseif ($max_tokens < 1 || $max_tokens > 4000) {
            $error = 'Max tokens must be between 1 and 4000.';
        } elseif ($temperature < 0 || $temperature > 2) {
            $error = 'Temperature must be between 0 and 2.';
        } else {
            // Update settings (you might want to store these in database or config)
            $settingsUpdated = true;

            if ($settingsUpdated) {
                $success = 'OpenAI settings updated successfully!';
            } else {
                $error = 'Error updating OpenAI settings.';
            }
        }
    } elseif (isset($_POST['update_feature_settings'])) {
        // Update feature enable/disable settings
        $features = [
            'content_analysis',
            'question_generation',
            'essay_evaluation',
            'content_summarization',
            'learning_path',
            'performance_analysis',
            'accessibility',
            'translation'
        ];

        $settingsUpdated = true;
        foreach ($features as $feature) {
            $enabled = isset($_POST[$feature . '_enabled']) ? 1 : 0;
            // Store in database or config
        }

        if ($settingsUpdated) {
            $success = 'AI feature settings updated successfully!';
        } else {
            $error = 'Error updating AI feature settings.';
        }
    } elseif (isset($_POST['update_limits'])) {
        // Update rate limits and costs
        $daily_limit = (float)($_POST['daily_cost_limit'] ?? AI_DAILY_COST_LIMIT);
        $monthly_limit = (float)($_POST['monthly_cost_limit'] ?? AI_MONTHLY_COST_LIMIT);
        $requests_per_hour = (int)($_POST['requests_per_hour'] ?? AI_RATE_LIMIT_REQUESTS);

        if ($daily_limit < 0 || $monthly_limit < 0 || $requests_per_hour < 1) {
            $error = 'Invalid limit values.';
        } else {
            // Update limits
            $success = 'AI limits updated successfully!';
        }
    }
}

// Get current AI usage stats
$db = getDB();
$stats = [
    'total_requests' => 0,
    'total_cost' => 0.00,
    'today_requests' => 0,
    'today_cost' => 0.00,
    'features_used' => []
];

try {
    // Get total stats
    $stmt = $db->query("SELECT COUNT(*) as total_requests, COALESCE(SUM(cost), 0) as total_cost FROM ai_usage_logs");
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $stats['total_requests'] = $result['total_requests'];
    $stats['total_cost'] = $result['total_cost'];

    // Get today's stats
    $stmt = $db->prepare("SELECT COUNT(*) as today_requests, COALESCE(SUM(cost), 0) as today_cost FROM ai_usage_logs WHERE DATE(created_at) = CURDATE()");
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $stats['today_requests'] = $result['today_requests'];
    $stats['today_cost'] = $result['today_cost'];

    // Get feature usage
    $stmt = $db->query("SELECT feature, COUNT(*) as count FROM ai_usage_logs GROUP BY feature ORDER BY count DESC");
    $stats['features_used'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (Exception $e) {
    // Handle database errors gracefully
}

$page_title = 'AI Settings';
include 'includes/admin_header.php';
?>

<?php if ($error): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<div class="settings-section">
    <h2>AI Settings & Analytics</h2>

    <!-- AI Usage Statistics -->
    <div class="settings-card">
        <h3>AI Usage Statistics</h3>
        <div class="stats-grid">
            <div class="stat-item">
                <div class="stat-value"><?php echo number_format($stats['total_requests']); ?></div>
                <div class="stat-label">Total AI Requests</div>
            </div>
            <div class="stat-item">
                <div class="stat-value">$<?php echo number_format($stats['total_cost'], 2); ?></div>
                <div class="stat-label">Total Cost</div>
            </div>
            <div class="stat-item">
                <div class="stat-value"><?php echo number_format($stats['today_requests']); ?></div>
                <div class="stat-label">Today's Requests</div>
            </div>
            <div class="stat-item">
                <div class="stat-value">$<?php echo number_format($stats['today_cost'], 2); ?></div>
                <div class="stat-label">Today's Cost</div>
            </div>
        </div>

        <?php if (!empty($stats['features_used'])): ?>
            <h4>Feature Usage Breakdown</h4>
            <div class="feature-usage">
                <?php foreach ($stats['features_used'] as $feature): ?>
                    <div class="feature-item">
                        <span class="feature-name"><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $feature['feature']))); ?></span>
                        <span class="feature-count"><?php echo number_format($feature['count']); ?> requests</span>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- OpenAI API Settings -->
    <div class="settings-card">
        <h3>OpenAI API Configuration</h3>
        <form method="POST">
            <div class="form-group">
                <label for="openai_api_key">OpenAI API Key:</label>
                <input type="password" id="openai_api_key" name="openai_api_key"
                       value="<?php echo htmlspecialchars(OPENAI_API_KEY); ?>" required>
                <small>Your OpenAI API key. Keep this secure and never share it.</small>
            </div>
            <div class="form-group">
                <label for="openai_model">Model:</label>
                <select id="openai_model" name="openai_model">
                    <option value="gpt-4o" <?php echo OPENAI_MODEL === 'gpt-4o' ? 'selected' : ''; ?>>GPT-4o (Recommended)</option>
                    <option value="gpt-4" <?php echo OPENAI_MODEL === 'gpt-4' ? 'selected' : ''; ?>>GPT-4</option>
                    <option value="gpt-3.5-turbo" <?php echo OPENAI_MODEL === 'gpt-3.5-turbo' ? 'selected' : ''; ?>>GPT-3.5 Turbo</option>
                </select>
                <small>The AI model to use for all AI features.</small>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="max_tokens">Max Tokens:</label>
                    <input type="number" id="max_tokens" name="max_tokens"
                           value="<?php echo OPENAI_MAX_TOKENS; ?>" min="1" max="4000" required>
                    <small>Maximum tokens per API call (1-4000).</small>
                </div>
                <div class="form-group">
                    <label for="temperature">Temperature:</label>
                    <input type="number" id="temperature" name="temperature"
                           value="<?php echo OPENAI_TEMPERATURE; ?>" min="0" max="2" step="0.1" required>
                    <small>Creativity level (0=deterministic, 2=very creative).</small>
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" name="update_openai_settings" class="btn btn-primary">Update OpenAI Settings</button>
            </div>
        </form>
    </div>

    <!-- AI Feature Settings -->
    <div class="settings-card">
        <h3>AI Feature Configuration</h3>
        <p class="settings-description">Enable or disable individual AI features.</p>
        <form method="POST">
            <div class="feature-grid">
                <div class="feature-item">
                    <label class="feature-toggle">
                        <input type="checkbox" name="content_analysis_enabled"
                               <?php echo isAIFeatureEnabled('content_analysis') ? 'checked' : ''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="feature-info">
                        <strong>Content Analysis</strong>
                        <p>AI-powered analysis of course content for readability, engagement, and learning objectives.</p>
                    </div>
                </div>

                <div class="feature-item">
                    <label class="feature-toggle">
                        <input type="checkbox" name="question_generation_enabled"
                               <?php echo isAIFeatureEnabled('question_generation') ? 'checked' : ''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="feature-info">
                        <strong>Question Generation</strong>
                        <p>AI-assisted creation of multiple choice, true/false, and essay questions.</p>
                    </div>
                </div>

                <div class="feature-item">
                    <label class="feature-toggle">
                        <input type="checkbox" name="essay_evaluation_enabled"
                               <?php echo isAIFeatureEnabled('essay_evaluation') ? 'checked' : ''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="feature-info">
                        <strong>Essay Evaluation</strong>
                        <p>Automated grading and feedback for essay-type questions.</p>
                    </div>
                </div>

                <div class="feature-item">
                    <label class="feature-toggle">
                        <input type="checkbox" name="content_summarization_enabled"
                               <?php echo isAIFeatureEnabled('content_summarization') ? 'checked' : ''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="feature-info">
                        <strong>Content Summarization</strong>
                        <p>Automatic generation of course and lesson summaries.</p>
                    </div>
                </div>

                <div class="feature-item">
                    <label class="feature-toggle">
                        <input type="checkbox" name="learning_path_enabled"
                               <?php echo isAIFeatureEnabled('learning_path') ? 'checked' : ''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="feature-info">
                        <strong>Learning Path Recommendations</strong>
                        <p>AI suggestions for optimal learning sequences and prerequisites.</p>
                    </div>
                </div>

                <div class="feature-item">
                    <label class="feature-toggle">
                        <input type="checkbox" name="performance_analysis_enabled"
                               <?php echo isAIFeatureEnabled('performance_analysis') ? 'checked' : ''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="feature-info">
                        <strong>Performance Analysis</strong>
                        <p>AI insights into student learning patterns and recommendations.</p>
                    </div>
                </div>

                <div class="feature-item">
                    <label class="feature-toggle">
                        <input type="checkbox" name="accessibility_enabled"
                               <?php echo isAIFeatureEnabled('accessibility') ? 'checked' : ''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="feature-info">
                        <strong>Content Accessibility</strong>
                        <p>AI analysis for accessibility compliance and improvement suggestions.</p>
                    </div>
                </div>

                <div class="feature-item">
                    <label class="feature-toggle">
                        <input type="checkbox" name="translation_enabled"
                               <?php echo isAIFeatureEnabled('translation') ? 'checked' : ''; ?>>
                        <span class="toggle-slider"></span>
                    </label>
                    <div class="feature-info">
                        <strong>Language Translation</strong>
                        <p>Basic translation support for multilingual content creation.</p>
                    </div>
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" name="update_feature_settings" class="btn btn-primary">Update Feature Settings</button>
            </div>
        </form>
    </div>

    <!-- Cost and Rate Limits -->
    <div class="settings-card">
        <h3>Cost Management & Rate Limits</h3>
        <p class="settings-description">Configure spending limits and usage restrictions.</p>
        <form method="POST">
            <div class="form-row">
                <div class="form-group">
                    <label for="daily_cost_limit">Daily Cost Limit ($):</label>
                    <input type="number" id="daily_cost_limit" name="daily_cost_limit"
                           value="<?php echo AI_DAILY_COST_LIMIT; ?>" min="0" step="0.01" required>
                    <small>Maximum daily spending on AI features.</small>
                </div>
                <div class="form-group">
                    <label for="monthly_cost_limit">Monthly Cost Limit ($):</label>
                    <input type="number" id="monthly_cost_limit" name="monthly_cost_limit"
                           value="<?php echo AI_MONTHLY_COST_LIMIT; ?>" min="0" step="0.01" required>
                    <small>Maximum monthly spending on AI features.</small>
                </div>
            </div>
            <div class="form-group">
                <label for="requests_per_hour">Requests Per Hour:</label>
                <input type="number" id="requests_per_hour" name="requests_per_hour"
                       value="<?php echo AI_RATE_LIMIT_REQUESTS; ?>" min="1" required>
                <small>Maximum AI requests allowed per hour per user.</small>
            </div>
            <div class="form-actions">
                <button type="submit" name="update_limits" class="btn btn-primary">Update Limits</button>
            </div>
        </form>
    </div>
</div>

<style>
.settings-section {
    max-width: 1000px;
}

.settings-section h2 {
    font-size: 1.875rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 2rem;
}

.settings-card {
    background: white;
    padding: 2rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 2rem;
}

.settings-card h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 1.5rem;
}

.settings-card h4 {
    font-size: 1.125rem;
    font-weight: 600;
    color: #374151;
    margin-bottom: 1rem;
}

/* Statistics Grid */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.stat-item {
    text-align: center;
    padding: 1.5rem;
    background: #f8fafc;
    border-radius: 0.5rem;
    border: 1px solid #e2e8f0;
}

.stat-value {
    font-size: 2rem;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 0.5rem;
}

.stat-label {
    font-size: 0.875rem;
    color: #64748b;
    font-weight: 500;
}

/* Feature Usage */
.feature-usage {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
}

.feature-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.75rem 1rem;
    background: #f8fafc;
    border-radius: 0.375rem;
    border: 1px solid #e2e8f0;
}

.feature-name {
    font-weight: 500;
    color: #374151;
}

.feature-count {
    font-size: 0.875rem;
    color: #64748b;
}

/* Feature Grid */
.feature-grid {
    display: grid;
    gap: 1.5rem;
}

.feature-item {
    display: flex;
    align-items: flex-start;
    gap: 1rem;
    padding: 1.5rem;
    background: #f8fafc;
    border-radius: 0.5rem;
    border: 1px solid #e2e8f0;
}

.feature-toggle {
    position: relative;
    display: inline-block;
    width: 3rem;
    height: 1.5rem;
    flex-shrink: 0;
}

.feature-toggle input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #cbd5e1;
    transition: .4s;
    border-radius: 1.5rem;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 1.125rem;
    width: 1.125rem;
    left: 0.1875rem;
    bottom: 0.1875rem;
    background-color: white;
    transition: .4s;
    border-radius: 50%;
}

input:checked + .toggle-slider {
    background-color: #2563eb;
}

input:checked + .toggle-slider:before {
    transform: translateX(1.5rem);
}

.feature-info strong {
    display: block;
    color: #1f2937;
    margin-bottom: 0.5rem;
}

.feature-info p {
    color: #64748b;
    font-size: 0.875rem;
    margin: 0;
}

/* Form Styles */
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

.form-group {
    margin-bottom: 1.5rem;
}

.form-group label {
    display: block;
    font-weight: 500;
    color: #374151;
    margin-bottom: 0.5rem;
}

.form-group input,
.form-group select {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid #d1d5db;
    border-radius: 0.375rem;
    font-size: 0.875rem;
}

.form-group input:focus,
.form-group select:focus {
    outline: none;
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

.form-group small {
    display: block;
    color: #6b7280;
    font-size: 0.75rem;
    margin-top: 0.25rem;
}

.form-actions {
    margin-top: 2rem;
    padding-top: 1.5rem;
    border-top: 1px solid #e5e7eb;
}

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0.75rem 1.5rem;
    border-radius: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
    text-decoration: none;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-primary {
    background-color: #2563eb;
    color: white;
}

.btn-primary:hover {
    background-color: #1d4ed8;
}

.settings-description {
    color: #64748b;
    margin-bottom: 2rem;
    font-size: 0.875rem;
}

/* Alert Styles */
.alert {
    padding: 1rem;
    border-radius: 0.375rem;
    margin-bottom: 1.5rem;
}

.alert-error {
    background-color: #fef2f2;
    border: 1px solid #fecaca;
    color: #dc2626;
}

.alert-success {
    background-color: #f0fdf4;
    border: 1px solid #bbf7d0;
    color: #16a34a;
}
</style>

<?php include 'includes/admin_footer.php'; ?>