<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields    = ['name', 'email', 'password'];

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

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

    protected function hashPassword(array $data): array
    {
        // Hanya proses jika key 'password' ada DAN nilainya tidak kosong
        if (isset($data['data']['password']) && !empty($data['data']['password'])) {
            $data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
        } else {
            // Jika password kosong, hapus dari data agar tidak menimpa password yang ada
            unset($data['data']['password']);
        }
        return $data;
    }

    // Validation
    protected $validationRules = [
        'name'     => 'required|max_length[100]',
        'email'    => 'required|valid_email|max_length[100]|is_unique[admins.email,id,{id}]',
        'password' => 'required|min_length[8]',
    ];
}