<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class JointAccountTransaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'joint_account_id',
        'initiated_by',
        'transaction_type',
        'amount',
        'description',
        'reference',
        'status',
        'approval_data',
        'metadata',
        'approved_at',
        'completed_at'
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'approval_data' => 'array',
        'metadata' => 'array',
        'approved_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($transaction) {
            if (empty($transaction->reference)) {
                $transaction->reference = 'JT' . time() . rand(1000, 9999);
            }
        });
    }

    // Relationships
    public function jointAccount(): BelongsTo
    {
        return $this->belongsTo(JointAccount::class);
    }

    public function initiator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'initiated_by');
    }

    public function approvals(): HasMany
    {
        return $this->hasMany(JointAccountApproval::class);
    }

    // Helper methods
    public function requiresApproval(): bool
    {
        return $this->jointAccount->requiresApproval($this->amount);
    }

    public function getApprovalCount(): int
    {
        return $this->approvals()->where('action', 'approved')->count();
    }

    public function getRejectionCount(): int
    {
        return $this->approvals()->where('action', 'rejected')->count();
    }

    public function hasUserApproved(User $user): bool
    {
        return $this->approvals()
            ->where('approver_id', $user->id)
            ->where('action', 'approved')
            ->exists();
    }

    public function hasUserRejected(User $user): bool
    {
        return $this->approvals()
            ->where('approver_id', $user->id)
            ->where('action', 'rejected')
            ->exists();
    }

    public function canUserApprove(User $user): bool
    {
        // Check if user is a member with approval rights
        if (!$this->jointAccount->canUserApprove($user)) {
            return false;
        }

        // Check if user has already taken action
        if ($this->hasUserApproved($user) || $this->hasUserRejected($user)) {
            return false;
        }

        // Check if transaction is pending
        return $this->status === 'pending';
    }

    public function isFullyApproved(): bool
    {
        $required = $this->jointAccount->getRequiredApprovals();
        $received = $this->getApprovalCount();
        
        return $received >= $required;
    }

    public function approve(): void
    {
        if ($this->isFullyApproved()) {
            $this->update([
                'status' => 'approved',
                'approved_at' => now(),
                'approval_data' => [
                    'approved_by' => $this->approvals()->where('action', 'approved')->with('approver')->get(),
                    'approved_at' => now()
                ]
            ]);
        }
    }

    public function reject(): void
    {
        $this->update([
            'status' => 'rejected',
            'approval_data' => [
                'rejected_by' => $this->approvals()->where('action', 'rejected')->with('approver')->get(),
                'rejected_at' => now()
            ]
        ]);
    }

    public function complete(): void
    {
        $this->update([
            'status' => 'completed',
            'completed_at' => now()
        ]);
    }
} 