<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class BookChapter extends Model
{
    use HasFactory;

    protected $fillable = [
        'book_id',
        'title',
        'file_name',
        'chapter_number',
        'description',
        'order',
    ];

    protected $casts = [
        'chapter_number' => 'integer',
        'order' => 'integer',
    ];

    // Relationships
    public function book()
    {
        return $this->belongsTo(Book::class);
    }

    public function notes()
    {
        return $this->hasMany(BookNote::class);
    }

    public function progress()
    {
        return $this->hasMany(BookProgress::class);
    }

    public function bookmarks()
    {
        return $this->hasMany(Bookmark::class);
    }

    public function practices()
    {
        return $this->hasMany(BookChapterPractice::class)->where('is_active', true)->orderBy('order');
    }

    // Helper methods
    public function getFilePath()
    {
        return public_path($this->book->folder_path . '/' . $this->file_name);
    }

    public function getUrl()
    {
        return asset($this->book->folder_path . '/' . $this->file_name);
    }

    public function getPreviousChapter()
    {
        return $this->book->chapters()
            ->where('order', '<', $this->order)
            ->orderBy('order', 'desc')
            ->first();
    }

    public function getNextChapter()
    {
        return $this->book->chapters()
            ->where('order', '>', $this->order)
            ->orderBy('order', 'asc')
            ->first();
    }
}
