<?php

namespace App\Domain\HR\Models;

use App\Domain\HR\Enums\CompensationStatus;
use App\Domain\HR\Enums\CompensationType;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Domain\Shared\Traits\BelongsToBranch;

class TrainerCompensation extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes, BelongsToBranch;

    protected $table = 'trainer_compensations';

    protected $fillable = [
        'academy_id', 'branch_id',
        'trainer_id',
        'training_session_id',
        'attendance_record_id',
        'payslip_item_id',
        'date',
        'type',
        'description',
        'quantity',
        'rate',
        'amount',
        'status',
        'approved_by',
        'approved_at',
        'notes',
        'metadata',
        'created_by',
    ];

    protected $casts = [
        'type' => CompensationType::class,
        'status' => CompensationStatus::class,
        'date' => 'date',
        'quantity' => 'decimal:2',
        'rate' => 'integer',
        'amount' => 'integer',
        'approved_at' => 'datetime',
        'metadata' => 'array',
    ];

    // --- Relationships ---

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

    public function session(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Training\Models\TrainingSession::class, 'training_session_id');
    }

    public function attendanceRecord(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Attendance\Models\AttendanceRecord::class, 'attendance_record_id');
    }

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

    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'created_by');
    }

    // --- Scopes ---

    public function scopePending(Builder $query): Builder
    {
        return $query->where('status', CompensationStatus::Pending->value);
    }

    public function scopeApproved(Builder $query): Builder
    {
        return $query->where('status', CompensationStatus::Approved->value);
    }

    public function scopeForPeriod(Builder $query, string $start, string $end): Builder
    {
        return $query->whereBetween('date', [$start, $end]);
    }
}
