<?php
declare(strict_types=1);

namespace App\Modules\Installments\Models;

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

class InstallmentScheduleItem extends Model
{
    protected static string $table = 'installment_schedule';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;

    protected static array $fillable = [
        'installment_plan_id', 'installment_number', 'due_date',
        'amount', 'principal', 'interest', 'remaining_after',
        'paid_amount', 'payment_id', 'status', 'paid_at',
    ];

    public static function getForPlan(int $planId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT s.*, py.receipt_id, r.receipt_number
             FROM installment_schedule s
             LEFT JOIN payments py ON py.id = s.payment_id
             LEFT JOIN receipts r ON r.id = py.receipt_id
             WHERE s.installment_plan_id = ?
             ORDER BY s.installment_number ASC",
            [$planId]
        );
    }

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

    public static function getRemainingBalance(int $planId): string
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT COALESCE(SUM(amount - paid_amount), 0) as remaining FROM installment_schedule WHERE installment_plan_id = ? AND status IN ('pending','overdue')",
            [$planId]
        );
        return $row['remaining'] ?? '0.00';
    }

    public static function getOverdueForPlan(int $planId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM installment_schedule WHERE installment_plan_id = ? AND status = 'pending' AND due_date < CURDATE() ORDER BY installment_number ASC",
            [$planId]
        );
    }
}