<?php

namespace App\Models;

use CodeIgniter\Model;

class ParticipantModel extends Model
{
    protected $table            = 'participants';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useSoftDeletes   = false; // Tidak ada deleted_at

    protected $allowedFields    = [
        'user_id', 
        'transaction_id', 
        'event_package_id',
        'church_id', 
        'church_name',
        'qr_number', 
        'qr_image_path',
        'title', 
        'name', 
        'kta_number', 
        'birth_date', 
        'phone_number', 
        'email', 
        'gender'
    ];

    protected $beforeInsert = ['cleanKtaNumber'];
    protected $beforeUpdate = ['cleanKtaNumber'];

    protected $useTimestamps = true; // Hanya ada created_at
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    protected function cleanKtaNumber(array $data): array
    {
        // Pastikan helper sudah dimuat
        helper('general');

        if (isset($data['data']['kta_number'])) {
            $data['data']['kta_number'] = strip_leading_zeros($data['data']['kta_number']);
        }
        return $data;
    }


    public function search(array $filters = [], int $perPage = 25): array
    {
        $builder = $this->select(
            'participants.*, ' .
            'transactions.uuid as transaction_uuid, transactions.invoice_number, transactions.payment_status, ' .
            'users.name as user_name, ' .
            'events.name as event_name, ' .
            'event_packages.name as package_name, ' .
            'churches.name as church_db_name'
        )
        ->join('transactions', 'transactions.id = participants.transaction_id', 'left')
        ->join('users', 'users.id = transactions.user_id', 'left')
        ->join('events', 'events.id = transactions.event_id', 'left')
        ->join('event_packages', 'event_packages.id = participants.event_package_id', 'left')
        ->join('churches', 'churches.id = participants.church_id', 'left');

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

        if (!empty($filters['phone'])) { 
            $builder->like('participants.phone_number', $filters['phone']); 
        }

        if (!empty($filters['email'])) { 
            $builder->like('participants.email', $filters['email']); 
        }

        if (!empty($filters['church'])) { 
            $builder->groupStart()->like('churches.name', 
                $filters['church'])->orLike('participants.church_name', 
                $filters['church'])->groupEnd(); 
        }

        if (!empty($filters['kta_number'])) { 
            $builder->where('participants.kta_number', $filters['kta_number']); 
        }

        if (!empty($filters['birth_date'])) { 
            $builder->where('participants.birth_date', $filters['birth_date']); 
        }

        if (!empty($filters['event_id'])) { 
            $builder->where('transactions.event_id', $filters['event_id']); 
        }

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

        if (!empty($filters['start_date'])) { 
            $builder->where('DATE(participants.created_at) >=', $filters['start_date']); 
        }

        if (!empty($filters['end_date'])) { 
            $builder->where('DATE(participants.created_at) <=', $filters['end_date']); 
        }

        if (!empty($filters['qr_number'])) { 
            $builder->where('participants.qr_number', $filters['qr_number']); 
        }

        if (!empty($filters['invoice_number'])) { 
            $builder->like('transactions.invoice_number', $filters['invoice_number']); 
        }
        // ...

        $builder->orderBy('participants.created_at', 'DESC');

        if ($perPage <= 0) {
            return $builder->findAll();
        }

        // Jika tidak, gunakan paginasi seperti biasa.
        return $builder->paginate($perPage);
    } 
}