<?php

namespace App\Models;

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

class InformasiKegiatan extends Model
{
    use HasFactory;

    protected $table = 'InformasiKegiatan';
    protected $primaryKey = 'KegiatanID';

    protected $fillable = [
        'NoRegistrasi',
        'JenisDokumen',
        'NamaKegiatan',
        'BidangUsaha',
        'SkalaBesaran',
        'LokasiKegiatan',
        'Kewenangan',
        'Pemrakarsa',
        'ProvinsiKota',
        'DeskripsiKegiatan',
        'DampakPotensial',
        'DeskripsiLokasi',
        'Latitude',
        'Longitude',
        'TanggalMulaiPeriode',
        'TanggalSelesaiPeriode',
        'Status'
    ];

    protected $casts = [
        'TanggalMulaiPeriode' => 'date',
        'TanggalSelesaiPeriode' => 'date',
        'Latitude' => 'decimal:8',
        'Longitude' => 'decimal:8',
    ];

    /**
     * Get all feedback for this activity
     */
    public function saranTanggapan()
    {
        return $this->hasMany(SaranTanggapan::class, 'KegiatanID');
    }

    /**
     * Get approved feedback only
     */
    public function saranTanggapanApproved()
    {
        return $this->hasMany(SaranTanggapan::class, 'KegiatanID')->where('Status', 'approved');
    }

    /**
     * Scope for active activities
     */
    public function scopeActive($query)
    {
        return $query->where('Status', 'aktif');
    }

    /**
     * Scope for specific document type
     */
    public function scopeByDocumentType($query, $type)
    {
        return $query->where('JenisDokumen', $type);
    }

    /**
     * Scope for current period
     */
    public function scopeCurrentPeriod($query)
    {
        $today = now()->toDateString();
        return $query->where('TanggalMulaiPeriode', '<=', $today)
                    ->where('TanggalSelesaiPeriode', '>=', $today);
    }

    /**
     * Get formatted period string
     */
    public function getPeriodeAttribute()
    {
        return $this->TanggalMulaiPeriode->format('d M') . ' - ' .
               $this->TanggalSelesaiPeriode->format('d M Y');
    }

    /**
     * Check if activity is currently active for feedback
     */
    public function isActiveFeedbackPeriod()
    {
        $today = now()->toDateString();
        return $this->Status === 'aktif' &&
               $this->TanggalMulaiPeriode <= $today &&
               $this->TanggalSelesaiPeriode >= $today;
    }
}
