<?php

/**
 * Class represents records from table billing_plan_category
 * {autogenerated}
 * @property int $billing_plan_category_id PK
 * @property string|null $title
 * @property string|null $description
 * @property int|null $parent_id
 * @property int|null $sort_order
 * {/autogenerated}
 */
class BillingPlanCategory extends Am_Record
{
    protected $_childNodes = [];

    function getChildNodes()
    {
        return $this->_childNodes;
    }

    function removeChildNode(BillingPlanCategory $node)
    {
        foreach ($this->_childNodes as $k => $n) {
            if ($n == $node)
                unset($this->_childNodes[$k]);
        }
    }

    function createChildNode()
    {
        $c = new self($this->getTable());
        $c->parent_id = $this->pk();
        if (!$c->parent_id)
            throw new Am_Exception_InternalError("Could not add child node to not-saved object in " . __METHOD__);
        $this->_childNodes[] = $c;
        return $c;
    }

    public function fromRow(array $vars)
    {
        if (isset($vars['childNodes'])) {
            foreach ($vars['childNodes'] as $row) {
                $r = new self($this->getTable());
                $r->fromRow($row);
                $this->_childNodes[] = $r;
            }
            unset($vars['childNodes']);
        }
        return parent::fromRow($vars);
    }

    public function save()
    {
        if ($this->pk() == $this->parent_id) {
            $this->parent_id = 0;
        }
        parent::save();
    }
}

/** @extends Am_Table<BillingPlanCategory> */
class BillingPlanCategoryTable extends Am_Table
{
    protected $_key = 'billing_plan_category_id';
    protected $_table = '?_billing_plan_category';
    protected $_recordClass = 'BillingPlanCategory';

    const COUNT = 'count';

    /**
     * Do not include categories that do not have products.
     */
    const EXCLUDE_EMPTY = 'exclude_empty';

    protected $categoryBillingPlansCache = null;

    function getTree($cast_objects = true)
    {
        $ret = [];
        foreach ($this->_db->select("SELECT
            billing_plan_category_id AS ARRAY_KEY,
            parent_id AS PARENT_KEY, pc.*
            FROM ?_billing_plan_category AS pc
            ORDER BY parent_id, 0+sort_order, title") as $r) {
            $ret[] = $cast_objects ? $this->createRecord($r) : $r;
        }
        return $ret;
    }

    protected function _calcCntAndFilterEmpty(BillingPLanCategory $node)
    {
        $res = $node->self_cnt = $this->_billing_plan_category_cnt[$node->pk()] ?? 0;
        foreach ($node->getChildNodes() as $n) {
            $n->cnt = $this->_calcCntAndFilterEmpty($n);
            if (!$n->cnt)
                $node->removeChildNode($n);
            $res += $n->cnt;
        }
        return $res;
    }

    function getOptions()
    {
        $ret = [];
        $rows = $this->_db->select("SELECT billing_plan_category_id AS ARRAY_KEY,
                parent_id AS PARENT_KEY,
                billing_plan_category_id, title
                FROM ?_billing_plan_category
                ORDER BY parent_id, 0+sort_order, title");

        foreach ($rows as $id => $r) {
            $this->renderNode($r, $id, '', [], '', $ret);
        }

        return $ret;
    }

    function getSubCategoryIds($cat_id)
    {
        $res = [];
        $childNodes = $this->extractSubtree($this->getTree(false), $cat_id);
        while($node = array_shift($childNodes)) {
            array_push($res, $node['billing_plan_category_id']);
            foreach ($node['childNodes'] as $n) {
                array_push($childNodes, $n);
            }
        }
        return $res;
    }

    protected function extractSubtree($rows, $root)
    {
        $childNodes = $rows;
        while($node = array_shift($childNodes)) {
            if ($node['billing_plan_category_id'] == $root) return $node['childNodes'];
            foreach ($node['childNodes'] as $n) {
                array_push($childNodes, $n);
            }
        }
        return [];
    }

    protected function renderNode($r, $id, $type, array $options, $title, &$ret)
    {
        $do_count = !empty($options[self::COUNT]);
        $exclude_empty = !empty($options[self::EXCLUDE_EMPTY]);

        $title .= ( $title ? '/' : '') . $r['title'];
        $ctitle = $title;

        if ($exclude_empty && !$r['count']) {
            foreach ($r['childNodes'] as $cid => $c)
                $this->renderNode($c, $cid, $type, $options, $ctitle, $ret);
            return;
        }

        if ($do_count)
            $title .= sprintf(' (%d)', $r['count']);

        $ret[$id] = $title;

        foreach ($r['childNodes'] as $cid => $c)
            $this->renderNode($c, $cid, $type, $options, $ctitle, $ret);
    }

    function moveNodes($fromId, $toId)
    {
        $this->_db->query("UPDATE {$this->_table} SET parent_id=?d WHERE parent_id=?d",
            $toId, $fromId);
    }

    public function delete($key)
    {
        parent::delete($key);
        $this->_db->query("DELETE FROM ?_billing_plan_billing_plan_category WHERE billing_plan_category_id=?d", $key);
    }

    /**
     * @return array { category_id => [billing_plan_id1, billing_plan_id2, ...] }
     */
    public function getCategoryBillingPlans($useCache = true)
    {
        if (!$useCache || ($this->categoryBillingPlansCache === null))
        {
            $this->categoryBillingPlansCache = $this->_db->selectCol("
                SELECT bpc.billing_plan_category_id as ARRAY_KEY, GROUP_CONCAT(bpbpc.billing_plan_id)
                FROM ?_billing_plan_category AS bpc LEFT JOIN ?_billing_plan_billing_plan_category AS bpbpc
                USING (billing_plan_category_id)
                GROUP BY bpc.billing_plan_category_id");
            foreach ($this->categoryBillingPlansCache as &$prList)
                $prList = array_filter(explode(',', $prList ?? ''));
        }
        return $this->categoryBillingPlansCache;
    }

    public function getBillingPlanIds($catId)
    {
        return $this->_db->selectCol(
            "SELECT billing_plan_id FROM ?_billing_plan_billing_plan_category WHERE billing_plan_category_id=?",
            $catId
        );
    }
}