<?php

namespace App\Models;

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

class Document extends Model
{
    protected $fillable = [
        'business_id', 'document_type', 'file_name', 'file_url', 'mime_type',
        'file_size', 'status', 'uploaded_by', 'uploaded_date',
        'processed_by', 'processed_date', 'contact_id', 'is_deleted',
    ];

    protected $casts = [
        'uploaded_date' => 'datetime',
        'processed_date' => 'datetime',
        'is_deleted' => 'boolean',
    ];

    public function toArray(): array
    {
        $a = parent::toArray();

        // camelCase aliases for the columns
        $a['businessId']     = $a['business_id']     ?? null;
        $a['documentType']   = $a['document_type']   ?? null;
        $a['fileName']       = $a['file_name']       ?? null;
        $a['fileUrl']        = $a['file_url']        ?? null;
        $a['mimeType']       = $a['mime_type']       ?? null;
        $a['fileSize']       = $a['file_size']       ?? null;
        $a['uploadedBy']     = $a['uploaded_by']     ?? null;
        $a['uploadedDate']   = $a['uploaded_date']   ?? null;
        $a['processedBy']    = $a['processed_by']    ?? null;
        $a['processedDate']  = $a['processed_date']  ?? null;
        $a['contactId']      = $a['contact_id']      ?? null;
        $a['isDeleted']      = (bool) ($a['is_deleted'] ?? false);

        // Flatten data fields so list views (which read doc.invoiceNumber etc.) work.
        $d = $this->relationLoaded('data') ? $this->data : null;
        $a['invoiceNumber']         = $d?->invoice_number;
        $a['invoiceDate']           = $d?->document_date?->toIso8601String();
        $a['documentDate']          = $d?->document_date?->toIso8601String();
        $a['dueDate']               = $d?->due_date?->toIso8601String();
        $a['subtotal']              = $d?->subtotal;
        $a['taxTotal']              = $d?->tax_total;
        $a['totalAmount']           = $d?->total_amount;
        $a['grossAmount']           = $d?->total_amount;
        $a['convertedGrossAmount']  = $d?->total_amount;
        $a['currency']              = $d?->currency;
        $a['supplierId']            = $d?->supplier_id;
        $a['customerId']            = $d?->customer_id;
        $a['description']           = $d?->description;
        $a['lineItems']             = $d?->line_items ?? [];

        // Stubs for relations the frontend optionally accesses.
        $a['category']      = $a['category']      ?? null;
        $a['paymentMethod'] = $a['paymentMethod'] ?? null;

        // Internal pages read `documentId` and `file` directly.
        $a['documentId'] = $a['id'] ?? null;
        $a['file']       = $a['file_url'] ?? null;

        return $a;
    }

    public function business(): BelongsTo { return $this->belongsTo(Business::class); }
    public function uploader(): BelongsTo { return $this->belongsTo(User::class, 'uploaded_by'); }
    public function processor(): BelongsTo { return $this->belongsTo(User::class, 'processed_by'); }
    public function contact(): BelongsTo { return $this->belongsTo(Contact::class); }
    public function data(): HasOne { return $this->hasOne(DocumentData::class); }
    public function history(): HasMany { return $this->hasMany(DocumentHistory::class); }
    public function exceptions(): HasMany { return $this->hasMany(DocumentException::class); }
}
