<?php

namespace App\Models;

use App\Enums\EmployeeAdvanceStatus;
use App\Models\Concerns\HasRejection;
use App\Models\Concerns\InteractsWithActivityLog;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[Guarded(['id'])]
#[Appends([
    'amount_formatted',
    'can_pay',
    'can_verify',
    'created_at_formatted',
    'due_date_formatted',
    'due_date_input',
    'employee_name',
    'is_editable',
    'paid_amount_formatted',
    'rejection_reason',
    'remaining_amount',
    'remaining_amount_formatted',
    'status_label',
])]
class EmployeeAdvance extends Model
{
    // 1. Use Trait
    use HasFactory, HasRejection, InteractsWithActivityLog;

    // 2. Casting
    protected function casts(): array
    {
        return [
            'amount' => 'integer',
            'due_date' => 'date',
            'paid_amount' => 'integer',
            'paid_at' => 'datetime',
            'status' => EmployeeAdvanceStatus::class,
            'verified_at' => 'datetime',
        ];
    }

    // 3. Scope (grouped by column, then alphabetical)
    // Column Group: status
    #[Scope]
    protected function approved(Builder $query): void
    {
        $query->where('status', EmployeeAdvanceStatus::APPROVED);
    }

    #[Scope]
    protected function paid(Builder $query): void
    {
        $query->where('status', EmployeeAdvanceStatus::PAID);
    }

    #[Scope]
    protected function partiallyPaid(Builder $query): void
    {
        $query->where('status', EmployeeAdvanceStatus::PARTIALLY_PAID);
    }

    #[Scope]
    protected function pending(Builder $query): void
    {
        $query->where('status', EmployeeAdvanceStatus::PENDING);
    }

    #[Scope]
    protected function rejected(Builder $query): void
    {
        $query->where('status', EmployeeAdvanceStatus::REJECTED);
    }

    // 4. Attribute
    public function amountFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->amount, 0, ',', '.'),
        );
    }

    public function canPay(): Attribute
    {
        return Attribute::make(
            get: fn () => in_array($this->status, [EmployeeAdvanceStatus::APPROVED, EmployeeAdvanceStatus::PARTIALLY_PAID], true),
        );
    }

    public function canVerify(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->status === EmployeeAdvanceStatus::PENDING,
        );
    }

    public function createdAtFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->created_at?->translatedFormat('l, d F Y H:i'),
        );
    }

    public function dueDateFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->due_date?->translatedFormat('l, d F Y'),
        );
    }

    public function dueDateInput(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->due_date?->format('Y-m-d'),
        );
    }

    public function employeeName(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->employee?->user?->profile?->full_name
                ?? $this->employee?->user?->username,
        );
    }

    public function isEditable(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->status === EmployeeAdvanceStatus::PENDING,
        );
    }

    public function paidAmountFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->paid_amount, 0, ',', '.'),
        );
    }

    public function rejectionReason(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->rejection?->reason,
        );
    }

    public function remainingAmount(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->amount - $this->paid_amount,
        );
    }

    public function remainingAmountFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format($this->remaining_amount, 0, ',', '.'),
        );
    }

    public function statusLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->status?->label(),
        );
    }

    // 5. Relation
    public function cashTransaction(): BelongsTo
    {
        return $this->belongsTo(CashTransaction::class);
    }

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

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

    public function payments(): HasMany
    {
        return $this->hasMany(EmployeeAdvancePayment::class)->latest('paid_at');
    }

    public function repaymentCashTransaction(): BelongsTo
    {
        return $this->belongsTo(CashTransaction::class, 'repayment_cash_transaction_id');
    }

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