<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ContractTemplate extends Model
{
    public const STATUSES = ['draft', 'active', 'inactive'];
    public const FORMATS = ['docx', 'pdf'];

    public const SIGNATORIES = [
        'borrower' => 'Borrower / Customer',
        'guarantor' => 'Guarantor',
        'loan_officer' => 'Loan Officer',
        'branch_manager' => 'Branch Manager',
        'local_official' => 'Local Government Official',
        'witness' => 'Witness',
        'office_stamp' => 'Office Stamp',
    ];

    protected $fillable = [
        'business_id','name','version','original_name','format','file_path','extracted_text','blocks','mappings',
        'required_signatories','status','is_default','uploaded_by','updated_by',
    ];

    protected function casts(): array
    {
        return [
            'version' => 'integer',
            'blocks' => 'array',
            'mappings' => 'array',
            'required_signatories' => 'array',
            'is_default' => 'boolean',
        ];
    }

    public function isPdf(): bool
    {
        return strtolower((string) ($this->format ?: pathinfo($this->original_name, PATHINFO_EXTENSION))) === 'pdf';
    }

    public function isDocx(): bool
    {
        return ! $this->isPdf();
    }

    public function business(): BelongsTo { return $this->belongsTo(Business::class); }
    public function uploader(): BelongsTo { return $this->belongsTo(User::class, 'uploaded_by'); }
    public function updater(): BelongsTo { return $this->belongsTo(User::class, 'updated_by'); }
    public function loans(): HasMany { return $this->hasMany(Loan::class); }
}
