<?php

namespace App\Models;

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

class ProfitDistribution extends Model
{
    use HasFactory;

    protected $fillable = [
        'distribution_number',
        'distribution_date',
        'total_profit',
        'total_members',
        'per_member_share',
        'status',
        'distributed_by',
        'distribution_method',
        'notes',
        'financial_year_start',
        'financial_year_end'
    ];

    protected $casts = [
        'distribution_date' => 'date',
        'total_profit' => 'decimal:2',
        'per_member_share' => 'decimal:2',
        'financial_year_start' => 'date',
        'financial_year_end' => 'date',
    ];

    // স্বয়ংক্রিয় বন্টন নম্বর জেনারেটর
    public static function generateDistributionNumber()
    {
        $year = date('Y');
        $prefix = 'PROFIT';
        
        $lastDistribution = self::where('distribution_number', 'like', $prefix . '-' . $year . '-%')
            ->orderBy('distribution_number', 'desc')
            ->first();
        
        if ($lastDistribution) {
            $lastNumber = intval(substr($lastDistribution->distribution_number, -3));
            $nextNumber = str_pad($lastNumber + 1, 3, '0', STR_PAD_LEFT);
        } else {
            $nextNumber = '001';
        }
        
        return $prefix . '-' . $year . '-' . $nextNumber;
    }

    // বুট মেথড
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($distribution) {
            if (empty($distribution->distribution_number)) {
                $distribution->distribution_number = self::generateDistributionNumber();
            }
        });
    }

    // রিলেশনশিপ: বন্টনকারী
    public function distributor()
    {
        return $this->belongsTo(User::class, 'distributed_by');
    }

    // রিলেশনশিপ: সদস্য শেয়ার
    public function memberShares()
    {
        return $this->hasMany(MemberProfitShare::class, 'distribution_id');
    }

    // রিলেশনশিপ: পরিশোধিত শেয়ার
    public function paidShares()
    {
        return $this->hasMany(MemberProfitShare::class, 'distribution_id')
            ->where('status', 'paid');
    }

    // রিলেশনশিপ: বকেয়া শেয়ার
    public function pendingShares()
    {
        return $this->hasMany(MemberProfitShare::class, 'distribution_id')
            ->where('status', 'pending');
    }

    // স্ট্যাটাস বাংলায়
    public function getStatusInBanglaAttribute()
    {
        $statuses = [
            'calculated' => 'গণনাকৃত',
            'distributed' => 'বিতরণকৃত',
            'completed' => 'সম্পন্ন'
        ];
        
        return $statuses[$this->status] ?? $this->status;
    }

    // বন্টন মেথড বাংলায়
    public function getDistributionMethodInBanglaAttribute()
    {
        $methods = [
            'cash' => 'নগদ',
            'bank' => 'ব্যাংক',
            'saving_account' => 'সঞ্চয় একাউন্ট'
        ];
        
        return $methods[$this->distribution_method] ?? $this->distribution_method;
    }

    // আর্থিক বছর
    public function getFinancialYearAttribute()
    {
        $start = $this->financial_year_start->format('Y');
        $end = $this->financial_year_end->format('Y');
        
        return $start . '-' . $end;
    }

    // মোট বিতরণকৃত
    public function getTotalDistributedAttribute()
    {
        return $this->paidShares()->sum('share_amount');
    }

    // মোট বকেয়া
    public function getTotalPendingAttribute()
    {
        return $this->pendingShares()->sum('share_amount');
    }

    // বন্টনের শতাংশ
    public function getDistributionPercentageAttribute()
    {
        if ($this->total_profit == 0) {
            return 0;
        }
        
        return ($this->total_distributed / $this->total_profit) * 100;
    }

    // স্বয়ংক্রিয় লাভ গণনা
    public function calculateProfit($startDate, $endDate)
    {
        // মোট আয়
        $totalIncome = Income::whereBetween('income_date', [$startDate, $endDate])
            ->sum('amount');
        
        // মোট ব্যয়
        $totalExpense = Expense::whereBetween('expense_date', [$startDate, $endDate])
            ->sum('amount');
        
        // মোট লাভ
        $totalProfit = $totalIncome - $totalExpense;
        
        // সক্রিয় সদস্য সংখ্যা
        $totalMembers = Member::active()->approved()->count();
        
        // প্রতি সদস্যের শেয়ার
        $perMemberShare = $totalMembers > 0 ? $totalProfit / $totalMembers : 0;
        
        $this->total_profit = $totalProfit;
        $this->total_members = $totalMembers;
        $this->per_member_share = $perMemberShare;
        $this->financial_year_start = $startDate;
        $this->financial_year_end = $endDate;
        
        return $this;
    }

    // স্বয়ংক্রিয় সদস্য শেয়ার তৈরি
    public function generateMemberShares()
    {
        $members = Member::active()->approved()->get();
        $shares = [];
        
        foreach ($members as $member) {
            $shares[] = [
                'distribution_id' => $this->id,
                'member_id' => $member->member_id,
                'share_amount' => $this->per_member_share,
                'status' => 'pending',
                'created_at' => now(),
                'updated_at' => now(),
            ];
        }
        
        MemberProfitShare::insert($shares);
        
        return count($shares);
    }
}