<?php
require_once '../config/database.php';

$page_title = "AI Performance Analyzer Setup";
include '../includes/header.php';
include '../includes/sidebar_layout.php';

$message = '';
$success = false;

// Handle setup request
if (isset($_POST['setup_ai'])) {
    try {
        // Create AI performance predictions table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_performance_predictions (
                id INT AUTO_INCREMENT PRIMARY KEY,
                student_id INT NOT NULL,
                subject_id INT NOT NULL,
                exam_type ENUM('midterm', 'final', 'test') NOT NULL,
                session VARCHAR(20) NOT NULL,
                predicted_grade VARCHAR(5),
                predicted_marks DECIMAL(5,2),
                confidence_score DECIMAL(3,2),
                analysis_date DATE NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
                FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
                INDEX idx_student_subject (student_id, subject_id),
                INDEX idx_session_exam (session, exam_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        // Create AI learning patterns table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_learning_patterns (
                id INT AUTO_INCREMENT PRIMARY KEY,
                student_id INT NOT NULL,
                subject_id INT NOT NULL,
                pattern_type ENUM('improvement', 'decline', 'stable', 'volatile') NOT NULL,
                trend_slope DECIMAL(5,2),
                consistency_score DECIMAL(3,2),
                last_updated DATE NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
                FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
                INDEX idx_student_pattern (student_id, pattern_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        // Create AI recommendations table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_recommendations (
                id INT AUTO_INCREMENT PRIMARY KEY,
                student_id INT NOT NULL,
                subject_id INT,
                recommendation_type ENUM('study_tips', 'focus_areas', 'improvement_strategies', 'warning') NOT NULL,
                priority ENUM('high', 'medium', 'low') DEFAULT 'medium',
                title VARCHAR(200) NOT NULL,
                description TEXT NOT NULL,
                suggested_action TEXT,
                generated_date DATE NOT NULL,
                status ENUM('pending', 'implemented', 'dismissed') DEFAULT 'pending',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
                FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
                INDEX idx_student_rec (student_id, recommendation_type),
                INDEX idx_priority_status (priority, status)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        // Create AI analytics dashboard data table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_dashboard_analytics (
                id INT AUTO_INCREMENT PRIMARY KEY,
                class_id INT NOT NULL,
                session VARCHAR(20) NOT NULL,
                subject_id INT,
                metric_type ENUM('average_performance', 'pass_rate', 'top_performers', 'at_risk_students') NOT NULL,
                value DECIMAL(5,2),
                comparison_value DECIMAL(5,2),
                trend_direction ENUM('up', 'down', 'stable') DEFAULT 'stable',
                analysis_period DATE NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE CASCADE,
                FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE CASCADE,
                INDEX idx_class_session (class_id, session),
                INDEX idx_metric_type (metric_type)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        // Create AI student risk assessment table
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS ai_risk_assessments (
                id INT AUTO_INCREMENT PRIMARY KEY,
                student_id INT NOT NULL,
                risk_level ENUM('low', 'medium', 'high', 'critical') NOT NULL,
                risk_factors JSON,
                overall_score DECIMAL(3,2),
                assessment_date DATE NOT NULL,
                next_review_date DATE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
                INDEX idx_student_risk (student_id, risk_level),
                INDEX idx_assessment_date (assessment_date)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        $message = "✅ AI Performance Analyzer tables created successfully!";
        $success = true;
        
    } catch (Exception $e) {
        $message = "❌ Error creating tables: " . $e->getMessage();
        $success = false;
    }
}
?>

<div class="main-content">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col">
                    <h3 class="page-title">AI Performance Analyzer Setup</h3>
                    <ul class="breadcrumb">
                        <li class="breadcrumb-item"><a href="../index.php">Dashboard</a></li>
                        <li class="breadcrumb-item active">AI Setup</li>
                    </ul>
                </div>
            </div>
        </div>

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

        <div class="row">
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">Setup AI Performance Analyzer</h5>
                    </div>
                    <div class="card-body">
                        <p>This will create the necessary database tables for the AI Performance Analyzer system.</p>
                        
                        <div class="alert alert-info">
                            <h6>What will be created:</h6>
                            <ul>
                                <li><strong>ai_performance_predictions</strong> - Stores AI-generated performance predictions</li>
                                <li><strong>ai_learning_patterns</strong> - Tracks student learning patterns and trends</li>
                                <li><strong>ai_recommendations</strong> - Stores personalized student recommendations</li>
                                <li><strong>ai_dashboard_analytics</strong> - Pre-computed analytics for fast dashboard loading</li>
                                <li><strong>ai_risk_assessments</strong> - Student risk assessment scores and factors</li>
                            </ul>
                        </div>

                        <form method="POST">
                            <button type="submit" name="setup_ai" class="btn btn-primary btn-lg" 
                                    onclick="return confirm('Are you sure you want to set up the AI Performance Analyzer?')">
                                <i class="fas fa-cogs"></i> Setup AI Performance Analyzer
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">AI Features</h5>
                    </div>
                    <div class="card-body">
                        <h6>Performance Prediction</h6>
                        <p>Predicts student performance based on historical data and learning patterns.</p>
                        
                        <h6>Learning Analytics</h6>
                        <p>Tracks student progress, identifies trends, and detects learning patterns.</p>
                        
                        <h6>Smart Recommendations</h6>
                        <p>Provides personalized study tips, focus areas, and improvement strategies.</p>
                        
                        <h6>Risk Assessment</h6>
                        <p>Identifies students at risk of academic failure and suggests interventions.</p>
                        
                        <h6>Visual Dashboard</h6>
                        <p>Interactive charts and metrics for monitoring class and student performance.</p>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($success): ?>
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0">Next Steps</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>Access the AI Dashboard</h6>
                        <p>You can now access the AI Performance Analyzer dashboard:</p>
                        <a href="index.php" class="btn btn-success">
                            <i class="fas fa-chart-line"></i> Go to AI Dashboard
                        </a>
                    </div>
                    <div class="col-md-6">
                        <h6>Generate Initial Data</h6>
                        <p>Run these actions to populate the AI system with initial data:</p>
                        <ol>
                            <li>Click "Generate Predictions" on the dashboard</li>
                            <li>Click "Get Recommendations" to create student suggestions</li>
                            <li>Click "Run Risk Assessment" to evaluate student risks</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

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