<?php

declare(strict_types=1);

namespace External\PompoBundle\Admin\Tabs;

use KupShop\AdminBundle\Admin\WindowTab;
use Query\Operator;

class PompoDropshipmentTab extends WindowTab
{
    protected $title = 'flapDropshipmentPompo';
    protected $template = 'window/dropshipment.pompo.tpl';

    public static function getTypes(): array
    {
        return [
            'Dropshipment' => 1,
        ];
    }

    public function getVars($smarty_tpl_vars)
    {
        return [
            'datago' => $smarty_tpl_vars['body']->value['data']['data']['pompo']['datago'] ?? [],
        ];
    }

    public function handleUpdate()
    {
        $data = $this->getData();

        $dataGo = [];

        $index = 1;
        foreach ($data['datago'] ?? [] as $key => $item) {
            if (!empty($item['delete']) || $key === 0) {
                continue;
            }

            if (empty($item['marketplace']) || empty($item['user']) || empty($item['password'])) {
                continue;
            }

            if (empty($item['country'])) {
                $item['country'] = null;
            }

            $dataGo[$index++] = $item;
        }

        $this->updateCustomData('datago', $dataGo);
    }

    public function getLabel()
    {
        return 'Pompo';
    }

    private function updateCustomData(string $key, mixed $data): void
    {
        if (!($id = (int) $this->getID())) {
            return;
        }

        $currentData = sqlQueryBuilder()
            ->select('data')
            ->from('dropshipment')
            ->where(Operator::equals(['id' => $id]))
            ->execute()->fetchOne();

        $currentData = json_decode($currentData ?: '', true) ?: [];

        $currentData['pompo'][$key] = $data;

        sqlQueryBuilder()
            ->update('dropshipment')
            ->directValues(['data' => json_encode($currentData)])
            ->where(Operator::equals(['id' => $id]))
            ->execute();
    }
}
