<?php

namespace App\Models;

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

class Download extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'description',
        'file_path',
        'file_name',
        'file_type',
        'file_size',
        'category',
        'status',
        'visibility',
        'download_count',
        'sort_order',
        'version',
        'file_hash',
        'changelog',
    ];

    protected $casts = [
        'file_size' => 'integer',
        'download_count' => 'integer',
        'sort_order' => 'integer',
    ];

    /**
     * Get the client download records for this download.
     */
    public function clientDownloads()
    {
        return $this->hasMany(ClientDownload::class);
    }

    /**
     * Check if this download was added recently (last 7 days).
     */
    public function isNew(): bool
    {
        return $this->created_at && $this->created_at->greaterThan(now()->subDays(7));
    }

    /**
     * Scope: only active downloads.
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope: filter by category.
     */
    public function scopeByCategory($query, string $category)
    {
        return $query->where('category', $category);
    }

    /**
     * Scope: only clients_only visibility.
     */
    public function scopeClientsOnly($query)
    {
        return $query->where('visibility', 'clients_only');
    }

    /**
     * Scope: only public visibility.
     */
    public function scopePublicOnly($query)
    {
        return $query->where('visibility', 'public');
    }

    /**
     * Get formatted file size.
     */
    public function getFormattedSize(): string
    {
        $bytes = $this->file_size;

        if ($bytes >= 1073741824) {
            return number_format($bytes / 1073741824, 2) . ' GB';
        } elseif ($bytes >= 1048576) {
            return number_format($bytes / 1048576, 2) . ' MB';
        } elseif ($bytes >= 1024) {
            return number_format($bytes / 1024, 2) . ' KB';
        }

        return $bytes . ' B';
    }

    /**
     * Increment the download count.
     */
    public function incrementDownloads(): void
    {
        $this->increment('download_count');
    }
}
