<?php
defined('BASEPATH') OR exit('No direct script access allowed');

if (!function_exists('az_check_device')) {
    /**
     * Cek apakah device (PC/HP) terdaftar untuk outlet ini
     * Return: array('allowed' => bool, 'device' => object|null)
     */
    function az_check_device($idoutlet = '') {
        $ci =& get_instance();
        $ci->load->database();

        $ip = $ci->input->ip_address();
        $ua = $ci->input->user_agent();
        $token = $ci->input->cookie('az_device_token');

        // Deteksi tipe device
        $device_type = 'PC';
        if (preg_match('/Mobile|Android|iPhone|iPad|iPod/i', $ua)) {
            $device_type = 'HP';
        }

        $where = array('status' => 1);
        if (strlen($idoutlet) > 0) {
            $where['idoutlet'] = $idoutlet;
        }

        // Prioritas cek: token > IP
        if (strlen($token) > 0) {
            $where['device_token'] = $token;
        } else {
            $where['ip_address'] = $ip;
        }

        $device = $ci->db->get_where('device_registry', $where)->row();

        if ($device) {
            // Update last seen
            $ci->db->where('iddevice', $device->iddevice);
            $ci->db->update('device_registry', array(
                'ip_address' => $ip,
                'user_agent' => $ua
            ));
            return array('allowed' => true, 'device' => $device);
        }

        return array('allowed' => false, 'device' => null, 'type' => $device_type);
    }
}

if (!function_exists('az_register_device')) {
    /**
     * Daftarkan device baru (hanya bisa dipanggil administrator)
     */
    function az_register_device($idoutlet, $device_type, $device_name, $iduser = null) {
        $ci =& get_instance();
        $ci->load->database();

        $token = bin2hex(random_bytes(32));
        $ip = $ci->input->ip_address();
        $ua = $ci->input->user_agent();

        $data = array(
            'idoutlet' => $idoutlet,
            'device_type' => $device_type,
            'device_name' => $device_name,
            'device_token' => $token,
            'ip_address' => $ip,
            'user_agent' => $ua,
            'iduser' => $iduser,
            'status' => 1,
            'created' => date('Y-m-d H:i:s')
        );

        $ci->db->insert('device_registry', $data);
        $insert_id = $ci->db->insert_id();

        // Set cookie token (berlaku 1 tahun)
        $ci->input->set_cookie('az_device_token', $token, 31536000);

        return array(
            'iddevice' => $insert_id,
            'token' => $token
        );
    }
}

if (!function_exists('az_get_device_type')) {
    function az_get_device_type() {
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        if (preg_match('/Mobile|Android|iPhone|iPad|iPod/i', $ua)) {
            return 'HP';
        }
        return 'PC';
    }
}