<?php
// src/Controllers/PortalController.php

require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../Helpers/Auth.php';

class PortalController {
    public static function getStudentEnrollments(int $userId): array {
        $db = Database::getConnection();
        $stmt = $db->prepare("
            SELECT e.*, c.title_en, c.title_ar, c.description_en, c.description_ar, 
                   c.category_en, c.category_ar, c.instructor_en, c.instructor_ar, 
                   c.duration_en, c.duration_ar, c.image, c.price_ngn, c.price_usd
            FROM enrollments e
            JOIN courses c ON e.course_id = c.id
            WHERE e.user_id = ?
            ORDER BY e.enrolled_at DESC
        ");
        $stmt->execute([$userId]);
        $enrollments = $stmt->fetchAll();

        $stmtMods = $db->prepare("SELECT module_index, title_en, title_ar FROM course_modules WHERE course_id = ? ORDER BY module_index ASC");

        foreach ($enrollments as &$e) {
            $stmtMods->execute([$e['course_id']]);
            $modules = $stmtMods->fetchAll();
            $e['modules_en'] = array_column($modules, 'title_en');
            $e['modules_ar'] = array_column($modules, 'title_ar');
            $e['completed_modules'] = json_decode($e['completed_modules_json'] ?? '[]', true) ?: [];
        }

        return $enrollments;
    }

    public static function getLiveClasses(): array {
        $db = Database::getConnection();
        $stmt = $db->query("SELECT * FROM live_classes ORDER BY id ASC");
        return $stmt->fetchAll();
    }

    public static function toggleModuleCompletion(int $userId, string $courseId, int $moduleIndex): array {
        $db = Database::getConnection();

        $stmt = $db->prepare("SELECT * FROM enrollments WHERE user_id = ? AND course_id = ?");
        $stmt->execute([$userId, $courseId]);
        $enrollment = $stmt->fetch();

        if (!$enrollment) {
            return ['success' => false, 'message' => 'Enrollment record not found.'];
        }

        $completedMods = json_decode($enrollment['completed_modules_json'] ?? '[]', true) ?: [];

        if (in_array($moduleIndex, $completedMods)) {
            $completedMods = array_values(array_filter($completedMods, fn($m) => $m !== $moduleIndex));
        } else {
            $completedMods[] = $moduleIndex;
        }

        // Calculate progress percentage
        $stmtTotal = $db->prepare("SELECT COUNT(*) FROM course_modules WHERE course_id = ?");
        $stmtTotal->execute([$courseId]);
        $totalModules = (int)$stmtTotal->fetchColumn();

        $progress = $totalModules > 0 ? round((count($completedMods) / $totalModules) * 100) : 0;
        $status = $progress >= 100 ? 'completed' : 'in_progress';

        $stmtUpdate = $db->prepare("UPDATE enrollments SET completed_modules_json = ?, progress = ?, status = ? WHERE id = ?");
        $stmtUpdate->execute([json_encode($completedMods), $progress, $status, $enrollment['id']]);

        return [
            'success' => true,
            'progress' => $progress,
            'status' => $status,
            'completedModules' => $completedMods
        ];
    }
}
