<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Expense extends Model
{
    use BelongsToTenant;

    public const STATUS_PENDING = 'pending';
    public const STATUS_APPROVED = 'approved';
    public const STATUS_REJECTED = 'rejected';
    public const STATUS_CANCELED = 'canceled';

    protected $fillable = [
        'tenant_id',
        'recorded_by',
        'branch_id',
        'expense_category_id',
        'is_recurring',
        'recurrence_frequency',
        'category',
        'amount',
        'spent_at',
        'payee',
        'method',
        'notes',
        'reference',
        'status',
        'approval_level_required',
        'current_approval_level',
        'approval_history',
        'submitted_at',
        'approved_by',
        'approved_at',
        'rejected_by',
        'rejected_at',
        'rejected_reason',
        'canceled_by',
        'canceled_at',
        'canceled_reason',
        'accounting_posted_at',
    ];

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
            'spent_at' => 'date',
            'is_recurring' => 'boolean',
            'approval_level_required' => 'integer',
            'current_approval_level' => 'integer',
            'approval_history' => 'array',
            'submitted_at' => 'datetime',
            'approved_at' => 'datetime',
            'rejected_at' => 'datetime',
            'canceled_at' => 'datetime',
            'accounting_posted_at' => 'datetime',
        ];
    }

    public function categoryModel(): BelongsTo
    {
        return $this->belongsTo(ExpenseCategory::class, 'expense_category_id');
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

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

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

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

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

    public function nextApprovalLevel(): int
    {
        return min((int) $this->approval_level_required, (int) $this->current_approval_level + 1);
    }

    public function approvalProgressLabel(): string
    {
        if ($this->status === self::STATUS_APPROVED) {
            return 'Approved';
        }

        if ($this->status === self::STATUS_REJECTED) {
            return 'Rejected';
        }

        if ($this->status === self::STATUS_CANCELED) {
            return 'Canceled';
        }

        return 'Level '.((int) $this->current_approval_level + 1).' of '.max(1, (int) $this->approval_level_required);
    }
}
