<?php

namespace App\Models\Operation;

use App\Models\Agency\Agency;
use App\Models\Agency\AgencyContract;
use App\Models\Resource;
use App\Models\ResourceSchedule;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Rehber atamasından üretilmiş kontrat örneği (şablon + render edilmiş HTML).
 */
class ResourceContract extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'agency_id',
        'schedule_id',
        'template_id',
        'resource_id',
        'title',
        'content',
        'merge_data',
        'status',
        'sent_at',
        'signed_at',
        'pdf_path',
        'disk_item_id',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'merge_data' => 'array',
        'sent_at' => 'datetime',
        'signed_at' => 'datetime',
    ];

    public const STATUSES = [
        'draft' => 'Taslak',
        'sent' => 'Gönderildi',
        'signed' => 'İmzalandı',
        'declined' => 'Reddedildi',
    ];

    public const STATUS_COLORS = [
        'draft' => '#64748b',
        'sent' => '#f59e0b',
        'signed' => '#16a34a',
        'declined' => '#dc2626',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (auth()->check()) {
                $model->created_by = $model->created_by ?? auth()->id();
            }
        });

        static::updating(function ($model) {
            if (auth()->check()) {
                $model->updated_by = auth()->id();
            }
        });
    }

    // ─── İlişkiler ───────────────────────────────────────────────

    public function agency()
    {
        return $this->belongsTo(Agency::class);
    }

    public function schedule()
    {
        return $this->belongsTo(ResourceSchedule::class, 'schedule_id');
    }

    public function template()
    {
        return $this->belongsTo(AgencyContract::class, 'template_id');
    }

    public function resource()
    {
        return $this->belongsTo(Resource::class);
    }

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

    public function diskItem()
    {
        return $this->belongsTo(\App\Models\Disk\DiskItem::class, 'disk_item_id');
    }

    // ─── Scope ───────────────────────────────────────────────────

    public function scopeByAgency($query, $agencyId)
    {
        return $query->where('agency_id', $agencyId);
    }

    // ─── Accessor ────────────────────────────────────────────────

    public function getStatusLabelAttribute(): string
    {
        return self::STATUSES[$this->status] ?? $this->status;
    }

    public function getStatusColorAttribute(): string
    {
        return self::STATUS_COLORS[$this->status] ?? '#64748b';
    }

    /** İki taraflı imza alanı (Acente + Rehber/Kaynak) — belge çıktısının sonuna eklenir. */
    public function signatureBlockHtml(): string
    {
        $data = $this->merge_data ?? [];
        $agency = e($data['acente.ad'] ?? optional($this->agency)->name ?? 'Acente');
        $counter = e($data['rehber.ad_soyad'] ?? optional($this->resource)->name ?? '');
        $roleLabel = mb_strtoupper($data['gorev.rol'] ?? 'KARŞI TARAF', 'UTF-8');
        $date = e($data['tarih.bugun'] ?? '');

        $cell = fn (string $t, string $name, string $note) =>
            '<td style="width:45%;vertical-align:top;text-align:center;padding:0 8px">'
            . '<div style="height:56px"></div>'
            . '<div style="border-top:1px solid #334155;padding-top:8px;font-weight:bold;letter-spacing:.03em">' . $t . '</div>'
            . '<div style="margin-top:3px">' . $name . '</div>'
            . '<div style="color:#64748b;font-size:11px;margin-top:2px">' . $note . '</div></td>';

        return '<div style="margin-top:46px;page-break-inside:avoid">'
            . ($date !== '' ? '<p style="text-align:right;color:#64748b;font-size:12px;margin-bottom:12px">Tarih: ' . $date . '</p>' : '')
            . '<table style="width:100%;border-collapse:collapse"><tr>'
            . $cell('ACENTE', $agency, 'Kaşe / İmza')
            . '<td style="width:10%"></td>'
            . $cell($roleLabel, $counter, 'İmza')
            . '</tr></table></div>';
    }

    /** Kontratı tek dosyalık, yazdırılabilir HTML belgeye dönüştürür. */
    public function toPrintableHtml(): string
    {
        $title = e($this->title);
        $body = ($this->content ?: '') . $this->signatureBlockHtml();

        // Font: 'DejaVu Sans' — dompdf ile gelir ve Türkçe karakterleri (ş,ı,ğ,İ,Ş…) tam destekler.
        // Tarayıcıda görüntülemede DejaVu yoksa Arial'a düşer (o da Türkçe destekler).
        return '<!doctype html><html lang="tr"><head><meta charset="utf-8">'
            . '<meta name="viewport" content="width=device-width, initial-scale=1"><title>' . $title . '</title>'
            . '<style>body,body *{font-family:"DejaVu Sans",Arial,Helvetica,sans-serif}'
            . 'body{max-width:780px;margin:32px auto;padding:0 26px;line-height:1.7;color:#1e293b}'
            . 'h1,h2,h3{color:#0f172a} img{max-width:100%;height:auto} @media print{body{margin:0}}</style>'
            . '</head><body>' . $body . '</body></html>';
    }
}
