<?php

namespace App\Models\SelfPaced;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * CourseTopic Model
 *
 * Top-level section within a Course containing sub-topics and content.
 *
 * @property int $id
 * @property int $course_id
 * @property string $title
 * @property string|null $description
 * @property int $sort_order
 * @property bool $is_published
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class CourseTopic extends Model
{
    protected $table = 'self_paced_topics';

    protected $fillable = [
        'course_id',
        'title',
        'description',
        'sort_order',
        'is_published',
        // New timing fields
        'min_time_seconds',
        'max_time_seconds',
    ];

    protected $casts = [
        'sort_order'        => 'integer',
        'is_published'      => 'boolean',
        'min_time_seconds'  => 'integer',
        'max_time_seconds'  => 'integer',
        'created_at'        => 'datetime',
        'updated_at'        => 'datetime',
    ];

    protected $attributes = [
        'sort_order'   => 0,
        'is_published' => true,
    ];

    // =========================================================================
    // RELATIONSHIPS
    // =========================================================================

    public function course(): BelongsTo
    {
        return $this->belongsTo(Course::class, 'course_id');
    }

    public function subtopics(): HasMany
    {
        return $this->hasMany(CourseSubTopic::class, 'topic_id')->orderBy('sort_order');
    }

    public function downloads(): HasMany
    {
        return $this->hasMany(CourseDownload::class, 'topic_id');
    }

    public function timers(): HasMany
    {
        return $this->hasMany(TopicTimer::class, 'topic_id');
    }

    // =========================================================================
    // QUERY SCOPES
    // =========================================================================

    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order');
    }

    // =========================================================================
    // HELPER METHODS
    // =========================================================================

    public function getSubtopicsCount(): int
    {
        return $this->subtopics()->count();
    }

    /**
     * Check if all subtopics are completed for a given enrollment.
     */
    public function isCompletedForEnrollment(int $enrollmentId): bool
    {
        $total = $this->subtopics()->where('is_published', true)->count();

        if ($total === 0) {
            return false;
        }

        $completed = LearningProgress::where('enrollment_id', $enrollmentId)
            ->whereIn('subtopic_id', $this->subtopics()->where('is_published', true)->pluck('id'))
            ->count();

        return $completed >= $total;
    }

    /**
     * Check if topic has a minimum time requirement
     *
     * @return bool
     */
    public function hasMinTime(): bool
    {
        return $this->min_time_seconds !== null && $this->min_time_seconds > 0;
    }

    /**
     * Check if elapsed time satisfies the minimum time requirement
     *
     * @param int $elapsedSeconds
     * @return bool
     */
    public function isTimeSatisfied(int $elapsedSeconds): bool
    {
        if (!$this->hasMinTime()) {
            return true;
        }
        return $elapsedSeconds >= $this->min_time_seconds;
    }

    /**
     * Get remaining seconds until minimum time is satisfied
     *
     * @param int $elapsedSeconds
     * @return int
     */
    public function getRemainingMinSeconds(int $elapsedSeconds): int
    {
        if (!$this->hasMinTime()) {
            return 0;
        }
        return max(0, $this->min_time_seconds - $elapsedSeconds);
    }

    /**
     * Check if this topic is accessible for a given enrollment
     * (Based on sequential unlocking requirements)
     *
     * @param int $enrollmentId
     * @return bool
     */
    public function isAccessibleForEnrollment(int $enrollmentId): bool
    {
        $course = $this->course;
        $topics = $course->topics()->where('is_published', true)->orderBy('sort_order')->get();

        // Find the position of this topic
        $thisPosition = $topics->search(fn ($topic) => $topic->id === $this->id);

        // If this is the first topic, always accessible
        if ($thisPosition === 0) {
            return true;
        }

        // If not first, check if the previous topic is completed
        $previousTopic = $topics[$thisPosition - 1];
        return $previousTopic->isCompletedForEnrollment($enrollmentId);
    }
}
