<?php
/**
 * Fix for LMS system
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/config/database.php';

echo "<h2>LMS System Fix Tool</h2>";

try {
    // Drop and recreate tables that need structural updates
    try {
        $pdo->exec("DROP TABLE IF EXISTS student_lesson_progress");
        echo "<p style='color: orange;'>🗑️ Dropped existing student_lesson_progress table</p>";
    } catch (Exception $e) {
        echo "<p style='color: orange;'>⚠️ Could not drop student_lesson_progress table: " . $e->getMessage() . "</p>";
    }
    
    try {
        $pdo->exec("DROP TABLE IF EXISTS live_class_attendance");
        echo "<p style='color: orange;'>🗑️ Dropped existing live_class_attendance table</p>";
    } catch (Exception $e) {
        echo "<p style='color: orange;'>⚠️ Could not drop live_class_attendance table: " . $e->getMessage() . "</p>";
    }

    // Create all LMS tables with correct structure
    $lms_tables_sql = [
        'courses' => "CREATE TABLE IF NOT EXISTS courses (
            id INT AUTO_INCREMENT PRIMARY KEY,
            course_code VARCHAR(20) UNIQUE NOT NULL,
            course_name VARCHAR(200) NOT NULL,
            description TEXT,
            class_id INT,
            subject_id INT,
            teacher_id INT,
            thumbnail VARCHAR(255),
            start_date DATE,
            end_date DATE,
            status ENUM('draft', 'active', 'completed', 'archived') DEFAULT 'draft',
            created_by INT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE SET NULL,
            FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE SET NULL,
            FOREIGN KEY (teacher_id) REFERENCES teachers(id) ON DELETE SET NULL,
            FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
        )",
        
        'course_modules' => "CREATE TABLE IF NOT EXISTS course_modules (
            id INT AUTO_INCREMENT PRIMARY KEY,
            course_id INT NOT NULL,
            module_name VARCHAR(200) NOT NULL,
            module_order INT DEFAULT 1,
            description TEXT,
            status ENUM('active', 'inactive') DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
        )",
        
        'course_lessons' => "CREATE TABLE IF NOT EXISTS course_lessons (
            id INT AUTO_INCREMENT PRIMARY KEY,
            module_id INT NOT NULL,
            lesson_title VARCHAR(200) NOT NULL,
            lesson_order INT DEFAULT 1,
            content_type ENUM('video', 'pdf', 'text', 'quiz', 'assignment', 'live_class') NOT NULL,
            content_url VARCHAR(500),
            content_text TEXT,
            duration_minutes INT,
            is_free BOOLEAN DEFAULT FALSE,
            status ENUM('active', 'inactive', 'draft') DEFAULT 'draft',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (module_id) REFERENCES course_modules(id) ON DELETE CASCADE
        )",
        
        'live_classes' => "CREATE TABLE IF NOT EXISTS live_classes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            course_id INT,
            teacher_id INT NOT NULL,
            class_id INT,
            subject_id INT,
            topic VARCHAR(200) NOT NULL,
            description TEXT,
            meeting_link VARCHAR(500),
            meeting_id VARCHAR(100),
            passcode VARCHAR(50),
            scheduled_at DATETIME NOT NULL,
            duration_minutes INT DEFAULT 60,
            status ENUM('scheduled', 'ongoing', 'completed', 'cancelled') DEFAULT 'scheduled',
            recording_url VARCHAR(500),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE SET NULL,
            FOREIGN KEY (teacher_id) REFERENCES teachers(id) ON DELETE CASCADE,
            FOREIGN KEY (class_id) REFERENCES classes(id) ON DELETE SET NULL,
            FOREIGN KEY (subject_id) REFERENCES subjects(id) ON DELETE SET NULL
        )",
        
        'student_enrollments' => "CREATE TABLE IF NOT EXISTS student_enrollments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            student_id INT NOT NULL,
            course_id INT NOT NULL,
            enrollment_date DATE DEFAULT CURRENT_DATE,
            completed_at TIMESTAMP NULL,
            progress_percent INT DEFAULT 0,
            status ENUM('enrolled', 'in_progress', 'completed', 'dropped') DEFAULT 'enrolled',
            FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
            UNIQUE KEY unique_student_course (student_id, course_id)
        )",
        
        'student_lesson_progress' => "CREATE TABLE IF NOT EXISTS student_lesson_progress (
            id INT AUTO_INCREMENT PRIMARY KEY,
            student_id INT NOT NULL,
            lesson_id INT NOT NULL,
            course_id INT NOT NULL,
            is_completed BOOLEAN DEFAULT FALSE,
            completion_date DATE,
            time_spent_minutes INT DEFAULT 0,
            last_accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
            FOREIGN KEY (lesson_id) REFERENCES course_lessons(id) ON DELETE CASCADE,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
            UNIQUE KEY unique_student_lesson (student_id, lesson_id)
        )",
        
        'lms_assignments' => "CREATE TABLE IF NOT EXISTS lms_assignments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            course_id INT NOT NULL,
            lesson_id INT,
            title VARCHAR(200) NOT NULL,
            description TEXT,
            instructions TEXT,
            max_marks INT DEFAULT 100,
            pass_marks INT DEFAULT 40,
            due_date DATETIME,
            allow_late_submission BOOLEAN DEFAULT FALSE,
            late_submission_penalty_percent INT DEFAULT 0,
            status ENUM('draft', 'published', 'closed') DEFAULT 'draft',
            created_by INT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
            FOREIGN KEY (lesson_id) REFERENCES course_lessons(id) ON DELETE SET NULL,
            FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL
        )",
        
        'assignment_submissions' => "CREATE TABLE IF NOT EXISTS assignment_submissions (
            id INT AUTO_INCREMENT PRIMARY KEY,
            assignment_id INT NOT NULL,
            student_id INT NOT NULL,
            submission_text TEXT,
            attachment_url VARCHAR(500),
            submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            is_late BOOLEAN DEFAULT FALSE,
            marks_obtained DECIMAL(5,2),
            grade VARCHAR(5),
            feedback TEXT,
            graded_by INT,
            graded_at TIMESTAMP NULL,
            status ENUM('submitted', 'graded', 'returned') DEFAULT 'submitted',
            FOREIGN KEY (assignment_id) REFERENCES lms_assignments(id) ON DELETE CASCADE,
            FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
            FOREIGN KEY (graded_by) REFERENCES users(id) ON DELETE SET NULL,
            UNIQUE KEY unique_assignment_student (assignment_id, student_id)
        )",
        
        'live_class_attendance' => "CREATE TABLE IF NOT EXISTS live_class_attendance (
            id INT AUTO_INCREMENT PRIMARY KEY,
            live_class_id INT NOT NULL,
            student_id INT NOT NULL,
            attendance_status ENUM('present', 'absent', 'late') DEFAULT 'present',
            join_time TIME,
            leave_time TIME,
            duration_minutes INT,
            participation_score INT DEFAULT 0,
            notes TEXT,
            recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (live_class_id) REFERENCES live_classes(id) ON DELETE CASCADE,
            FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
            UNIQUE KEY unique_student_class (live_class_id, student_id)
        )"
    ];

    echo "<h3>Creating LMS Tables...</h3>";
    $created_tables = [];
    
    foreach ($lms_tables_sql as $table_name => $sql) {
        try {
            $pdo->exec($sql);
            echo "<p style='color: green;'>✅ $table_name table - OK</p>";
            $created_tables[] = $table_name;
        } catch (Exception $e) {
            echo "<p style='color: red;'>❌ Error creating $table_name table: " . $e->getMessage() . "</p>";
        }
    }

    // Check login status
    session_start();
    if (isset($_SESSION['user_id'])) {
        echo "<p style='color: green;'>✅ You are currently logged in as: {$_SESSION['username']} (Role: {$_SESSION['user_role']})</p>";
    } else {
        echo "<p style='color: orange;'>⚠️ You are NOT logged in. Please log in first.</p>";
    }

    echo "<h3>LMS Management Pages:</h3>";
    echo "<ul>";
    echo "<li><a href='admin/lms/index.php'>🎓 LMS Dashboard</a></li>";
    echo "<li><a href='admin/lms/courses.php'>📚 Courses Management</a></li>";
    echo "<li><a href='admin/lms/live_classes.php'>💻 Live Classes</a></li>";
    echo "<li><a href='admin/lms/assignments.php'>📝 Assignments</a></li>";
    echo "<li><a href='admin/lms/student_progress.php'>📈 Student Progress</a></li>";
    echo "</ul>";

} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Error: " . $e->getMessage() . "</p>";
}

echo "<h3>Quick Actions:</h3>";
echo "<ul>";
echo "<li><a href='force_login.php'>🔐 Force Login as Admin</a></li>";
echo "<li><a href='login.php'>🔐 Normal Login Page</a> (Default: admin/admin123)</li>";
echo "<li><a href='index.php'>🏠 Home Page</a></li>";
echo "<li><a href='fix_transport_system.php'>🚌 Fix Transport System</a></li>";
echo "<li><a href='fix_hostel_system.php'>🏨 Fix Hostel System</a></li>";
echo "</ul>";

echo "<p><strong>Note:</strong> If LMS pages still don't load after fixing tables, make sure you're logged in first.</p>";
?>