<?php

namespace App\Models;

use CodeIgniter\Model;

class PaymentModel extends Model
{
    protected $table      = 'payments';
    protected $primaryKey = 'id_payment';
    protected $returnType = 'array';

    protected $useTimestamps = false;
    protected $createdField  = 'created_at';
    protected $updatedField  = null;

    protected $allowedFields = [
        'id_order',
        'id_payment_method',
        'tanggal_bayar',
        'jumlah_bayar',
        'bukti_bayar',
        'status'
    ];

    protected $validationRules = [
        'id_order'          => 'required|integer',
        'id_payment_method' => 'required|integer',
        'tanggal_bayar'     => 'required',
        'jumlah_bayar'      => 'required|decimal'
    ];

    /**
     * Semua pembayaran berdasarkan Order
     */
    public function getByOrder($orderId)
    {
        return $this->select('
                payments.*,
                payment_methods.nama_metode
            ')
            ->join(
                'payment_methods',
                'payment_methods.id_payment_method = payments.id_payment_method'
            )
            ->where('payments.id_order', $orderId)
            ->orderBy('payments.tanggal_bayar', 'ASC')
            ->findAll();
    }

    /**
     * Total pembayaran
     */
    public function getTotalPaid($orderId)
    {
        $row = $this->selectSum('jumlah_bayar')
            ->where('id_order', $orderId)
            ->where('status', 'verified')
            ->first();

        return (float) ($row['jumlah_bayar'] ?? 0);
    }

    /**
     * Pembayaran terakhir
     */
    public function getLastPayment($orderId)
    {
        return $this->where('id_order', $orderId)
            ->orderBy('tanggal_bayar', 'DESC')
            ->first();
    }
}
