<?php
include_once __dir__ .  '/../core/LogEvent.php';
class KanbanDashboard 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 store()
    {
        $user_id = $this->getPostData('userId', FILTER_VALIDATE_INT);
        $process_id = $this->getPostData('processId', FILTER_VALIDATE_INT);
        $name = $this->getPostData('name');
        $color = $this->getPostData('color');
        $order = $this->getPostData('order', FILTER_VALIDATE_INT);

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

        if (is_null($order)) {
            $sql = "SELECT `order` FROM kanban_dashboard WHERE process_id = :process_id ORDER BY `order` DESC LIMIT 1";
            $stmt = parent::$conn->prepare($sql);
            $stmt->execute([':process_id' => $process_id]);
            $order = (int) $stmt->fetchColumn() + 1;
        }

        $sql = "INSERT INTO kanban_dashboard (process_id, name, color, `order`) VALUES (:process_id, :name, :color, :order)";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':process_id' => $process_id,
            ':name' => $name,
            ':color' => $color,
            ':order' => $order
        ]);

        $last_insert_id = parent::$conn->lastInsertId();
        $url = '';
        $title = "Nova etapa \"$name\" adicionada no dashboard Kanban";
        LogEvent::log($user_id, $last_insert_id, $url, $title, LogEvent::KANBAN_CREATE_STEP_PROCESS);
        
        return $this->getById($last_insert_id);
    }

    function update()
    {
        $id = $this->getPostData('id', FILTER_VALIDATE_INT);
        $process_id = $this->getPostData('processId', FILTER_VALIDATE_INT);
        $name = $this->getPostData('name');
        $color = $this->getPostData('color');
        $order = $this->getPostData('order', FILTER_VALIDATE_INT);
        $archived = $this->getPostData('archived', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);

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

        $sql = "UPDATE kanban_dashboard SET name = :name, color = :color, archived = :archived WHERE id = :id AND process_id = :process_id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([
            ':name' => $name,
            ':color' => $color,
            ':archived' => $archived,
            ':id' => $id,
            ':process_id' => $process_id
        ]);

        return $this->getById($id);
    }

    function list()
    {
        $process_id = $this->getGetData('processId', FILTER_VALIDATE_INT);
        if (!$process_id) {
            return ['type' => 'ERROR', 'message' => 'Invalid input data'];
        }

        $sql = "SELECT * FROM kanban_dashboard WHERE process_id = :process_id ORDER BY `order`";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':process_id' => $process_id]);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return ['type' => 'OK', 'result' => $result];
    }

    function delete()
    {
        $user_id = $this->getGetData('userId', FILTER_VALIDATE_INT);
        $id = $this->getGetData('id', FILTER_VALIDATE_INT);
        $process_id = $this->getGetData('processId', FILTER_VALIDATE_INT);
        
        if (!$id) {
            return ['type' => 'ERROR', 'message' => 'Invalid input data'];
        }

        $sql = "SELECT name FROM kanban_dashboard WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $id]);
        $kanban = $stmt->fetch(PDO::FETCH_ASSOC);        
        $step_name = $kanban['name'];

        $sql = "SELECT name FROM process_list WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $process_id]);
        $process = $stmt->fetch(PDO::FETCH_ASSOC);        
        $process_name = $process['name'];

        $sql = "DELETE FROM kanban_dashboard WHERE id = :id";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([':id' => $id]);        

        $url = '';
        $title = "Etapa \"$step_name\" removida do processo seletivo \"$process_name\"";
        LogEvent::log($user_id, $id, $url, $title, LogEvent::KANBAN_DELETE_STEP_PROCESS);

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

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

        return $result ? ['type' => 'OK', 'result' => $result] : ['type' => 'ERROR', 'message' => 'Record not found'];
    }

    function listAllItems() {

        $process_id = $this->getGetData('processId', FILTER_VALIDATE_INT);
        $sql = "SELECT KI.id, KI.data, KD.name, KD.order FROM kanban_item AS KI
            LEFT JOIN kanban_dashboard AS KD ON KD.id = KI.step_id
            WHERE process_id = ? AND KI.type = 'item' ORDER BY KD.order ASC";
        
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$process_id]);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $sql = "SELECT count(*) AS total, id, `name` FROM kanban_dashboard WHERE process_id = ? GROUP BY id ORDER BY `order` LIMIT 10";
        $stmt = parent::$conn->prepare($sql);
        $stmt->execute([$process_id]);
        $result_total = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return [
            'type' => 'OK', 
            'data' =>  [
                'steps' => $result_total,
                'items' => $result
            ]
        ];

    }

}
