<?php

namespace App\Models;

use App\Models\BaseModel;

class Message extends BaseModel
{
    protected $table = 'messages';

    // CI: useTimestamps = false (manual date fields)
    public $timestamps = false;

    protected $fillable = [
        'sender_id',
        'recipient_id',
        'subject',
        'message',
        'sent_datetime',
        'read_status',
        'read_datetime',
        'message_number',
        'priority',
        'attachment',
        'status',
        'semester',
        'school_year',
    ];

    protected $casts = [
        'sender_id'      => 'integer',
        'recipient_id'   => 'integer',
        'read_status'    => 'boolean',
        'message_number' => 'integer',

        'sent_datetime'  => 'datetime',
        'read_datetime'  => 'datetime',
    ];

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

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

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

    public static function getUnreadMessages(int $recipientId)
    {
        return static::query()
            ->where('recipient_id', $recipientId)
            ->where('read_status', 0)
            ->orderByDesc('sent_datetime')
            ->get();
    }

    public static function markAsRead(int $messageId): bool
    {
        $affected = static::query()
            ->whereKey($messageId)
            ->update([
                'read_status'   => 1,
                'read_datetime' => now(), // set app timezone (configure to UTC if desired)
            ]);

        return $affected > 0;
    }

    public static function getMessagesByPriority(string $priority = 'normal')
    {
        return static::query()
            ->where('priority', $priority)
            ->orderByDesc('sent_datetime')
            ->get();
    }

    public static function getMessagesByStatus(string $status = 'sent')
    {
        return static::query()
            ->where('status', $status)
            ->orderByDesc('sent_datetime')
            ->get();
    }

    public static function getInboxMessages(int $userId)
    {
        return static::query()
            ->where('recipient_id', $userId)
            ->where('status', 'received')
            ->orderByDesc('sent_datetime')
            ->get();
    }

    public static function getSentMessages(int $userId)
    {
        return static::query()
            ->where('sender_id', $userId)
            ->where('status', 'sent')
            ->orderByDesc('sent_datetime')
            ->get();
    }

    public static function getDraftMessages(int $userId)
    {
        return static::query()
            ->where('sender_id', $userId)
            ->where('status', 'draft')
            ->orderByDesc('sent_datetime')
            ->get();
    }

    public static function getTrashedMessages(int $userId)
    {
        return static::query()
            ->where(function ($q) use ($userId) {
                $q->where('sender_id', $userId)
                  ->orWhere('recipient_id', $userId);
            })
            ->where('status', 'trashed')
            ->orderByDesc('sent_datetime')
            ->get();
    }

    public static function getMessagesBySemesterAndYear(string $semester, ?string $schoolYear = null)
    {
        $q = static::query()->where('semester', $semester);

        if (!empty($schoolYear)) {
            $q->where('school_year', $schoolYear);
        }

        return $q->orderByDesc('sent_datetime')->get();
    }
}