<?php

namespace App\Models;

class PaymentAttemptModel extends TenantModel
{
    protected $table            = 'payment_attempts';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'purpose',
        'folio_id',
        'booking_id',
        'client_reference',
        'checkout_id',
        'checkout_url',
        'amount',
        'status',
        'provider_payment_type',
        'raw_response',
    ];

    /**
     * Unique per attempt, human-traceable, and namespaced by purpose so a
     * folio payment and a deposit can never collide even if both happened
     * to be generated in the same millisecond.
     */
    public function generateClientReference(string $purpose): string
    {
        return strtoupper(substr($purpose, 0, 4)) . '-' . date('YmdHis') . '-' . random_int(1000, 9999);
    }

    public function findByClientReference(string $clientReference): ?object
    {
        return $this->where('client_reference', $clientReference)->first();
    }
}
