<?php

class Artsections extends Window
{
    protected $tableName = 'articles_branches';
    protected $show_on_web = 'articlesSection';

    public function __construct()
    {
        $this->defaults = ['date' => date('Y-m-d H:i'),
            'behaviour' => '1',
            'orderby' => 'date',
            'orderdir' => 'ASC',
            'top_branch' => null,
        ];
    }

    public function get_vars()
    {
        $vars = parent::get_vars();
        $pageVars = getVal('body', $vars);

        $acn = $this->getAction();
        $ID = $this->getID();
        $pageVars['tree'] = $this->articlesSections(null, 0, $ID);

        if ($acn == 'remove') {
            $SQL = sqlQuery('SELECT * FROM '.getTableName('articles_branches')." WHERE id='{$ID}' ");
            foreach ($SQL as $row) {
                $pageVars['data'] = $row;
            }
            $pageVars['acn'] = 'erase';
        }

        $vars['body'] = $pageVars;

        return $vars;
    }

    public function getData()
    {
        $data = parent::getData();
        if (isset($data['template'])) {
            $data['template'] = !preg_match('/^[a-zA-Z0-9_\-.]+$/', $data['template']) ? null : $data['template'];
        }
        if (isset($data['items_per_page'])) {
            $data['items_per_page'] = empty($data['items_per_page']) || !is_numeric($data['items_per_page']) ? null : (int) $data['items_per_page'];
        }
        if (empty($data['top_branch'])) {
            $data['top_branch'] = null;
        }

        return $data;
    }

    public function handleUpdate()
    {
        clearCache('article-sections-', true);

        $newBranchId = $_POST['data']['top_branch'] ?? null;
        $childrenIds = $this->getDescendantCategories($this->getID());

        if (in_array($newBranchId, $childrenIds)) {
            $this->returnError('Nelze zvolit jako nadřazenou sekci některou z podsekcí!');
        }

        return parent::handleUpdate();
    }

    public function getDescendantCategories($topBranch): array
    {
        return sqlFetchAll(sqlQuery(
            'WITH RECURSIVE cte (level, id) AS (
          SELECT 0, SR1.top_branch
          FROM articles_branches SR1
          WHERE SR1.top_branch = :top_branch
          UNION ALL
          SELECT cte.level + 1, SR2.id
          FROM articles_branches SR2
                   INNER JOIN cte ON (cte.id = SR2.top_branch)
          WHERE cte.level < 50
      )
      SELECT id
      FROM cte ORDER BY level', ['top_branch' => $topBranch]), ['id' => 'id']);
    }

    public function handleDelete()
    {
        clearCache('article-sections-', true);

        $IDsec = $this->getID();
        $IDsecSel = getVal('IDsecSel');
        if ($IDsecSel > 0) {
            @sqlQuery('UPDATE '.getTableName('articles_relation')."
					SET id_branch='".$IDsecSel."'
					WHERE id_branch='".$IDsec."' ");
        } elseif ($IDsecSel == 0) {
            @sqlQuery('DELETE
					FROM '.getTableName('articles_relation')."
					WHERE id_branch='".$IDsec."' ");
        }

        $SQL = @sqlQuery('DELETE
					FROM '.getTableName('articles_branches')."
					WHERE id='".$IDsec."' ");
        writeDownActivity(sprintf(translate('activityDeleted'), $IDsec));
        redirect('launch.php?s=artsections.php&acn=erased&ErrStr='.urlencode(translate('note_5')));
    }

    public function articlesSections($topCat, $Pos = 0, $ignored = null)
    {
        $SQL = sqlQueryBuilder()
            ->select('ab.id, ab.name, ab.descr, ab.figure')
            ->from('articles_branches', 'ab')
            ->where(\Query\Operator::equalsNullable(['ab.top_branch' => $topCat]))
            ->orderBy('ab.name', 'ASC')
            ->execute();

        $data = [];
        foreach ($SQL as $key => $row) {
            if ($ignored == null || $ignored != $row['id']) {
                $data[$key]['id'] = $row['id'];
                $data[$key]['title'] = $row['name'];
                $data[$key]['figure'] = $row['figure'];
                $data[$key]['level'] = $Pos;
                $data[$key]['submenu'] = $this->articlesSections($row['id'], $Pos + 1, $ignored = null);
            }
        }

        return $data;
    }
}

$artsections = new Artsections();
$artsections->run();
