<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;

class PaymentTransaction extends BaseModel
{
    protected $table = 'payment_transactions';

    // ✅ CI: useTimestamps = true (created_at/updated_at)
    public $timestamps = false;

    protected $fillable = [
        'transaction_id',
        'payment_id',
        'transaction_date',
        'amount',
        'payment_method',
        'payment_status',
        'transaction_fee',
        'payment_reference',
        'is_full_payment',
        'school_year',
        'semester',
    ];

    protected $casts = [
        'payment_id'        => 'integer',
        'amount'            => 'decimal:2', // adjust precision if needed
        'transaction_fee'   => 'decimal:2', // adjust precision if needed
        'transaction_date'  => 'datetime',
        'is_full_payment'   => 'boolean',
    ];

    /* Optional relationship */
    public function payment()
    {
        return $this->belongsTo(Payment::class, 'payment_id');
    }

    /* =========================
     * CI method equivalents
     * ========================= */

    public static function getTransactionsByPaymentId(int $paymentId): array
    {
        return static::query()
            ->where('payment_id', $paymentId)
            ->orderByDesc('transaction_date')
            ->get()
            ->toArray();
    }

    public static function getTransactionById(string $transactionId): ?self
    {
        return static::query()
            ->where('transaction_id', $transactionId)
            ->first();
    }

    /**
     * Update payment_status by transaction_id (not PK).
     */
    public static function updateTransactionStatus(string $transactionId, string $status): bool
    {
        return static::query()
            ->where('transaction_id', $transactionId)
            ->update(['payment_status' => $status]) >= 0;
    }

    public static function getTotalPaidByPaymentId(int $paymentId): float
    {
        $sum = static::query()
            ->where('payment_id', $paymentId)
            ->sum('amount');

        return (float) $sum;
    }

    public static function updateTransactionFee(string $transactionId, float $transactionFee): bool
    {
        return static::query()
            ->where('transaction_id', $transactionId)
            ->update(['transaction_fee' => $transactionFee]) >= 0;
    }

    public static function getLatestTransactionByPaymentId(int $paymentId): ?self
    {
        return static::query()
            ->where('payment_id', $paymentId)
            ->orderByDesc('transaction_date')
            ->first();
    }
}
