<?php
class KanbanCrmDashboardOp extends Core
{
    private function getPostData($key, $filter = FILTER_SANITIZE_SPECIAL_CHARS)
    {
        return filter_input(INPUT_POST, $key, $filter);
    }

    private function getGetData($key, $filter = FILTER_SANITIZE_SPECIAL_CHARS)
    {
        return filter_input(INPUT_GET, $key, $filter);
    }

    function addItems()
    {
        $step_id = $this->getPostData('stepId', FILTER_VALIDATE_INT);
        $group_id = $this->getPostData('groupId', FILTER_VALIDATE_INT);
        $group = $this->getPostData('group', FILTER_DEFAULT);
        $insert_last = $this->getPostData('insertLast', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
        $items = $this->getPostData('items', FILTER_DEFAULT);

        if (!$step_id || !$items) {
            return ['type' => 'ERROR', 'message' => 'Invalid input data'];
        }

        $sql = "SELECT * FROM kanban_crm WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $step_id]);

        if ($stmt->rowCount() === 0) {
            return ['type' => 'ERROR', 'result' => 'No records found'];
        }

        $order = 0;

        if ($group)
            $group_id = $this->createGroup(json_decode($group, true), $step_id);

        if ($insert_last)
            $order = $this->getLastOrder($step_id);

        $sql = "INSERT INTO kanban_crm_item(step_id, name, type, data, group_id, visible, `order`) 
                VALUES(:step_id, :name, :type, :data, :group_id, :visible, :order)";
        $stmt = parent::$conn->prepare($sql);
        $items = json_decode($items, true);

        foreach ($items as $index => $item) {
            $stmt->execute([
                ':step_id' => $step_id,
                ':name' => $item['name'],
                ':type' => $item['type'],
                ':data' => json_encode($item['data']),
                ':group_id' => $group_id,
                ':visible' => $group_id ? 0 : 1,
                ':order' => $order + $index
            ]);
        }

        $lastInsertId = parent::$conn->lastInsertId();

        return [
            'type' => 'OK',
            'result' => $this->getById($lastInsertId)
        ];
    }

    function moveToGroup()
    {
        $id = $this->getPostData('id', FILTER_VALIDATE_INT);
        $group_id = $this->getPostData('groupId', FILTER_VALIDATE_INT);

        if (!$id || !$group_id) {
            return ['type' => 'ERROR', 'message' => 'Invalid input data'];
        }

        $group = $this->getById($group_id);
        $sql = "UPDATE kanban_crm_item SET visible = 0, step_id = :step_id, group_id = :group_id, 
                order_group = 999, `order` = 999 WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':step_id' => $group['step_id'],
            ':group_id' => $group_id,
            ':id' => $id
        ]);

        return ['type' => 'OK'];
    }

    private function createGroup($group, $step_id)
    {
        $sql = "INSERT INTO kanban_crm_item(step_id, name, type, visible) VALUES(:step_id, :name, :type, :visible)";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':step_id' => $step_id,
            ':name' => $group['name'],
            ':type' => 'group',
            ':visible' => 1
        ]);

        return parent::$conn->lastInsertId();
    }

    private function getById($id)
    {
        $sql = "SELECT * FROM kanban_crm_item WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    private function getLastOrder($step_id)
    {
        $sql = "SELECT `order` FROM kanban_crm_item WHERE step_id = :step_id ORDER BY `order` DESC LIMIT 1";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':step_id' => $step_id]);
        return ((int) $stmt->fetchColumn()) + 1;
    }

    function moveStep()
    {
        $orders = $this->getPostData('orders', FILTER_DEFAULT);

        if (!$orders) {
            return ['type' => 'ERROR', 'message' => 'Invalid input data'];
        }

        $orders = json_decode($orders, true);
        $sql = "UPDATE kanban_crm SET `order` = :order WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);

        foreach ($orders as $order) {
            $stmt->execute([
                ':id' => $order['id'],
                ':order' => $order['order']
            ]);
        }

        return ['type' => 'OK'];
    }
    
}
