<?php

namespace App\Models;

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

class Report extends Model
{
    use HasFactory;

    protected $primaryKey = 'report_id';

    protected $fillable = [
        'report_name',
        'report_type',
        'report_data',
        'date_range_start',
        'date_range_end',
        'generated_by',
        'is_archived'
    ];

    protected $casts = [
        'report_data' => 'array',
        'date_range_start' => 'date',
        'date_range_end' => 'date',
        'is_archived' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Get the user who generated the report.
     */
    public function generator()
    {
        return $this->belongsTo(User::class, 'generated_by', 'user_id');
    }

    /**
     * Scope a query to only include specific report type.
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('report_type', $type);
    }

    /**
     * Scope a query to only include non-archived reports.
     */
    public function scopeActive($query)
    {
        return $query->where('is_archived', false);
    }

    /**
     * Scope a query to only include archived reports.
     */
    public function scopeArchived($query)
    {
        return $query->where('is_archived', true);
    }

    /**
     * Scope a query to include reports within date range.
     */
    public function scopeDateRange($query, $startDate, $endDate)
    {
        return $query->where(function($q) use ($startDate, $endDate) {
            $q->whereBetween('date_range_start', [$startDate, $endDate])
              ->orWhereBetween('date_range_end', [$startDate, $endDate])
              ->orWhere(function($q2) use ($startDate, $endDate) {
                  $q2->where('date_range_start', '<=', $startDate)
                     ->where('date_range_end', '>=', $endDate);
              });
        });
    }

    /**
     * Check if report is archived.
     */
    public function isArchived(): bool
    {
        return $this->is_archived;
    }

    /**
     * Archive the report.
     */
    public function archive()
    {
        $this->update(['is_archived' => true]);
    }

    /**
     * Unarchive the report.
     */
    public function unarchive()
    {
        $this->update(['is_archived' => false]);
    }

    /**
     * Get report summary.
     */
    public function getSummary()
    {
        return $this->report_data['summary'] ?? null;
    }

    /**
     * Get report data by key.
     */
    public function getData($key, $default = null)
    {
        return data_get($this->report_data, $key, $default);
    }
}
