<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Auth;
use Spatie\EloquentSortable\Sortable;
use Spatie\EloquentSortable\SortableTrait;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class AdminsTaskChecklistItem extends Model implements HasMedia, Sortable
{
    use HasFactory, InteractsWithMedia, SortableTrait;

    protected $fillable = [
        'admins_task_id',
        'title',
        'description',
        'is_completed',
        'order_column',
        'completed_at',
        'completed_by',
    ];

    protected $casts = [
        'is_completed' => 'boolean',
        'completed_at' => 'datetime',
    ];

    /**
     * Sortable configuration
     */
    public $sortable = [
        'order_column_name' => 'order_column',
        'sort_when_creating' => true,
    ];

    /**
     * Define the group column for sorting (items are sorted within each task)
     */
    public function buildSortQuery()
    {
        return static::query()->where('admins_task_id', $this->admins_task_id);
    }

    /**
     * Get the task this checklist item belongs to
     */
    public function adminsTask(): BelongsTo
    {
        return $this->belongsTo(AdminsTask::class);
    }

    /**
     * Get the user who completed this item
     */
    public function completedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'completed_by');
    }

    /**
     * Mark the checklist item as completed
     */
    public function markAsCompleted(): bool
    {
        $this->is_completed = true;
        $this->completed_at = now();
        $this->completed_by = Auth::id();

        return $this->save();
    }

    /**
     * Mark the checklist item as incomplete
     */
    public function markAsIncomplete(): bool
    {
        $this->is_completed = false;
        $this->completed_at = null;
        $this->completed_by = null;

        return $this->save();
    }

    /**
     * Toggle completion status
     */
    public function toggleCompletion(): bool
    {
        return $this->is_completed ? $this->markAsIncomplete() : $this->markAsCompleted();
    }

    /**
     * Register media collections for file uploads
     */
    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('checklist_item_attachments')
            ->acceptsMimeTypes([
                'application/pdf',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/vnd.ms-excel',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/vnd.ms-powerpoint',
                'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                'image/jpeg',
                'image/png',
                'image/gif',
                'image/webp',
                'text/plain',
                'application/zip',
                'application/x-rar-compressed',
            ]);
    }

    /**
     * Register media conversions for thumbnails
     */
    public function registerMediaConversions(?Media $media = null): void
    {
        $this->addMediaConversion('thumb')
            ->width(300)
            ->height(300)
            ->sharpen(10)
            ->optimize()
            ->nonQueued();

        $this->addMediaConversion('preview')
            ->width(500)
            ->height(500)
            ->sharpen(10)
            ->optimize()
            ->nonQueued();
    }

    /**
     * Get all checklist item attachments
     */
    public function getChecklistItemAttachments()
    {
        return $this->getMedia('checklist_item_attachments');
    }

    /**
     * Check if checklist item has attachments
     */
    public function hasAttachments(): bool
    {
        return $this->getMedia('checklist_item_attachments')->isNotEmpty();
    }

    /**
     * Get attachments count
     */
    public function getAttachmentsCount(): int
    {
        return $this->getMedia('checklist_item_attachments')->count();
    }
}
