<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields    = [
        'name',
        'email',
        'phone_number',
        'password',
        'kta_number',
        'birth_date',
        //'status',
        'email_verified_at',
        'phone_verified_at',
    ];

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

    // Callbacks untuk hashing password otomatis
    protected $beforeInsert = ['hashPassword', 'cleanKtaNumber'];
    protected $beforeUpdate = ['hashPassword', 'cleanKtaNumber'];

    protected function hashPassword(array $data): array
    {
        if (isset($data['data']['password'])) {
            $data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
        }
        return $data;
    }

    // Validation (digunakan di controller)
    protected $validationRules = [
        'name'         => 'required|min_length[3]|max_length[255]',
        'email'        => 'required|valid_email|max_length[100]|is_unique[users.email,id,{id}]',
        'phone_number' => 'required|min_length[10]|max_length[20]',
        'password'     => 'required|min_length[8]',
        'kta_number'   => 'permit_empty|max_length[50]',
        'birth_date'   => 'permit_empty|valid_date',
        //'status'       => 'in_list[unverified,verified]',
    ];

    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 = 10)
    {
        $builder = $this->select('id, name, email, phone_number, kta_number, email_verified_at, phone_verified_at');

        if (!empty($filters['name'])) { $builder->like('name', $filters['name']); }
        if (!empty($filters['email'])) { $builder->like('email', $filters['email']); }
        if (!empty($filters['phone_number'])) { $builder->like('phone_number', $filters['phone_number']); }
        if (!empty($filters['kta_number'])) { $builder->like('kta_number', $filters['kta_number']); }
        if (!empty($filters['birth_date'])) { $builder->where('birth_date', $filters['birth_date']); }
        
        $builder->orderBy('created_at', 'DESC');
        return $builder->paginate($perPage);
    }
}