<?php

namespace App\Controllers;

class TeacherController {
    private $pdo;
    private $config;
    
    public function __construct($pdo, $config) {
        $this->pdo = $pdo;
        $this->config = $config;
    }
    
    public function dashboard() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $userId = current_user()['id'];
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM courses WHERE created_by = ?");
        $stmt->execute([$userId]);
        $myCourses = $stmt->fetchColumn();
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM exercises WHERE module_id IN (SELECT m.id FROM modules m JOIN courses c ON m.course_id = c.id WHERE c.created_by = ?)");
        $stmt->execute([$userId]);
        $pendingMarking = $stmt->fetchColumn();
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM tests WHERE created_by = ? AND is_published = 1");
        $stmt->execute([$userId]);
        $activeTests = $stmt->fetchColumn();
        
        $stmt = $this->pdo->prepare("SELECT ta.*, t.title as test_title, u.first_name, u.last_name FROM test_attempts ta JOIN tests t ON ta.test_id = t.id JOIN students s ON ta.student_id = s.id JOIN users u ON s.user_id = u.id WHERE t.created_by = ? AND ta.status = 'completed' ORDER BY ta.ended_at DESC LIMIT 10");
        $stmt->execute([$userId]);
        $recentAttempts = $stmt->fetchAll();
        
        $stmt = $this->pdo->query("SELECT * FROM announcements WHERE (target_roles IS NULL OR target_roles = '[]' OR target_roles LIKE '%\"teacher\"%') AND (expires_at IS NULL OR expires_at > NOW()) ORDER BY is_pinned DESC, created_at DESC LIMIT 5");
        $announcements = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/dashboard.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function courses() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $userId = current_user()['id'];
        
        $stmt = $this->pdo->prepare("SELECT c.*, cc.name as category_name FROM courses c LEFT JOIN course_categories cc ON c.category_id = cc.id WHERE c.created_by = ? ORDER BY c.created_at DESC");
        $stmt->execute([$userId]);
        $courses = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/courses.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function courseCreate() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $error = '';
        $success = '';
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                $error = 'Invalid request.';
            } else {
                $title = trim($_POST['title'] ?? '');
                $slug = strtolower(trim(preg_replace('/[^a-z0-9]+/', '-', $title), '-'));
                $subtitle = trim($_POST['subtitle'] ?? '');
                $description = trim($_POST['description'] ?? '');
                $categoryId = $_POST['category_id'] ?? null;
                $levelId = $_POST['level_id'] ?? null;
                $duration = $_POST['duration_hours'] ?? 0;
                $passMark = $_POST['pass_mark'] ?? 50;
                $certEligible = isset($_POST['certificate_eligible']) ? 1 : 0;
                
                if (empty($title)) {
                    $error = 'Course title is required.';
                } else {
                    $stmt = $this->pdo->prepare("INSERT INTO courses (category_id, level_id, title, slug, subtitle, description, duration_hours, pass_mark, certificate_eligible, created_by, is_published) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)");
                    $stmt->execute([$categoryId, $levelId, $title, $slug, $subtitle, $description, $duration, $passMark, $certEligible, current_user()['id']]);
                    $success = 'Course created successfully!';
                }
            }
        }
        
        $stmt = $this->pdo->query("SELECT * FROM course_categories WHERE is_active = 1");
        $categories = $stmt->fetchAll();
        
        $stmt = $this->pdo->query("SELECT * FROM course_levels");
        $levels = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/course_create.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function modules($courseId) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $stmt = $this->pdo->prepare("SELECT * FROM courses WHERE id = ? AND created_by = ?");
        $stmt->execute([$courseId, current_user()['id']]);
        $course = $stmt->fetch();
        
        if (!$course) {
            http_response_code(403);
            require_once __DIR__ . '/../Views/errors/403.php';
            exit;
        }
        
        $stmt = $this->pdo->prepare("SELECT * FROM modules WHERE course_id = ? ORDER BY sort_order");
        $stmt->execute([$courseId]);
        $modules = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/modules.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function lessonCreate($courseId, $moduleId) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $stmt = $this->pdo->prepare("SELECT m.*, c.created_by FROM modules m JOIN courses c ON m.course_id = c.id WHERE m.id = ?");
        $stmt->execute([$moduleId]);
        $module = $stmt->fetch();
        
        if (!$module || $module['created_by'] != current_user()['id']) {
            http_response_code(403);
            require_once __DIR__ . '/../Views/errors/403.php';
            exit;
        }
        
        $error = '';
        $success = '';
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                $error = 'Invalid request.';
            } else {
                $title = trim($_POST['title'] ?? '');
                $slug = strtolower(trim(preg_replace('/[^a-z0-9]+/', '-', $title), '-'));
                $content = $_POST['content'] ?? '';
                $lessonType = $_POST['lesson_type'] ?? 'text';
                $sortOrder = $_POST['sort_order'] ?? 0;
                $isPublished = isset($_POST['is_published']) ? 1 : 0;
                
                if (empty($title)) {
                    $error = 'Lesson title is required.';
                } else {
                    $stmt = $this->pdo->prepare("INSERT INTO lessons (module_id, title, slug, content, lesson_type, sort_order, is_published, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$moduleId, $title, $slug, $content, $lessonType, $sortOrder, $isPublished, current_user()['id']]);
                    $success = 'Lesson created successfully!';
                }
            }
        }
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/lesson_create.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function tests() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $userId = current_user()['id'];
        
        $stmt = $this->pdo->prepare("SELECT t.*, c.title as course_title FROM tests t JOIN courses c ON t.course_id = c.id WHERE t.created_by = ? ORDER BY t.created_at DESC");
        $stmt->execute([$userId]);
        $tests = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/tests.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function marking() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $userId = current_user()['id'];
        
        $stmt = $this->pdo->prepare("SELECT es.*, u.first_name, u.last_name, e.title as exercise_title, c.title as course_title FROM exercise_submissions es JOIN students s ON es.student_id = s.id JOIN users u ON s.user_id = u.id JOIN exercises e ON es.exercise_id = e.id JOIN modules m ON e.module_id = m.id JOIN courses c ON m.course_id = c.id WHERE c.created_by = ? AND es.status = 'submitted' ORDER BY es.submitted_at DESC");
        $stmt->execute([$userId]);
        $submissions = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/marking.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function gradeSubmission($submissionId) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $stmt = $this->pdo->prepare("SELECT es.* FROM exercise_submissions es JOIN exercises e ON es.exercise_id = e.id JOIN modules m ON e.module_id = m.id JOIN courses c ON m.course_id = c.id WHERE es.id = ? AND c.created_by = ?");
        $stmt->execute([$submissionId, current_user()['id']]);
        $submission = $stmt->fetch();
        
        if (!$submission) {
            http_response_code(403);
            require_once __DIR__ . '/../Views/errors/403.php';
            exit;
        }
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                flash('error', 'Invalid request.');
            } else {
                $score = (int)$_POST['score'];
                $feedback = trim($_POST['feedback'] ?? '');
                $status = $score >= 50 ? 'graded' : 'returned';
                
                $this->pdo->prepare("UPDATE exercise_submissions SET score = ?, feedback = ?, status = ?, graded_at = NOW(), graded_by = ? WHERE id = ?")
                    ->execute([$score, $feedback, $status, current_user()['id'], $submissionId]);
                
                flash('success', 'Submission graded successfully.');
                redirect(base_url('teacher/marking'));
            }
        }
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/grade_submission.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function students() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $userId = current_user()['id'];
        
        $stmt = $this->pdo->prepare("SELECT s.*, u.first_name, u.last_name, u.email FROM students s JOIN users u ON s.user_id = u.id JOIN enrollments e ON s.id = e.student_id JOIN courses c ON e.course_id = c.id WHERE c.created_by = ? GROUP BY s.id ORDER BY s.created_at DESC");
        $stmt->execute([$userId]);
        $students = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/students.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function reports() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $userId = current_user()['id'];
        
        $stmt = $this->pdo->prepare("SELECT c.id, c.title, COUNT(DISTINCT e.student_id) as student_count, AVG(ta.score) as avg_score FROM courses c LEFT JOIN enrollments e ON c.id = e.course_id LEFT JOIN tests t ON c.id = t.course_id LEFT JOIN test_attempts ta ON t.id = ta.test_id AND ta.status = 'completed' WHERE c.created_by = ? GROUP BY c.id ORDER BY c.created_at DESC");
        $stmt->execute([$userId]);
        $reports = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/reports.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function announcements() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $error = '';
        $success = '';
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                $error = 'Invalid request.';
            } else {
                $title = trim($_POST['title'] ?? '');
                $content = trim($_POST['content'] ?? '');
                $targetRoles = $_POST['target_roles'] ?? [];
                $isPinned = isset($_POST['is_pinned']) ? 1 : 0;
                
                if (empty($title) || empty($content)) {
                    $error = 'Title and content are required.';
                } else {
                    $this->pdo->prepare("INSERT INTO announcements (title, content, target_roles, is_pinned, created_by) VALUES (?, ?, ?, ?, ?)")
                        ->execute([$title, $content, json_encode($targetRoles), $isPinned, current_user()['id']]);
                    $success = 'Announcement created successfully.';
                }
            }
        }
        
        $stmt = $this->pdo->prepare("SELECT * FROM announcements WHERE created_by = ? ORDER BY created_at DESC");
        $stmt->execute([current_user()['id']]);
        $announcements = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/announcements.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function support() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $userId = current_user()['id'];
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                flash('error', 'Invalid request.');
            } else {
                $subject = trim($_POST['subject'] ?? '');
                $message = trim($_POST['message'] ?? '');
                
                if (empty($subject) || empty($message)) {
                    flash('error', 'Please fill all fields.');
                } else {
                    $stmt = $this->pdo->prepare("INSERT INTO support_tickets (user_id, subject, message, status) VALUES (?, ?, ?, 'open')");
                    $stmt->execute([$userId, $subject, $message]);
                    flash('success', 'Support ticket created.');
                    redirect(base_url('teacher/support'));
                }
            }
        }
        
        $stmt = $this->pdo->prepare("SELECT * FROM support_tickets WHERE user_id = ? ORDER BY created_at DESC");
        $stmt->execute([$userId]);
        $tickets = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/support.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function questionBanks() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['teacher']);
        
        $stmt = $this->pdo->prepare("SELECT qb.*, COUNT(q.id) as question_count FROM question_banks qb LEFT JOIN questions q ON qb.id = q.bank_id WHERE qb.created_by = ? GROUP BY qb.id ORDER BY qb.created_at DESC");
        $stmt->execute([current_user()['id']]);
        $banks = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/teacher.php';
        include __DIR__ . '/../Views/teacher/question_banks.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
}
