<?php

namespace App\Models;

use App\Traits\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * @property int $id
 * @property string $name
 * @property string|null $description
 * @property int $client_only
 * @property int $hidden
 * @property int $status
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 *
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment query()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereClientOnly($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereHidden($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereUpdatedAt($value)
 *
 * @property string|null $outgoing_email_to
 * @property string|null $outgoing_email_name
 * @property bool $no_auto_responder
 * @property bool $have_feedback_request
 * @property int $feedback_after_hours
 * @property string|null $mail_hostname
 * @property int $mail_port
 * @property string|null $mail_email
 * @property string|null $mail_password
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\Admin> $admins
 * @property-read int|null $admins_count
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\TicketDepartmentCustomField> $customFields
 * @property-read int|null $custom_fields_count
 * @property-read \Illuminate\Database\Eloquent\Collection<int, \App\Models\LanguageTranslation> $translations
 * @property-read int|null $translations_count
 *
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment active()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment clientAccessible()
 * @method static \Database\Factories\TicketDepartmentFactory factory($count = null, $state = [])
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment visible()
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereDescription($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereFeedbackAfterHours($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereHaveFeedbackRequest($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereMailEmail($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereMailHostname($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereMailPassword($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereMailPort($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereNoAutoResponder($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereOutgoingEmailName($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereOutgoingEmailTo($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereTranslation(string $locale, string $field, string $value)
 * @method static \Illuminate\Database\Eloquent\Builder<static>|TicketDepartment whereTranslationLike(string $locale, string $field, string $value)
 *
 * @mixin \Eloquent
 */
class TicketDepartment extends Model
{
    use HasFactory, HasTranslations;

    /**
     * Çevrilebilir alanlar
     */
    protected $translatable = [
        'name',
        'description',
    ];

    protected $fillable = [
        'name',
        'description',
        'client_only',
        'hidden',
        'status',
        'sla_plan_id',
        'outgoing_email_to',
        'outgoing_email_name',
        'no_auto_responder',
        'have_feedback_request',
        'feedback_after_hours',
        'mail_hostname',
        'mail_port',
        'mail_email',
        'mail_password',
        'slack_enabled',
        'slack_channel_prefix',
        'telegram_enabled',
        'telegram_chat_id',
        'discord_enabled',
        'discord_webhook_url',
        'discord_use_forum_threads',
        'teams_enabled',
        'teams_webhook_url',
        'teams_use_threads',
        'pushover_enabled',
        'pushover_user_key',
        'whatsapp_enabled',
        'whatsapp_phone',
        'sms_enabled',
        'sms_notification_phones',
        'mail_import_enabled',
        'accept_unregistered_emails',
        'mail_protocol',
        'mail_ssl',
        'mail_footer_strip',
        'mail_poll_interval',
        'mail_post_action',
        'mail_move_folder',
        'mail_auth_type',
    ];

    protected $casts = [
        'client_only' => 'boolean',
        'hidden' => 'boolean',
        'status' => 'boolean',
        'no_auto_responder' => 'boolean',
        'accept_unregistered_emails' => 'boolean',
        'have_feedback_request' => 'boolean',
        'feedback_after_hours' => 'integer',
        'mail_port' => 'integer',
        'slack_enabled' => 'boolean',
        'telegram_enabled' => 'boolean',
        'discord_enabled' => 'boolean',
        'discord_use_forum_threads' => 'boolean',
        'teams_enabled' => 'boolean',
        'teams_use_threads' => 'boolean',
        'pushover_enabled' => 'boolean',
        'whatsapp_enabled' => 'boolean',
        'sms_enabled' => 'boolean',
    ];

    /**
     * Aktif departmanları getir
     */
    public function scopeActive($query)
    {
        return $query->where('status', true);
    }

    /**
     * Gizli olmayan departmanları getir
     */
    public function scopeVisible($query)
    {
        return $query->where('hidden', false);
    }

    /**
     * Müşteri erişimli departmanları getir
     */
    public function scopeClientAccessible($query)
    {
        return $query->where('client_only', true);
    }

    /**
     * Get the custom fields for the ticket department.
     */
    public function customFields()
    {
        return $this->hasMany(TicketDepartmentCustomField::class)->ordered();
    }

    /**
     * Get the admins assigned to this ticket department.
     */
    public function admins()
    {
        return $this->belongsToMany(Admin::class, 'ticket_department_admins', 'ticket_department_id', 'admin_id')
            ->withTimestamps();
    }

    /**
     * Get all admins who can access this department (assigned + super-admins),
     * filtered by email notification preference for the given event type.
     */
    public function getAuthorizedAdmins(?string $notificationEvent = null): \Illuminate\Support\Collection
    {
        $departmentAdmins = $this->admins()->get();

        $superAdmins = Admin::role('super-admin')
            ->whereNotIn('id', $departmentAdmins->pluck('id'))
            ->get();

        $allAdmins = $departmentAdmins->merge($superAdmins);

        if ($notificationEvent) {
            $allAdmins = $allAdmins->filter(function (Admin $admin) use ($notificationEvent) {
                $channels = $admin->getNotificationChannels($notificationEvent);

                // null = no preference set, use system defaults (send email)
                if ($channels === null) {
                    return true;
                }

                return in_array('email', $channels);
            });
        }

        return $allAdmins;
    }

    public function mailboxes()
    {
        return $this->hasMany(TicketDepartmentMailbox::class);
    }

    public function enabledMailboxes()
    {
        return $this->hasMany(TicketDepartmentMailbox::class)->where('enabled', true);
    }

    /**
     * PRC-601 — Yeni ticket auto-response ("mailinizi aldık / ticket açıldı")
     * gönderilmeli mi? Karar tek nokta: global ayar AÇIK ve departman bireysel
     * olarak kapatmamışsa. Hem email-pipe hem panel call-site'ı bunu kullanır;
     * mantığı çağrı yerlerine dağıtma.
     */
    public function shouldSendNewTicketAutoResponse(): bool
    {
        return Setting::get('auto_response_on_new_ticket', true) && ! $this->no_auto_responder;
    }
}
