<?php

namespace App\Models;

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

class ProfitSweepRule extends Model
{
    use HasFactory;

    protected $fillable = [
        'subsidiary_id',
        'parent_company_id',
        'sweep_type',
        'sweep_percentage',
        'threshold_amount',
        'fixed_amount',
        'frequency',
        'day_of_execution',
        'is_active',
        'effective_from',
        'effective_to',
    ];

    protected $casts = [
        'sweep_percentage' => 'decimal:2',
        'threshold_amount' => 'decimal:2',
        'fixed_amount' => 'decimal:2',
        'is_active' => 'boolean',
        'effective_from' => 'date',
        'effective_to' => 'date',
    ];

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

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

    public function transactions()
    {
        return $this->hasMany(ProfitSweepTransaction::class, 'sweep_rule_id');
    }

    public function calculateSweepAmount($subsidiaryCashBalance, $subsidiaryProfit = null)
    {
        switch ($this->sweep_type) {
            case 'percentage':
                return $subsidiaryProfit ? ($subsidiaryProfit * ($this->sweep_percentage / 100)) : 0;
            
            case 'threshold':
                return max(0, $subsidiaryCashBalance - $this->threshold_amount);
            
            case 'fixed_amount':
                return min($this->fixed_amount, $subsidiaryCashBalance);
            
            default:
                return 0;
        }
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true)
                    ->where('effective_from', '<=', now())
                    ->where(function($q) {
                        $q->whereNull('effective_to')
                          ->orWhere('effective_to', '>=', now());
                    });
    }
}
