<?php

namespace App\Models;

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

class ProfitSweepTransaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'sweep_rule_id',
        'transaction_number',
        'from_company_id',
        'to_company_id',
        'sweep_date',
        'year_month',
        'calculated_amount',
        'actual_amount',
        'subsidiary_profit',
        'month_revenue',
        'month_expenses',
        'month_net_profit',
        'is_no_profit_month',
        'status',
        'notes',
        'processed_by',
        'processed_at',
        'is_super_admin_recipient',
        'super_admin_bank_account_id',
    ];

    protected $casts = [
        'sweep_date' => 'date',
        'calculated_amount' => 'decimal:2',
        'actual_amount' => 'decimal:2',
        'subsidiary_profit' => 'decimal:2',
        'month_revenue' => 'decimal:2',
        'month_expenses' => 'decimal:2',
        'month_net_profit' => 'decimal:2',
        'is_no_profit_month' => 'boolean',
        'is_super_admin_recipient' => 'boolean',
        'processed_at' => 'datetime',
    ];

    public function sweepRule()
    {
        return $this->belongsTo(ProfitSweepRule::class, 'sweep_rule_id');
    }

    public function fromCompany()
    {
        return $this->belongsTo(Company::class, 'from_company_id');
    }

    public function toCompany()
    {
        return $this->belongsTo(Company::class, 'to_company_id');
    }

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

    public function superAdminBankAccount()
    {
        return $this->belongsTo(SuperAdminBankAccount::class, 'super_admin_bank_account_id');
    }

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

        static::creating(function ($transaction) {
            if (!$transaction->transaction_number) {
                $transaction->transaction_number = 'SWEEP-' . date('Ymd') . '-' . str_pad(
                    static::whereDate('created_at', date('Y-m-d'))->count() + 1,
                    4,
                    '0',
                    STR_PAD_LEFT
                );
            }
        });
    }
}
