<?php

namespace App\Models;

use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    /**
     * Mass assignable attributes
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'phone',
        'address',
        'avatar',
        'is_active',
    ];

    /**
     * Hidden attributes
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Casts
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'is_active' => 'boolean',
    ];

    /*
    |--------------------------------------------------------------------------
    | Relationships
    |--------------------------------------------------------------------------
    */

    // Categories created by teacher
    public function createdCategories()
    {
        return $this->hasMany(Category::class, 'created_by');
    }

    // Courses created by teacher
    public function teachingCourses()
    {
        return $this->hasMany(Course::class, 'teacher_id');
    }

    // Student enrollments
    public function enrollments()
    {
        return $this->hasMany(CourseEnrollment::class, 'student_id');
    }

    // Assignments created by teacher
    public function createdAssignments()
    {
        return $this->hasMany(Assignment::class, 'created_by');
    }

    public function createdLectures()
    {
        return $this->hasMany(Lecture::class, 'created_by');
    }

    // Assignment submissions (student side)
    public function submissions()
    {
        return $this->hasMany(AssignmentSubmission::class, 'student_id');
    }

    // Chats sent
    public function sentChats()
    {
        return $this->hasMany(Chat::class, 'sender_id');
    }

    // Chats received
    public function receivedChats()
    {
        return $this->hasMany(Chat::class, 'receiver_id');
    }

    public function shouldBeActiveBasedOnCourses(?CarbonInterface $date = null): bool
    {
        if ($this->hasRole('master-admin')) {
            return true;
        }

        $compareDate = ($date ?? now())->copy()->startOfDay()->toDateString();
        $hasTrackedCourses = false;
        $hasAnyActiveCourse = false;

        if ($this->hasRole('teacher')) {
            $teacherCourses = $this->teachingCourses();
            $hasTrackedCourses = $hasTrackedCourses || $teacherCourses->exists();
            $hasAnyActiveCourse = $hasAnyActiveCourse || $this->teachingCourses()
                ->where(function ($query) use ($compareDate) {
                    $query->whereNull('expire_date')
                        ->orWhereDate('expire_date', '>=', $compareDate);
                })
                ->exists();
        }

        if ($this->hasRole('student')) {
            $studentEnrollments = $this->enrollments();
            $hasTrackedCourses = $hasTrackedCourses || $studentEnrollments->exists();
            $hasAnyActiveCourse = $hasAnyActiveCourse || $this->enrollments()
                ->whereHas('course', function ($query) use ($compareDate) {
                    $query->where(function ($courseQuery) use ($compareDate) {
                        $courseQuery->whereNull('expire_date')
                            ->orWhereDate('expire_date', '>=', $compareDate);
                    });
                })
                ->exists();
        }

        if (! $hasTrackedCourses) {
            return true;
        }

        return $hasAnyActiveCourse;
    }

    public function syncCourseAccessStatus(?bool $isActive = null): bool
    {
        $shouldBeActive = $isActive ?? $this->shouldBeActiveBasedOnCourses();

        if ((bool) $this->is_active !== $shouldBeActive) {
            $this->forceFill(['is_active' => $shouldBeActive])->saveQuietly();
        }

        return $shouldBeActive;
    }
}
