<?php

final class DModelModuleTrackingCode extends Model
{
    public function getFieldsQuery(array $data)
    {
        [
            'title' => $title,
            'layout_id' => $layout_id,
            'all_layouts' => $all_layouts,
            'position' => $position,
            'status' => $status,
            'script' => $script,
        ] = $data;

        $title = $this->db->escape($title);
        $layout_id = (int) $layout_id;
        $all_layouts = (int) $all_layouts;
        $position = (int) $position;
        $status = (int) $status;
        $script = $this->db->escape($script);

        return " title='$title', layout_id=$layout_id, all_layouts=$all_layouts, position=$position, status=$status, script='$script'";
    }

    public function add(array $data)
    {
        foreach ($data as $item) {
            if (isset($item['tracking_code_id'])) {
                $this->edit($item['tracking_code_id'], $item);
                continue;
            }

            $sql = "INSERT INTO " . DB_PREFIX . "tracking_code SET {$this->getFieldsQuery($item)}";
            $this->db->query($sql);
        }
    }

    public function edit(int $id, array $data)
    {
        $sql = "UPDATE " . DB_PREFIX . "tracking_code SET {$this->getFieldsQuery($data)} WHERE tracking_code_id = $id";
        $this->db->query($sql);
    }

    public function delete($id)
    {
        if (is_array($id)) {
            foreach ($id as $value) {
                $this->delete($value);
            }

            return;
        }

        $sql = "DELETE FROM " . DB_PREFIX . "tracking_code WHERE tracking_code_id = $id";
        $this->db->query($sql);
    }

    public function normalizeData($rows) {
        return array_map(function ($row) {
            $scriptArrayJson = json_decode('["'.$row['script'].'"]', JSON_UNESCAPED_UNICODE);
            if ($scriptArrayJson && isset($scriptArrayJson[0])) {
                $row['script'] = $scriptArrayJson[0];
            }
            return $row;
        }, $rows);
    }

    public function getList()
    {
        $sql = "SELECT * FROM " . DB_PREFIX . "tracking_code";
        $query = $this->db->query($sql);
        return $this->normalizeData((array) $query->rows);
    }

    public function getListEnabled()
    {
        $sql = "SELECT * FROM " . DB_PREFIX . "tracking_code WHERE status = 1";
        $query = $this->db->query($sql);
        return $this->normalizeData((array) $query->rows);
    }
}
