<?php
declare(strict_types=1);

namespace App\Modules\Cashier\Models;

use App\Core\Model;

class PaymentRequest extends Model
{
    protected static string $table = 'payment_requests';

    protected static array $fillable = [
        'request_number', 'member_id', 'payment_type', 'amount', 'currency',
        'description_ar', 'related_entity_type', 'related_entity_id', 'status',
        'payment_id', 'receipt_number', 'requested_by', 'processed_by', 'processed_at',
        'branch_id', 'notes',
    ];

    protected static bool $timestamps = true;
    protected static bool $softDelete = false;

    public static function pendingForMember(int $memberId, ?string $paymentType = null): ?array
    {
        $sql = "SELECT * FROM payment_requests WHERE member_id = ? AND status IN ('pending','processing') AND is_voided = 0";
        $params = [$memberId];
        if ($paymentType !== null) {
            $sql .= ' AND payment_type = ?';
            $params[] = $paymentType;
        }
        $sql .= ' ORDER BY id DESC LIMIT 1';
        return \App\Core\App::getInstance()->db()->selectOne($sql, $params);
    }

    public static function completedForMember(int $memberId, string $paymentType): ?array
    {
        return \App\Core\App::getInstance()->db()->selectOne(
            "SELECT * FROM payment_requests WHERE member_id = ? AND payment_type = ? AND status = 'completed' AND is_voided = 0 ORDER BY id DESC LIMIT 1",
            [$memberId, $paymentType]
        );
    }
}
