<?php
/**
 * Class represents records from table selfservice_type
 * {autogenerated}
 * @property int $type_id PK
 * @property string $title
 * @property string|null $description
 * {/autogenerated}
 */
class SelfserviceType extends Am_Record
{
    /**
     * @param string $relation - 'in' or 'out'
     * @return SelfserviceTypeProduct[]
     */
    function getProductsRelation($relation)
    {
        return $this->getDi()->selfserviceTypeProductTable->findBy([
            'type_id' => $this->pk(),
            'relation' => $relation,
        ], null, null, 'sort_order');
    }
    /**
     * return products which are not yet related to any of selfserviceType
     * @return Product[]
     */
    public function getSpareProducts()
    {
        $plans = $this->getDi()->billingPlanTable->selectObjects(
            "SELECT * 
                FROM ?_billing_plan bp 
                LEFT JOIN ?_product p 
                USING(product_id)
            WHERE p.is_archived != 1 
                AND NOT EXISTS (SELECT * FROM ?_selfservice_type_product
                WHERE type_id=?d AND billing_plan_id = bp.plan_id )"
            , $this->pk());
        $ret = [];
        foreach ($plans as $plan)
            $ret[] = $plan->getProduct();
        return $ret;
    }
}

/** @extends Am_Table<SelfserviceType> */
class SelfserviceTypeTable extends Am_Table
{
    protected $_key = 'type_id';
    protected $_table = '?_selfservice_type';

    function getOptions()
    {
        return $this->_db->selectCol("SELECT type_id as ARRAY_KEY, title FROM {$this->_table}");
    }
}