<?php
declare(strict_types=1);

namespace App\Modules\Notifications\Models;

use App\Core\App;
use App\Core\Model;

class NotificationTrigger extends Model
{
    protected static string $table = 'notification_triggers';
    protected static array $fillable = [
        'trigger_code',
        'trigger_name_ar',
        'event_name',
        'template_id',
        'is_active',
        'channel',
        'recipient_type',
        'config_json',
        'priority',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $dispatchEvents = false;
    protected static bool $auditEnabled = false;
    protected static bool $autoTrackAuthor = false;

    /**
     * Get all active triggers for a specific event name.
     */
    public static function getActiveByEvent(string $eventName): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM notification_triggers WHERE event_name = ? AND is_active = 1 ORDER BY priority DESC",
            [$eventName]
        );
    }

    /**
     * Get all triggers (for admin listing).
     */
    public static function getAll(): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT nt.*, st.name_ar AS template_name
             FROM notification_triggers nt
             LEFT JOIN sms_templates st ON st.id = nt.template_id
             ORDER BY nt.event_name, nt.priority DESC"
        );
    }

    /**
     * Find a trigger by its code.
     */
    public static function findByCode(string $code): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM notification_triggers WHERE trigger_code = ?",
            [$code]
        );
    }

    /**
     * Toggle active status.
     */
    public static function toggleActive(int $id): bool
    {
        $db = App::getInstance()->db();
        $trigger = $db->selectOne("SELECT is_active FROM notification_triggers WHERE id = ?", [$id]);
        if (!$trigger) {
            return false;
        }
        $newStatus = $trigger['is_active'] ? 0 : 1;
        $db->update('notification_triggers', [
            'is_active'  => $newStatus,
            'updated_at' => date('Y-m-d H:i:s'),
        ], '`id` = ?', [$id]);
        return true;
    }
}
