<?php

namespace App\Models;

use App\Models\BaseModel;

class ContactUs extends BaseModel
{
    protected $table = 'contactus';

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

    protected $fillable = [
        'sender_id',
        'reciever_id',
        'subject',
        'message',
        'created_at',
        'updated_at',
        'semester',
        'school_year',
    ];

    protected $casts = [
        'sender_id'   => 'integer',
        'reciever_id' => 'integer',
    ];

    /* Optional relationships */
    public function sender()
    {
        return $this->belongsTo(User::class, 'sender_id');
    }

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

    /* =========================
     * CI method equivalents
     * ========================= */

    /**
     * Retrieve messages by semester and school year.
     */
    public static function getMessagesBySemesterAndYear(string $semester, string $schoolYear)
    {
        return static::query()
            ->where('semester', $semester)
            ->where('school_year', $schoolYear)
            ->get();
    }

    /**
     * Retrieve messages for a specific sender or receiver.
     */
    public static function getMessagesForUser(int $userId)
    {
        return static::query()
            ->where('sender_id', $userId)
            ->orWhere('reciever_id', $userId)
            ->get();
    }

    /**
     * Retrieve a message by ID.
     */
    public static function getMessageById(int $id): ?self
    {
        return static::query()->find($id);
    }

    /**
     * Update a message by ID.
     */
    public static function updateMessage(int $id, array $data): bool
    {
        return static::query()->whereKey($id)->update($data) >= 0;
    }
}