<?php

namespace App\Models;

use App\Models\BaseModel;

class ParentNotification extends BaseModel
{
    protected $table = 'parent_notifications';

    // ✅ CI: useTimestamps = true (created_at/updated_at)
    public $timestamps = true;

    protected $fillable = [
        'student_id',
        'code',
        'incident_date',
        'channel',
        'to_address',
        'subject',
        'status',
        'response',
        'semester',
        'school_year',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'student_id'    => 'integer',
        // incident_date is stored as Y-m-d in CI usage
        'incident_date' => 'date',
    ];

    /* Optional relationships */
    public function student()
    {
        return $this->belongsTo(Student::class, 'student_id');
    }

    /**
     * Equivalent of CI hasSent()
     */
    public static function hasSent(
        int $studentId,
        string $code,
        string $incidentYmd,
        string $channel = 'email',
        ?string $to = null
    ): bool {
        $q = static::query()
            ->where('student_id', $studentId)
            ->where('code', $code)
            ->whereDate('incident_date', $incidentYmd)
            ->where('channel', $channel);

        if (!empty($to)) {
            $q->where('to_address', $to);
        }

        $row = $q->orderByDesc('id')->first();

        return $row && (($row->status ?? '') === 'sent');
    }
}