<?php

namespace App\Modules\Devices\Models;

use App\Modules\Devices\Entities\Device;
use CodeIgniter\Model;

/**
 * Device Model
 * 
 * Handles database operations for devices.
 */
class DeviceModel extends Model
{
    protected $table            = 'devices';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = Device::class;
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'device_code',
        'device_name',
        'api_key',
        'is_active',
        'last_seen_at',
        'latitude',
        'longitude',
        'radius_meters',
    ];

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

    // Validation
    protected $validationRules = [
        'device_code' => 'required|max_length[100]|is_unique[devices.device_code,id,{id}]',
        'device_name' => 'permit_empty|max_length[255]',
        'api_key'     => 'required|max_length[255]',
        'is_active'   => 'permit_empty|in_list[0,1]',
        'latitude'    => 'permit_empty|decimal',
        'longitude'   => 'permit_empty|decimal',
        'radius_meters' => 'permit_empty|integer|greater_than_equal_to[0]',
    ];

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

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    /**
     * Find device by device_code
     * 
     * @param string $deviceCode
     * @return Device|null
     */
    public function findByDeviceCode(string $deviceCode): ?Device
    {
        return $this->where('device_code', $deviceCode)->first();
    }

    /**
     * Find active device by device_code
     * 
     * @param string $deviceCode
     * @return Device|null
     */
    public function findActiveByDeviceCode(string $deviceCode): ?Device
    {
        return $this->where('device_code', $deviceCode)
            ->where('is_active', 1)
            ->first();
    }

    /**
     * Update last_seen_at timestamp
     * 
     * @param int $deviceId
     * @return bool
     */
    public function updateLastSeen(int $deviceId): bool
    {
        return $this->update($deviceId, [
            'last_seen_at' => date('Y-m-d H:i:s'),
        ]);
    }
}
