<?php

namespace App\Models;

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

class CustomReport extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'school_id',
        'report_name',
        'description',
        'report_type',
        'query',
        'parameters',
        'columns',
        'filters',
        'created_by',
        'is_public',
        'is_active',
    ];

    protected $casts = [
        'parameters' => 'array',
        'columns' => 'array',
        'filters' => 'array',
        'is_public' => 'boolean',
        'is_active' => 'boolean',
    ];

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

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function scheduledReports()
    {
        return $this->hasMany(ScheduledReport::class, 'custom_report_id');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopePublic($query)
    {
        return $query->where('is_public', true);
    }

    public function scopeForUser($query, $userId)
    {
        return $query->where('created_by', $userId)
                     ->orWhere('is_public', true);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('report_type', $type);
    }
}
