<?php

namespace App\Models;

use CodeIgniter\Model;

class ServerModel extends Model
{
    protected $table = 'server';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;

    protected $returnType = 'array';
    protected $useSoftDeletes = true;

    protected $allowedFields = [
        'server_name',
        'kepemilikan_dropdown',
        'kepemilikan_lainnya',
        'serah_terima',
        'penanggung_jawab',
        'cpu_core',
        'ram',
        'storage',
        'status',
        'operating_system',
        'server_date',
        'last_evaluated',
        'next_maintenance'
    ];

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

    protected $validationRules = [
        'server_name' => 'required|max_length[255]',
        'kepemilikan_dropdown' => 'required|max_length[255]',
        'cpu_core' => 'required|integer',
        'ram' => 'required|integer',
        'storage' => 'required|integer',
        'status' => 'required|max_length[50]',
        'operating_system' => 'required|max_length[255]',
        'server_date' => 'required|valid_date',
        'last_evaluated' => 'required|valid_date',
        'next_maintenance' => 'required|valid_date',
    ];

    protected $validationMessages = [];
    protected $skipValidation = false;

    // Custom method to handle the conditional fields
    public function processServerData(array $data)
    {
        // If kepemilikan is not "lainnya", clear the lainnya field
        if ($data['kepemilikan_dropdown'] !== 'lainnya') {
            $data['kepemilikan_lainnya'] = null;
            $data['serah_terima'] = null;
            $data['penanggung_jawab'] = null;
        }

        return $data;
    }
}
