<?php

class UsersImporter extends BaseDataImporter
{
    private $newUsers = [];

    public function isOnlyForAdmin(): bool
    {
        return true;
    }

    public function import($data)
    {
        $data = json_decode($data, JSON_OBJECT_AS_ARRAY);
        $cfmpUsers = $data['cfmp'];
        $cfsettignsUsers = $data['cfsettings'];
        $this->importCfSettingsUsers($cfsettignsUsers);
        $this->importCfmpUsers($cfmpUsers);
    }

    private function importCfSettingsUsers($data)
    {
        foreach ($data as $user) {
            $this->settingsDb->reset_query();
            $filter = ['username' => $user['username']];
            $userExist = $this->settingsDb->get_where('users', $filter);

            $user['external'] = boolval($user['external']) == true ? 't' : 'f';
            $user['active'] = boolval($user['active']) == true ? 't' : 'f';

            if ($userExist->num_rows() == 0) {
                $this->settingsDb->insert('users', $user);
            } elseif ($this->skipDuplicates == 0) {
                $this->settingsDb->update('users', $user, $filter);
            }
        }
    }

    private function importCfmpUsers($data)
    {
        foreach ($data as $user) {
            $filter = ['username' => $user['username']];
            $userExist = $this->db->get_where('users', $filter);

            //delete old ID from import data
            $oldId = $user['id'];
            unset($user['id']);
            if ($userExist->num_rows() == 0) {
                $this->db->insert('users', $user);
                $this->newUsers[$user['username']] = $this->db->insert_id();
            } elseif ($this->skipDuplicates == 0) {
                $this->db->update('users', $user, $filter);
                $this->newUsers[$user['username']] = $oldId;
            }
        }
    }
}
