<?php
declare(strict_types=1);

namespace App\Modules\HR\Models;

use App\Core\Model;
use App\Core\App;

class HrLoanInstallment extends Model
{
    protected static string $table = 'hr_loan_installments';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = false;

    protected static array $fillable = [
        'loan_id', 'installment_number', 'due_date', 'amount',
        'payroll_run_id', 'deducted_at', 'status', 'notes',
    ];

    public static function getForLoan(int $loanId): array
    {
        return static::query()
            ->where('loan_id', '=', $loanId)
            ->orderBy('installment_number', 'ASC')
            ->get();
    }

    public static function getNextPending(int $loanId): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM hr_loan_installments WHERE loan_id = ? AND status = 'pending' ORDER BY installment_number ASC LIMIT 1",
            [$loanId]
        );
    }

    public static function markDeducted(int $installmentId, ?int $payrollRunId = null): void
    {
        $db = App::getInstance()->db();
        $db->update('hr_loan_installments', [
            'payroll_run_id' => $payrollRunId,
            'deducted_at'    => date('Y-m-d H:i:s'),
            'status'         => 'deducted',
            'updated_at'     => date('Y-m-d H:i:s'),
        ], '`id` = ?', [$installmentId]);
    }
}
