<?php

namespace App\Controllers;

class StudentController {
    private $pdo;
    private $config;
    
    public function __construct($pdo, $config) {
        $this->pdo = $pdo;
        $this->config = $config;
    }
    
    private function getStudentId() {
        $user = current_user();
        $stmt = $this->pdo->prepare("SELECT id FROM students WHERE user_id = ?");
        $stmt->execute([$user['id']]);
        return $stmt->fetchColumn();
    }
    
    public function dashboard() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        $userId = current_user()['id'];
        
        $stmt = $this->pdo->prepare("SELECT s.*, u.first_name, u.last_name, u.email, u.phone, u.whatsapp, p.name as package_name FROM students s JOIN users u ON s.user_id = u.id LEFT JOIN packages p ON s.current_package_id = p.id WHERE s.user_id = ?");
        $stmt->execute([$userId]);
        $student = $stmt->fetch();
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE student_id = ? AND status = 'active'");
        $stmt->execute([$studentId]);
        $activeCourses = $stmt->fetchColumn();
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM test_attempts WHERE student_id = ? AND status = 'completed'");
        $stmt->execute([$studentId]);
        $testsCompleted = $stmt->fetchColumn();
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM certificates WHERE student_id = ? AND status = 'issued'");
        $stmt->execute([$studentId]);
        $certificates = $stmt->fetchColumn();
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM payments WHERE student_id = ? AND status = 'pending'");
        $stmt->execute([$studentId]);
        $pendingPayments = $stmt->fetchColumn();
        
        $stmt = $this->pdo->prepare("SELECT e.*, c.title as course_title, c.thumbnail FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = ? AND e.status = 'active' ORDER BY e.enrolled_at DESC LIMIT 5");
        $stmt->execute([$studentId]);
        $enrollments = $stmt->fetchAll();
        
        $stmt = $this->pdo->query("SELECT * FROM announcements WHERE (target_roles IS NULL OR target_roles = '[]' OR target_roles LIKE '%\"student\"%') 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/student.php';
        include __DIR__ . '/../Views/student/dashboard.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function courses() { return $this->myCourses(); }
    
    public function profile() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        $userId = current_user()['id'];
        
        $stmt = $this->pdo->prepare("SELECT s.*, u.first_name, u.last_name, u.email, u.phone, u.whatsapp, u.bio FROM students s JOIN users u ON s.user_id = u.id WHERE s.user_id = ?");
        $stmt->execute([$userId]);
        $student = $stmt->fetch();
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                flash('error', 'Invalid request.');
            } else {
                $firstName = trim($_POST['first_name'] ?? '');
                $lastName = trim($_POST['last_name'] ?? '');
                $phone = trim($_POST['phone'] ?? '');
                $whatsapp = trim($_POST['whatsapp'] ?? '');
                $bio = trim($_POST['bio'] ?? '');
                
                $this->pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, phone = ?, whatsapp = ?, bio = ? WHERE id = ?")
                    ->execute([$firstName, $lastName, $phone, $whatsapp, $bio, $userId]);
                
                flash('success', 'Profile updated successfully.');
                redirect(base_url('student/profile'));
            }
        }
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/profile.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function myCourses() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT e.*, c.title as course_title, c.subtitle, c.thumbnail, c.duration_hours FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = ? AND e.status = 'active' ORDER BY e.enrolled_at DESC");
        $stmt->execute([$studentId]);
        $enrollments = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/courses.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function courseView($courseSlug) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT c.* FROM courses c JOIN enrollments e ON c.id = e.course_id WHERE c.slug = ? AND e.student_id = ? AND e.status = 'active'");
        $stmt->execute([$courseSlug, $studentId]);
        $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 = ? AND is_published = 1 ORDER BY sort_order");
        $stmt->execute([$course['id']]);
        $modules = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/course_view.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function lesson($moduleSlug, $lessonSlug) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT l.*, m.course_id, c.title as course_title FROM lessons l JOIN modules m ON l.module_id = m.id JOIN courses c ON m.course_id = c.id JOIN enrollments e ON c.id = e.course_id WHERE l.slug = ? AND m.slug = ? AND e.student_id = ? AND e.status = 'active'");
        $stmt->execute([$lessonSlug, $moduleSlug, $studentId]);
        $lesson = $stmt->fetch();
        
        if (!$lesson) {
            http_response_code(403);
            require_once __DIR__ . '/../Views/errors/403.php';
            exit;
        }
        
        $this->pdo->prepare("INSERT IGNORE INTO activity_logs (user_id, student_id, activity_type, description, metadata) VALUES (?, ?, 'lesson_view', ?, ?)")
            ->execute([current_user()['id'], $studentId, 'Viewed lesson: ' . $lesson['title'], json_encode(['lesson_id' => $lesson['id']])]);
        
        $stmt = $this->pdo->prepare("SELECT * FROM lesson_files WHERE lesson_id = ? ORDER BY sort_order");
        $stmt->execute([$lesson['id']]);
        $files = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/lesson.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function tests() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT ta.*, t.title as test_title, t.duration_minutes, t.pass_mark, c.title as course_title FROM test_attempts ta JOIN tests t ON ta.test_id = t.id JOIN courses c ON t.course_id = c.id WHERE ta.student_id = ? ORDER BY ta.created_at DESC LIMIT 20");
        $stmt->execute([$studentId]);
        $attempts = $stmt->fetchAll();
        
        $stmt = $this->pdo->prepare("SELECT t.*, c.title as course_title, (SELECT COUNT(*) FROM test_attempts WHERE test_id = t.id AND student_id = ? AND status = 'completed') as attempts_made FROM tests t JOIN courses c ON t.course_id = c.id JOIN enrollments e ON c.id = e.course_id WHERE e.student_id = ? AND e.status = 'active' AND t.is_published = 1 AND t.test_type IN ('quiz', 'cbt', 'final_exam') ORDER BY t.created_at DESC");
        $stmt->execute([$studentId, $studentId]);
        $availableTests = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/tests.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    private function loadAttemptQuestions($attemptId) {
        $stmt = $this->pdo->prepare("SELECT q.*, taq.options_order_json FROM test_attempt_questions taq JOIN questions q ON taq.question_id = q.id WHERE taq.attempt_id = ? ORDER BY taq.sort_order");
        $stmt->execute([$attemptId]);
        $questions = $stmt->fetchAll();
        foreach ($questions as &$question) {
            $optionIds = json_decode($question['options_order_json'] ?? '[]', true) ?: [];
            if ($optionIds) {
                $placeholders = implode(',', array_fill(0, count($optionIds), '?'));
                $stmt = $this->pdo->prepare("SELECT * FROM question_options WHERE id IN ($placeholders) ORDER BY FIELD(id, $placeholders)");
                $stmt->execute(array_merge($optionIds, $optionIds));
            } else {
                $stmt = $this->pdo->prepare("SELECT * FROM question_options WHERE question_id = ? ORDER BY sort_order");
                $stmt->execute([$question['id']]);
            }
            $question['options'] = $stmt->fetchAll();
        }
        return $questions;
    }

    private function assignAttemptQuestions($attemptId, array $test): array {
        $existing = $this->loadAttemptQuestions($attemptId);
        if ($existing) return $existing;

        $stmt = $this->pdo->prepare("SELECT ts.*, qb.id as bank_id FROM test_sections ts LEFT JOIN question_banks qb ON ts.bank_id = qb.id WHERE ts.test_id = ? ORDER BY ts.sort_order");
        $stmt->execute([$test['id']]);
        $sections = $stmt->fetchAll();

        $sortOrder = 1;
        foreach ($sections as $section) {
            if (!$section['bank_id']) continue;
            $sql = "SELECT q.* FROM questions q WHERE q.bank_id = ?";
            $params = [$section['bank_id']];
            if ($section['difficulty_filter'] !== 'all') {
                $sql .= " AND q.difficulty = ?";
                $params[] = $section['difficulty_filter'];
            }
            $sql .= $test['randomize_questions'] ? " ORDER BY RAND()" : " ORDER BY q.id";
            $sql .= " LIMIT " . (int)$section['question_count'];
            $stmt = $this->pdo->prepare($sql);
            $stmt->execute($params);
            foreach ($stmt->fetchAll() as $question) {
                $optionSql = "SELECT id FROM question_options WHERE question_id = ?" . ($test['randomize_answers'] ? " ORDER BY RAND()" : " ORDER BY sort_order");
                $optStmt = $this->pdo->prepare($optionSql);
                $optStmt->execute([$question['id']]);
                $optionIds = $optStmt->fetchAll(\PDO::FETCH_COLUMN);
                $this->pdo->prepare("INSERT INTO test_attempt_questions (attempt_id, question_id, sort_order, options_order_json) VALUES (?, ?, ?, ?)")
                    ->execute([$attemptId, $question['id'], $sortOrder++, json_encode(array_map('intval', $optionIds))]);
            }
        }

        return $this->loadAttemptQuestions($attemptId);
    }

    public function takeTest($testId, $attemptSegment = null, $attemptIdParam = null) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT * FROM tests WHERE id = ? AND is_published = 1");
        $stmt->execute([$testId]);
        $test = $stmt->fetch();
        
        if (!$test) {
            http_response_code(404);
            require_once __DIR__ . '/../Views/errors/404.php';
            exit;
        }
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM enrollments WHERE student_id = ? AND course_id = ? AND status = 'active'");
        $stmt->execute([$studentId, $test['course_id']]);
        if (!$stmt->fetchColumn()) {
            http_response_code(403);
            require_once __DIR__ . '/../Views/errors/403.php';
            exit;
        }
        
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM test_attempts WHERE test_id = ? AND student_id = ? AND status IN ('completed', 'auto_submitted')");
        $stmt->execute([$testId, $studentId]);
        $attemptsMade = $stmt->fetchColumn();
        
        if ($attemptsMade >= $test['max_attempts']) {
            flash('error', 'You have reached the maximum number of attempts for this test.');
            redirect(base_url('student/tests'));
        }
        
        $stmt = $this->pdo->prepare("SELECT id FROM test_attempts WHERE test_id = ? AND student_id = ? AND status = 'in_progress' LIMIT 1");
        $stmt->execute([$testId, $studentId]);
        $existingAttempt = $stmt->fetch();
        
        if ($existingAttempt && !$attemptIdParam) {
            redirect(base_url('student/take-test/' . $testId . '/attempt/' . $existingAttempt['id']));
        }

        if ($attemptIdParam) {
            $attemptId = (int)$attemptIdParam;
            $stmt = $this->pdo->prepare("SELECT * FROM test_attempts WHERE id = ? AND test_id = ? AND student_id = ? AND status = 'in_progress'");
            $stmt->execute([$attemptId, $testId, $studentId]);
            if (!$stmt->fetch()) {
                flash('error', 'No active test session found.');
                redirect(base_url('student/tests'));
            }
        } else {
            $attemptNumber = $attemptsMade + 1;
            $stmt = $this->pdo->prepare("INSERT INTO test_attempts (test_id, student_id, attempt_number, started_at, status, ip_address, user_agent) VALUES (?, ?, ?, NOW(), 'in_progress', ?, ?)");
            $stmt->execute([$testId, $studentId, $attemptNumber, $_SERVER['REMOTE_ADDR'] ?? '', $_SERVER['HTTP_USER_AGENT'] ?? '']);
            $attemptId = $this->pdo->lastInsertId();
        }
        $questions = $this->assignAttemptQuestions($attemptId, $test);
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/take_test.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function submitTest($testId) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT ta.*, t.pass_mark as test_pass_mark, t.certificate_trigger, t.course_id, t.negative_marking, t.negative_mark_value FROM test_attempts ta JOIN tests t ON ta.test_id = t.id WHERE ta.test_id = ? AND ta.student_id = ? AND ta.status = 'in_progress' LIMIT 1");
        $stmt->execute([$testId, $studentId]);
        $attempt = $stmt->fetch();
        
        if (!$attempt) {
            flash('error', 'No active test session found.');
            redirect(base_url('student/tests'));
        }
        
        $answers = $_POST['answers'] ?? [];
        $score = 0;
        $maxScore = 0;
        $correctCount = 0;
        $totalQuestions = 0;
        
        $assigned = $this->loadAttemptQuestions($attempt['id']);
        $assignedIds = array_map(fn($q) => (int)$q['id'], $assigned);

        foreach ($answers as $questionId => $selectedOptionId) {
            if (!in_array((int)$questionId, $assignedIds, true)) continue;
            $totalQuestions++;
            $stmt = $this->pdo->prepare("SELECT points FROM questions WHERE id = ?");
            $stmt->execute([$questionId]);
            $points = (int)($stmt->fetchColumn() ?: 1);
            $maxScore += $points;
            
            $stmt = $this->pdo->prepare("SELECT qo.is_correct FROM question_options qo WHERE qo.id = ? AND qo.question_id = ?");
            $stmt->execute([$selectedOptionId, $questionId]);
            $isCorrect = $stmt->fetchColumn();
            
            if ($isCorrect) {
                $score += $points;
                $correctCount++;
            }
            
            $this->pdo->prepare("INSERT INTO test_attempt_answers (attempt_id, question_id, selected_option_id, is_correct, points_awarded) VALUES (?, ?, ?, ?, ?)")
                ->execute([$attempt['id'], $questionId, $selectedOptionId, $isCorrect ? 1 : 0, $isCorrect ? $points : 0]);
        }
        
        $finalScore = $maxScore > 0 ? round(($score / $maxScore) * 100, 2) : 0;
        $passed = $finalScore >= (int)$attempt['test_pass_mark'];
        
        $this->pdo->prepare("UPDATE test_attempts SET status = 'completed', ended_at = NOW(), time_spent = ?, score = ?, max_score = ?, pass_mark = ?, passed = ? WHERE id = ?")
            ->execute([time() - strtotime($attempt['started_at']), $finalScore, $maxScore, (int)$attempt['test_pass_mark'], $passed ? 1 : 0, $attempt['id']]);
        
        if ($passed && (int)$attempt['certificate_trigger'] === 1) {
            $courseId = $attempt['course_id'];
            $certIssued = false;
            $this->issueCertificate($studentId, $courseId);
            $certIssued = true;
            
            log_activity(current_user()['id'], 'test_passed', 'Student passed test: ' . $testId, ['score' => $finalScore, 'certificate_issued' => $certIssued], $studentId);
        }
        
        flash('success', 'Test submitted successfully! Your score: ' . $finalScore . '%');
        redirect(base_url('student/test-result/' . $attempt['id']));
    }
    
    private function issueCertificate($studentId, $courseId) {
        $stmt = $this->pdo->prepare("SELECT s.student_number, u.first_name, u.last_name, c.title as course_name FROM students s JOIN users u ON s.user_id = u.id JOIN courses c ON c.id = ? WHERE s.id = ?");
        $stmt->execute([$courseId, $studentId]);
        $data = $stmt->fetch();
        
        if (!$data) return;
        
        $certNumber = generate_certificate_number($this->pdo);
        
        $qrPath = 'storage/certificates/qr-' . $certNumber . '.png';
        $dir = dirname(__DIR__ . '/../' . $qrPath);
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        
        $qrFile = __DIR__ . '/../../' . $qrPath;
        $qrData = base_url('verify?number=' . $certNumber);
        if (class_exists('Endroid\\QrCode\\Writer\\PngWriter') && method_exists('Endroid\\QrCode\\QrCode', 'create')) {
            $qrCodeClass = 'Endroid\\QrCode\\QrCode';
            $writerClass = 'Endroid\\QrCode\\Writer\\PngWriter';
            $qr = $qrCodeClass::create($qrData)->setSize(200)->setMargin(10);
            (new $writerClass())->write($qr)->saveToFile($qrFile);
        } else {
            $qrCodeClass = 'Endroid\\QrCode\\QrCode';
            if (!class_exists($qrCodeClass)) {
                error_log('Endroid QR Code is not installed; certificate QR was skipped.');
                $qrPath = null;
            } else {
            $qr = new $qrCodeClass($qrData);
            if (method_exists($qr, 'setSize')) $qr->setSize(200);
            if (method_exists($qr, 'setMargin')) $qr->setMargin(10);
            if (method_exists($qr, 'writeFile')) $qr->writeFile($qrFile);
            }
        }
        
        $stmt = $this->pdo->prepare("INSERT INTO certificates (certificate_number, student_id, course_id, student_name, course_name, issue_date, qr_code_path, status, issued_by) VALUES (?, ?, ?, ?, ?, CURDATE(), ?, 'issued', ?)");
        $stmt->execute([$certNumber, $studentId, $courseId, $data['first_name'] . ' ' . $data['last_name'], $data['course_name'], $qrPath, current_user()['id']]);
        
        $certId = $this->pdo->lastInsertId();
        $this->generateCertificatePDF($certId);
        
        $body = '<h2>Congratulations!</h2><p>Dear ' . e($data['first_name'] . ' ' . $data['last_name']) . ',</p><p>You have successfully completed <strong>' . e($data['course_name']) . '</strong>. Your certificate has been issued.</p><p>Certificate Number: <strong>' . $certNumber . '</strong></p><p>Download it from your dashboard.</p>';
        send_email(current_user()['email'], 'Certificate Issued - CIX Orbit Academy', $body);
    }
    
    private function generateCertificatePDF($certId) {
        $stmt = $this->pdo->prepare("SELECT * FROM certificates WHERE id = ?");
        $stmt->execute([$certId]);
        $cert = $stmt->fetch();
        
        if (!$cert) return;
        
        $mpdf = new \Mpdf\Mpdf(['margin_left' => 15, 'margin_right' => 15, 'margin_top' => 20, 'margin_bottom' => 20]);
        
        $qrImage = $cert['qr_code_path'] ? realpath(__DIR__ . '/../../' . $cert['qr_code_path']) : '';
        $html = '<!DOCTYPE html><html><head><style>
            body { font-family: DejaVu Sans, sans-serif; text-align: center; }
            .certificate { border: 8px solid #ff6b00; padding: 40px; position: relative; }
            .watermark { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(-30deg); font-size: 80px; color: rgba(255,107,0,0.08); white-space: nowrap; pointer-events: none; }
            h1 { font-size: 36px; color: #000; margin-bottom: 10px; }
            h2 { font-size: 24px; color: #333; margin-bottom: 30px; }
            .student-name { font-size: 32px; font-weight: bold; color: #ff6b00; margin: 20px 0; }
            .course-name { font-size: 22px; color: #333; margin: 20px 0; }
            .details { font-size: 14px; color: #666; margin: 30px 0; }
            .qr { margin: 20px auto; display: block; }
            .footer { margin-top: 40px; font-size: 12px; color: #999; }
            .seal { width: 100px; height: 100px; border-radius: 50%; background: #ff6b00; margin: 20px auto; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; }
        </style></head><body>
            <div class="certificate">
                <div class="watermark">CIX ORBIT ACADEMY</div>
                <h1>Certificate of Completion</h1>
                <h2>This is to certify that</h2>
                <div class="student-name">' . e($cert['student_name']) . '</div>
                <h2>has successfully completed the course</h2>
                <div class="course-name">' . e($cert['course_name']) . '</div>
                <div class="details">
                    Certificate Number: ' . e($cert['certificate_number']) . '<br>
                    Issue Date: ' . e($cert['issue_date']) . '<br>
                    Student Number: ' . e($cert['student_number'] ?? '') . '<br>
                    Final Mark: ' . e($cert['final_mark'] ?? 'N/A') . '%<br>
                    Verification: ' . base_url('verify') . '
                </div>
                ' . ($qrImage ? '<img src="' . e($qrImage) . '" class="qr" width="120">' : '') . '
                <div class="seal">CIX</div>
                <div class="footer">
                    <p>Powered by CIX Connect | ' . e(get_setting('academy_url', '')) . '</p>
                    <p>Academic Email: ' . e(get_setting('academic_email', '')) . ' | Office: ' . e(get_setting('office_phone', '')) . '</p>
                </div>
            </div>
        </body></html>';
        
        $mpdf->WriteHTML($html);
        $pdfPath = 'storage/certificates/cert-' . $cert['certificate_number'] . '.pdf';
        $mpdf->Output(__DIR__ . '/../../' . $pdfPath, \Mpdf\Output\Destination::FILE);
        
        $this->pdo->prepare("UPDATE certificates SET pdf_path = ? WHERE id = ?")->execute([$pdfPath, $certId]);
    }
    
    public function payments() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        $stmt = $this->pdo->prepare("SELECT s.*, u.first_name, u.last_name, u.email, p.name as package_name, p.price, p.currency FROM students s JOIN users u ON s.user_id = u.id LEFT JOIN packages p ON s.current_package_id = p.id WHERE s.id = ?");
        $stmt->execute([$studentId]);
        $student = $stmt->fetch();

        if (isset($_GET['regenerate']) && $student && $student['current_package_id']) {
            $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM payments WHERE student_id = ? AND status IN ('pending', 'awaiting_proof', 'submitted')");
            $stmt->execute([$studentId]);
            if (!$stmt->fetchColumn()) {
                $this->pdo->prepare("INSERT INTO payments (student_id, package_id, amount, currency, status, reference_number, notes) VALUES (?, ?, ?, ?, 'awaiting_proof', ?, 'Regenerated from student portal')")
                    ->execute([$studentId, $student['current_package_id'], $student['price'] ?? 0, $student['currency'] ?? 'ZAR', $student['student_number']]);
                log_audit(current_user()['id'], 'payment_instruction_regenerate', 'student', $studentId);
                flash('success', 'Payment instruction regenerated.');
            }
            redirect(base_url('student/payments'));
        }
        
        $stmt = $this->pdo->prepare("SELECT p.*, pk.name as package_name FROM payments p LEFT JOIN packages pk ON p.package_id = pk.id WHERE p.student_id = ? ORDER BY p.created_at DESC");
        $stmt->execute([$studentId]);
        $payments = $stmt->fetchAll();
        $bankDetails = get_bank_details();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/payments.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function uploadProof() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                flash('error', 'Invalid request.');
            } else {
                $paymentId = $_POST['payment_id'] ?? '';
                $stmt = $this->pdo->prepare("SELECT * FROM payments WHERE id = ? AND student_id = ? AND status IN ('pending', 'awaiting_proof', 'rejected') LIMIT 1");
                $stmt->execute([$paymentId, $studentId]);
                $payment = $stmt->fetch();
                
                if (!$payment) {
                    flash('error', 'No payment record found for this proof upload. Regenerate your payment instruction or contact admin.');
                } elseif (empty($_FILES['proof_file']['name'])) {
                    flash('error', 'Please select a file.');
                } else {
                    $allowed = get_setting('upload_allowed_proofs', 'pdf,jpg,jpeg,png,doc,docx');
                    $allowed = explode(',', $allowed);
                    $result = upload_file($_FILES['proof_file'], $allowed, __DIR__ . '/../../public/uploads');
                    
                    if ($result['success']) {
                        $stmt = $this->pdo->prepare("INSERT INTO payment_proofs (payment_id, student_id, file_path, file_name, file_size, file_type, status) VALUES (?, ?, ?, ?, ?, ?, 'submitted')");
                        $stmt->execute([$paymentId, $studentId, 'uploads/' . $result['filename'], $result['filename'], $result['size'] ?? 0, mime_content_type($result['path'])]);
                        
                        $this->pdo->prepare("UPDATE payments SET status = 'submitted' WHERE id = ? AND student_id = ?")->execute([$paymentId, $studentId]);
                        log_audit(current_user()['id'], 'payment_proof_upload', 'payment', (int)$paymentId);
                        
                        flash('success', 'Proof of payment uploaded successfully.');
                        redirect(base_url('student/payments'));
                    } else {
                        flash('error', $result['error']);
                    }
                }
            }
        }
        
        redirect(base_url('student/payments'));
    }
    
    public function certificates() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT c.*, cr.title as course_title FROM certificates c JOIN courses cr ON c.course_id = cr.id WHERE c.student_id = ? AND c.status = 'issued' ORDER BY c.issue_date DESC");
        $stmt->execute([$studentId]);
        $certs = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/certificates.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function results() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT ta.*, t.title as test_title, t.pass_mark, c.title as course_title FROM test_attempts ta JOIN tests t ON ta.test_id = t.id JOIN courses c ON t.course_id = c.id WHERE ta.student_id = ? AND ta.status = 'completed' ORDER BY ta.ended_at DESC");
        $stmt->execute([$studentId]);
        $results = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/results.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function assignments() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT a.*, c.title as course_title, (SELECT status FROM assignment_submissions WHERE assignment_id = a.id AND student_id = ?) as submission_status, (SELECT score FROM assignment_submissions WHERE assignment_id = a.id AND student_id = ?) as submission_score FROM assignments a JOIN courses c ON a.course_id = c.id JOIN enrollments e ON c.id = e.course_id WHERE e.student_id = ? AND e.status = 'active' AND a.is_published = 1 ORDER BY a.due_date ASC");
        $stmt->execute([$studentId, $studentId, $studentId]);
        $assignments = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/assignments.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function support() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf_token'] ?? '')) {
                flash('error', 'Invalid request.');
            } else {
                $subject = trim($_POST['subject'] ?? '');
                $message = trim($_POST['message'] ?? '');
                $priority = $_POST['priority'] ?? 'medium';
                
                if (empty($subject) || empty($message)) {
                    flash('error', 'Please fill all fields.');
                } else {
                    $stmt = $this->pdo->prepare("INSERT INTO support_tickets (student_id, user_id, subject, priority, message, status) VALUES (?, ?, ?, ?, ?, 'open')");
                    $stmt->execute([$studentId, current_user()['id'], $subject, $priority, $message]);
                    
                    flash('success', 'Support ticket created successfully.');
                    redirect(base_url('student/support'));
                }
            }
        }
        
        $stmt = $this->pdo->prepare("SELECT * FROM support_tickets WHERE student_id = ? ORDER BY created_at DESC");
        $stmt->execute([$studentId]);
        $tickets = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/support.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function announcement($id) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $stmt = $this->pdo->prepare("SELECT * FROM announcements WHERE id = ? AND (expires_at IS NULL OR expires_at > NOW())");
        $stmt->execute([$id]);
        $announcement = $stmt->fetch();
        
        if (!$announcement) {
            http_response_code(404);
            require_once __DIR__ . '/../Views/errors/404.php';
            exit;
        }
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/announcement.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function announcements() {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $stmt = $this->pdo->query("SELECT * FROM announcements WHERE (target_roles IS NULL OR target_roles = '[]' OR target_roles LIKE '%\"student\"%') AND (expires_at IS NULL OR expires_at > NOW()) ORDER BY is_pinned DESC, created_at DESC");
        $announcements = $stmt->fetchAll();
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/announcements.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
    
    public function testResult($attemptId) {
        \App\Middleware\AuthMiddleware::requireAuth();
        \App\Middleware\AuthMiddleware::requireRole(['student']);
        
        $studentId = $this->getStudentId();
        
        $stmt = $this->pdo->prepare("SELECT ta.*, t.title as test_title FROM test_attempts ta JOIN tests t ON ta.test_id = t.id WHERE ta.id = ? AND ta.student_id = ?");
        $stmt->execute([$attemptId, $studentId]);
        $attempt = $stmt->fetch();
        
        if (!$attempt) {
            http_response_code(404);
            require_once __DIR__ . '/../Views/errors/404.php';
            exit;
        }
        
        include __DIR__ . '/../Views/layouts/student.php';
        include __DIR__ . '/../Views/student/test_result.php';
        include __DIR__ . '/../Views/layouts/footer.php';
    }
}
