<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class LogNotifikasi extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'log_notifikasi';

    protected $fillable = [
        'pemeriksaan_kesehatan_id',
        'pasien_id',
        'analisis_ai_id',
        'jenis_notifikasi',
        'nomor_tujuan',
        'email_tujuan',
        'judul_pesan',
        'isi_pesan',
        'template_digunakan',
        'status_pengiriman',
        'waktu_dikirim',
        'waktu_diterima',
        'retry_count',
        'pesan_error',
        'message_id',
        'provider',
        'response_provider',
        'biaya_pengiriman',
        'dibaca',
        'waktu_dibaca',
        'dibalas',
        'balasan_user',
        'prioritas',
        'kategori',
        'dikirim_oleh',
        'ip_address',
        'otomatis',
        'metadata_tambahan',
        'catatan',
    ];

    protected $casts = [
        'waktu_dikirim' => 'datetime',
        'waktu_diterima' => 'datetime',
        'retry_count' => 'integer',
        'response_provider' => 'array',
        'biaya_pengiriman' => 'decimal:4',
        'dibaca' => 'boolean',
        'waktu_dibaca' => 'datetime',
        'dibalas' => 'boolean',
        'otomatis' => 'boolean',
        'metadata_tambahan' => 'array',
    ];

    public function pemeriksaanKesehatan()
    {
        return $this->belongsTo(PemeriksaanKesehatan::class);
    }

    public function pasien()
    {
        return $this->belongsTo(Pasien::class);
    }

    public function analisisAi()
    {
        return $this->belongsTo(AnalisisAi::class);
    }

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

    public function scopeTerkirim($query)
    {
        return $query->where('status_pengiriman', 'TERKIRIM');
    }

    public function scopeGagal($query)
    {
        return $query->where('status_pengiriman', 'GAGAL');
    }

    public function scopeHariIni($query)
    {
        return $query->whereDate('created_at', now()->toDateString());
    }
}

class PengaturanSistem extends Model
{
    use HasFactory;

    protected $table = 'pengaturan_sistem';

    protected $fillable = [
        'kunci',
        'kategori',
        'nama_pengaturan',
        'deskripsi',
        'nilai',
        'nilai_integer',
        'nilai_decimal',
        'nilai_boolean',
        'nilai_json',
        'tipe_data',
        'aturan_validasi',
        'nilai_default',
        'pilihan_nilai',
        'aktif',
        'dapat_diubah',
        'sensitif',
        'urutan',
        'diubah_oleh',
        'terakhir_diubah',
        'catatan_perubahan',
    ];

    protected $casts = [
        'nilai_integer' => 'integer',
        'nilai_decimal' => 'decimal:2',
        'nilai_boolean' => 'boolean',
        'nilai_json' => 'array',
        'aktif' => 'boolean',
        'dapat_diubah' => 'boolean',
        'sensitif' => 'boolean',
        'urutan' => 'integer',
        'terakhir_diubah' => 'datetime',
    ];

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

    public static function get($kunci, $default = null)
    {
        $setting = static::where('kunci', $kunci)->where('aktif', true)->first();

        if (!$setting) {
            return $default;
        }

        return match ($setting->tipe_data) {
            'INTEGER' => $setting->nilai_integer,
            'DECIMAL' => $setting->nilai_decimal,
            'BOOLEAN' => $setting->nilai_boolean,
            'JSON' => $setting->nilai_json,
            default => $setting->nilai,
        };
    }

    public static function set($kunci, $nilai)
    {
        $setting = static::where('kunci', $kunci)->first();

        if (!$setting || !$setting->dapat_diubah) {
            return false;
        }

        $field = match ($setting->tipe_data) {
            'INTEGER' => 'nilai_integer',
            'DECIMAL' => 'nilai_decimal',
            'BOOLEAN' => 'nilai_boolean',
            'JSON' => 'nilai_json',
            default => 'nilai',
        };

        $setting->update([
            $field => $nilai,
            'terakhir_diubah' => now(),
        ]);

        return true;
    }
}

class LogAktivitasSistem extends Model
{
    use HasFactory;

    protected $table = 'log_aktivitas_sistem';

    protected $fillable = [
        'user_id',
        'jenis_aktivitas',
        'modul',
        'aksi',
        'deskripsi',
        'model_type',
        'model_id',
        'data_lama',
        'data_baru',
        'ip_address',
        'user_agent',
        'method',
        'url',
        'request_data',
        'status',
        'pesan_error',
        'http_status_code',
        'waktu_aktivitas',
        'durasi_eksekusi',
        'metadata_tambahan',
    ];

    protected $casts = [
        'data_lama' => 'array',
        'data_baru' => 'array',
        'request_data' => 'array',
        'http_status_code' => 'integer',
        'waktu_aktivitas' => 'datetime',
        'durasi_eksekusi' => 'decimal:3',
        'metadata_tambahan' => 'array',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function model()
    {
        return $this->morphTo();
    }

    public static function log($jenis, $modul, $aksi, $data = [])
    {
        return static::create([
            'user_id' => auth()->id(),
            'jenis_aktivitas' => $jenis,
            'modul' => $modul,
            'aksi' => $aksi,
            'deskripsi' => $data['deskripsi'] ?? null,
            'model_type' => $data['model_type'] ?? null,
            'model_id' => $data['model_id'] ?? null,
            'data_lama' => $data['data_lama'] ?? null,
            'data_baru' => $data['data_baru'] ?? null,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'method' => request()->method(),
            'url' => request()->fullUrl(),
            'waktu_aktivitas' => now(),
            'status' => $data['status'] ?? 'BERHASIL',
        ]);
    }
}
