<?php

namespace App\Models;

use CodeIgniter\Model;

class CourseModel extends Model
{
    protected $table            = 'courses';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'course_code', 'course_type', 'module_name', 'module_order',
        'lesson_title', 'lesson_order', 'youtube_url', 'duration', 'notes',
    ];

    protected $useTimestamps = false;

    /**
     * Return all lessons for a given course code, ordered by module then lesson.
     */
    public function getLessonsByCourseCode(string $code): array
    {
        return $this->where('course_code', $code)
                    ->orderBy('module_order', 'ASC')
                    ->orderBy('lesson_order', 'ASC')
                    ->findAll();
    }

    /**
     * Group lessons into modules for modular courses.
     * Returns: [ ['module' => 'Module 1: ...', 'lessons' => [...]], ... ]
     */
    public function getGroupedModules(string $code): array
    {
        $lessons = $this->getLessonsByCourseCode($code);
        $grouped = [];

        foreach ($lessons as $lesson) {
            $moduleName = $lesson['module_name'] ?? 'General';
            $key = $lesson['module_order'] . '||' . $moduleName;

            if (!isset($grouped[$key])) {
                $grouped[$key] = [
                    'module'  => $moduleName,
                    'order'   => (int) $lesson['module_order'],
                    'lessons' => [],
                ];
            }
            $grouped[$key]['lessons'][] = $lesson;
        }

        // Sort by module order
        usort($grouped, fn($a, $b) => $a['order'] - $b['order']);

        return $grouped;
    }

    /**
     * Get the course_type for a given course code (uses first row).
     */
    public function getCourseType(string $code): string
    {
        $row = $this->where('course_code', $code)->first();
        return $row['course_type'] ?? 'modular';
    }

    /**
     * Extract YouTube video ID from various URL formats.
     * Supports: youtu.be/ID, youtube.com/watch?v=ID, youtube.com/embed/ID
     */
    public static function extractYouTubeId(?string $url): ?string
    {
        if (empty($url)) return null;

        // youtu.be/ID
        if (preg_match('/youtu\.be\/([a-zA-Z0-9_-]{11})/', $url, $m)) {
            return $m[1];
        }
        // youtube.com/watch?v=ID or &v=ID
        if (preg_match('/[?&]v=([a-zA-Z0-9_-]{11})/', $url, $m)) {
            return $m[1];
        }
        // youtube.com/embed/ID
        if (preg_match('/embed\/([a-zA-Z0-9_-]{11})/', $url, $m)) {
            return $m[1];
        }

        return null;
    }
}
