<?php

namespace App\Models;

use CodeIgniter\Model;

class TransactionModel extends Model
{
    protected $table            = 'transactions';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useSoftDeletes   = true;

    protected $allowedFields    = [
        'uuid',
        'user_id',
        'event_id',
        'invoice_number',
        'transaction_date',
        'payment_type',
        'payment_url',
        'payment_status',
        'total_quantity',
        'subtotal',
        'total_discount',
        'handling_fee',
        'total_amount',
        'promotion_id'
    ];

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules = [
        'user_id'        => 'required|is_natural_no_zero',
        'event_id'       => 'required|is_natural_no_zero',
        'invoice_number' => 'required|max_length[100]|is_unique[transactions.invoice_number,id,{id}]',
        'payment_type'   => 'required|in_list[cash,va,transfer]',
        'payment_status' => 'required|in_list[pending,paid,canceled,rejected,deleted]',
        'total_quantity' => 'required|is_natural',
        'subtotal'       => 'required|numeric',
        'total_discount' => 'required|numeric',
        'handling_fee'   => 'required|numeric',
        'total_amount'   => 'required|numeric',
    ];


    public function search(array $filters = [], int $perPage = 10)
    {
        $builder = $this->select(
            'transactions.id, transactions.uuid, transactions.invoice_number, transactions.created_at, transactions.total_amount, transactions.payment_type, transactions.payment_status, ' .
            'users.name as user_name, events.name as event_name'
        )
        ->join('users', 'users.id = transactions.user_id', 'left')
        ->join('events', 'events.id = transactions.event_id', 'left');

        // Filter: Nama User
        if (!empty($filters['user_name'])) {
            $builder->like('users.name', $filters['user_name']);
        }

        // Filter: No Transaksi (Invoice)
        if (!empty($filters['invoice_number'])) {
            $builder->like('transactions.invoice_number', $filters['invoice_number']);
        }
        
        // Filter: Event Terkait
        if (!empty($filters['event_id'])) {
            $builder->where('transactions.event_id', $filters['event_id']);
        }
        
        // Filter: Gereja Terkait Event
        if (!empty($filters['church_id'])) {
            // Ini memerlukan join tambahan ke events table jika relasi church ada di sana
            $builder->where('events.church_id', $filters['church_id']);
        }

        // Filter: Status
        if (!empty($filters['payment_status'])) {
            $builder->where('transactions.payment_status', $filters['payment_status']);
        }

        // Filter: Status
        if (!empty($filters['payment_method'])) {
            $builder->where('transactions.payment_type', $filters['payment_method']);
        }

        // Filter: Range Tanggal
        if (!empty($filters['start_date'])) {
            $builder->where('DATE(transactions.created_at) >=', $filters['start_date']);
        }
        if (!empty($filters['end_date'])) {
            $builder->where('DATE(transactions.created_at) <=', $filters['end_date']);
        }

        if (isset($filters['admin_church_ids'])) {
            if ($filters['admin_church_ids'] !== null) {
                $builder->groupStart()
                    ->whereIn('events.church_id', $filters['admin_church_ids'])
                    ->orWhere('events.church_id IS NULL')
                ->groupEnd();
            }
        }

        // Urutkan dari yang terbaru
        $builder->orderBy('transactions.created_at', 'DESC');
        
        // Kembalikan hasil dengan paginasi
        return $builder->paginate($perPage);
    }
}