<?php
$page_title = 'Daftarkan Perangkat';
require_once('includes/load.php');

// akses minimal level 2
page_require_level(2);

// ambil data karyawan
$all_employees = find_all('employees');

// ambil data karyawan yg sudah punya device_id
$registered_devices = find_all('employees', 'device_id IS NOT NULL');

if (isset($_POST['register_device'])) {
    $req_fields = array('employee_id', 'device_id');
    validate_fields($req_fields);

    if (empty($errors)) {
        $employee_id = (int)$_POST['employee_id'];
        $device_id   = remove_junk($db->escape($_POST['device_id']));

        // validasi device_id
        if (empty($device_id) || strlen($device_id) < 10) {
            $session->msg('d', 'Device ID tidak valid.');
            redirect('register_device.php', false);
        }

        // cek apakah device_id sudah dipakai karyawan lain
        $check_device_query = $db->query("SELECT COUNT(*) AS count FROM employees WHERE device_id = '{$device_id}' AND id != '{$employee_id}'");
        $device_exists = $db->fetch_assoc($check_device_query);

        if ($device_exists['count'] > 0) {
            $session->msg('d', 'Device ini sudah terdaftar untuk karyawan lain.');
            redirect('register_device.php', false);
        }
        
        // Cek apakah device_id yang dikirim sama dengan yang sudah terdaftar
        $current_device_query = $db->query("SELECT device_id FROM employees WHERE id = '{$employee_id}'");
        $current_device = $db->fetch_assoc($current_device_query);

        if ($current_device['device_id'] === $device_id) {
            $session->msg('w', "Perangkat ini sudah terdaftar untuk karyawan yang dipilih.");
            redirect('register_device.php', false);
        }

        // simpan device_id ke tabel employees
        $query = "UPDATE employees SET device_id = ? WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->bind_param("si", $device_id, $employee_id);

        if ($stmt->execute()) {
            $session->msg('s', "Perangkat berhasil didaftarkan!");
            redirect('register_device.php', false);
        } else {
            $session->msg('d', "Gagal mendaftarkan perangkat. Coba lagi.");
            redirect('register_device.php', false);
        }
        $stmt->close();
    } else {
        $session->msg("d", $errors);
        redirect('register_device.php', false);
    }
}
?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong><span class="glyphicon glyphicon-phone"></span>
                <span>Daftarkan Perangkat Karyawan</span></strong>
            </div>
            <div class="panel-body">
                <form method="post" action="register_device.php" class="clearfix">
                    <div class="form-group">
                        <label for="employee_id">Pilih Karyawan</label>
                        <select class="form-control" name="employee_id" required>
                            <option value="">-- Pilih Karyawan --</option>
                            <?php foreach ($all_employees as $emp): ?>
                                <option value="<?php echo (int)$emp['id']; ?>" <?php echo (!empty($emp['device_id'])) ? 'data-device="'.$emp['device_id'].'"' : ''; ?>>
                                    <?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?>
                                    <?php echo (!empty($emp['device_id'])) ? '(Sudah terdaftar)' : ''; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Device ID</label>
                        <input type="text" class="form-control" name="device_id" id="device-id" readonly required>
                        <small class="text-muted">Device ID otomatis terbaca dari perangkat/browser ini.</small>
                    </div>

                    <div class="form-group">
                        <div class="alert alert-warning">
                            <strong>Perhatian:</strong> Pastikan karyawan mendaftar dari perangkat miliknya sendiri.
                        </div>
                    </div>

                    <button type="submit" name="register_device" class="btn btn-primary">
                        <span class="glyphicon glyphicon-ok"></span> Daftarkan Perangkat
                    </button>
                    <a href="profile.php" class="btn btn-default">
                        <span class="glyphicon glyphicon-chevron-left"></span> Batal
                    </a>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="panel panel-info">
            <div class="panel-heading">
                <strong><span class="glyphicon glyphicon-list"></span>
                <span>Perangkat Terdaftar</span></strong>
            </div>
            <div class="panel-body" style="max-height: 400px; overflow-y: auto;">
                <?php if ($registered_devices): ?>
                    <ul class="list-group">
                        <?php foreach ($registered_devices as $device): ?>
                            <li class="list-group-item">
                                <strong><?php echo htmlspecialchars($device['first_name'] . ' ' . $device['last_name']); ?></strong>
                                <br>
                                <small>Device ID: <?php echo htmlspecialchars(substr($device['device_id'], 0, 25)); ?>...</small>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p class="text-center">Belum ada perangkat terdaftar</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', async function() {
    const deviceInput = document.getElementById('device-id');

    async function generateDeviceId() {
        // Hanya menggunakan user agent untuk stabilitas
        let raw = navigator.userAgent;
        const msgUint8 = new TextEncoder().encode(raw);
        const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
        return hashHex;
    }

    const deviceId = await generateDeviceId();
    deviceInput.value = deviceId;
});
</script>

<?php include_once('layouts/footer.php'); ?>