<?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 Business extends Model
{
    protected $fillable = [
        'user_id', 'business_name', 'business_short_name', 'document_inbox',
        'business_type', 'organization_type', 'contact_number', 'registration_number',
        'address', 'email', 'country_id', 'currency_id', 'state_id',
        'is_organization', 'is_active',
    ];

    protected $casts = [
        'is_organization' => 'boolean',
        'is_active' => 'boolean',
    ];

    // Frontend reads camelCase; emit both shapes so existing UI code works.
    public function toArray(): array
    {
        $a = parent::toArray();
        $a['businessName']        = $a['business_name']        ?? null;
        $a['businessShortName']   = $a['business_short_name']  ?? null;
        $a['documentInbox']       = $a['document_inbox']       ?? null;
        $a['businessType']        = $a['business_type']        ?? null;
        $a['organizationType']    = $a['organization_type']    ?? null;
        $a['contactNumber']       = $a['contact_number']       ?? null;
        $a['registrationNumber']  = $a['registration_number']  ?? null;
        $a['countryId']           = $a['country_id']           ?? null;
        $a['currencyId']          = $a['currency_id']          ?? null;
        $a['stateId']             = $a['state_id']             ?? null;
        $a['isOrganization']      = (bool) ($a['is_organization'] ?? false);
        $a['isActive']            = (bool) ($a['is_active']      ?? true);
        return $a;
    }

    public function user(): BelongsTo { return $this->belongsTo(User::class); }
    public function documents(): HasMany { return $this->hasMany(Document::class); }
    public function contacts(): HasMany { return $this->hasMany(Contact::class); }
    public function chartOfAccounts(): HasMany { return $this->hasMany(ChartOfAccount::class); }
    public function paymentMethods(): HasMany { return $this->hasMany(PaymentMethod::class); }
    public function vatGstRates(): HasMany { return $this->hasMany(VatGstRate::class); }
    public function subscription(): HasOne { return $this->hasOne(Subscription::class)->latestOfMany(); }
    public function subscriptions(): HasMany { return $this->hasMany(Subscription::class); }
    public function billingHistory(): HasMany { return $this->hasMany(BillingHistory::class); }
}
