<?php namespace App\Models;

use CodeIgniter\Model;

class mAccounts extends Model {
    protected $table = 'budget_accounts';
    protected $primaryKey = 'id';
    
    protected $useAutoIncrement = true;
    
    protected $returnType = 'object';
    protected $useSoftDeletes = false;
    
    protected $allowedFields = ['parent_id','type','bookable','description','lkz'];
    
    protected $useTimestamps = false;
    private $mAccountList = array();

    protected function initialize()
    {
        $result = $this->findAll();
        foreach ($result as $value) {
            $this->mAccountList[$value->id] = $value;
        }
    }


    /**
	 * Erstellt DropDownListe aus gegeben array
     * @param array liste der daten
     * @param bool wenn true wird auch ein 0-Eintrag erstellt 
	 * @return mixed
	 */
    private function createDropDownList($data,$withnull = true,$key=0)
	{
        $liste = array();
        if ($withnull)
            $liste[$key] = '-----';
        foreach ( $data as $row )
		{
			$liste[$row->id] = $row->description;
		}
		asort( $liste );
        return $liste;
    }

    /**
	 * holt Text vom gegebenen Element
     * @param int id des gewünschten Elements
	 * @return string  Full Name of Entry
	 */
    public function getDropDownEntry($id){
        $element = $this->mAccountList[$id];
        $description = $element->description;
        $id = $element->parent_id;
        while ( $id > 0 )
        {
            $description = $this->mAccountList[$id]->description .'-'.$description;
            $id = $this->mAccountList[$id]->parent_id;
        }
        return $description;;
    }

    /**
	 * liefert DropDown Liste mit gegeben Suchparametern
     * @param string Kontotyp "InOut,In,Out,Acc"
     * @param bool ob bookable gesetzt sein muss
	 * @return bool  ob lkz Flag gesetzt sein darf
	 */
    public function getDropDownList($type, $bookable = true, $lkz = false )
	{
        if ($bookable == true)
            $this->where('bookable',true);
        if ($lkz == false)          $this->where('lkz',NULL);
        if ( $type == 'InOut' )     $this->where('type !=','account');
        elseif ( $type == 'Acc' )   $this->where('type','account');
        elseif ( $type == 'In' )    $this->where('type','input');
        elseif ( $type == 'Out' )   $this->where('type','output');
        $this->orderBy('description');
        $result = $this->findAll();
        $parent = array();
        foreach ( $result as &$element )
        {
            $id = $element->parent_id;
            while ( $id > 0 )
            {
                $element->description = $this->mAccountList[$id]->description .'-'.$element->description;
                if ($this->mAccountList[$id]->parent_id == 0){
                    $parent[] = (object)['id' => $element->id,'description' => $element->description ];
                }
                $id = $this->mAccountList[$id]->parent_id;
            }
        }
        return $this->createDropDownList($result);
    }

        /**
	 * liefert 2 DropDown Listen mit gegeben Suchparametern
     * parent für Vorselektion, subs für Untereinträge
     * @param string Kontotyp "InOut,In,Out,Acc"
     * @param bool ob bookable gesetzt sein muss
	 * @return bool  ob lkz Flag gesetzt sein darf
	 */
    public function getDropDownLists($type, $bookable = true, $lkz = false )
	{
        if ($bookable == true)      $this->where('bookable',true);
        if ($lkz == false)          $this->where('lkz',null);
        if ( $type == 'InOut' )     $this->where('type !=','account');
        elseif ( $type == 'Acc' )   $this->where('type','account');
        elseif ( $type == 'In' )    $this->where('type','output');
        elseif ( $type == 'Out' )   $this->where('type','input');
        $this->orderBy('description');
        $result = $this->findAll();
        
        $parent = array();
        $listen = array();
        foreach ( $result as &$element )
        {
            $id = $element->parent_id;
            while ( $id > 0 )
            {
                if ($this->mAccountList[$id]->lkz == 1) continue 2;
                if ($this->mAccountList[$id]->parent_id == 0){
                    if (!array_key_exists($id, $parent))
                        $parent[$id] = (object)['id' => $id,'description' => $this->mAccountList[$id]->description ];
                    $listen[$id][$element->id] = (object)['id' => $element->id,'description' => $element->description ];
                }
                else{
                    $element->description = $this->mAccountList[$id]->description .'-'.$element->description;
                }
                $id = $this->mAccountList[$id]->parent_id;
            }
        }
        $subs = array();
        $subs[0] = $this->createDropDownList(array());
        foreach ( $listen as $key => $element ){
            $subs[$key] = $this->createDropDownList($element,($this->mAccountList[$key]->bookable=="t"), $key);
        }
        return array('parent'=> $this->createDropDownList($parent),'subs'=>(object)$subs);
    }

     /**
	 * liefert parent id für category
     * @param int account id
	 * @return int parent id
	 */
    public function getParent($sid){
        if ($sid == 0) return 0;
        $result = $sid;
        $id = $this->mAccountList[$sid]->parent_id;
        while ( $id > 0 )
        {
            $result = $id;
            $id = $this->mAccountList[$id]->parent_id;
        }
        return $result;
    }

    
     /**
	 * liefert array für jedes sub element und level
	 * @return mixed  array for each level element
	 */
    public function getTreeData(){
        helper('array');
        $parents = array();
        $subs = array();
        foreach ( $this->mAccountList as $element )
        {
            if ($element->parent_id == 0)
                $parents[$element->id] = $element;
        }
        foreach ( $this->mAccountList as $element )
        {
            // if ($element->parent_id > 0)
            //     echo "".$parents[$element->parent_id]->id;
            if (($element->parent_id > 0) &&  array_key_exists($element->parent_id , $parents))
                 $parents[$element->parent_id]->subs[$element->id] = $element;
         }
        array_sort_by_multiple_keys($parents, ['description' => SORT_ASC]);
        return ['parents'=>$parents,'subs'=>$subs, 'all'=>$this->mAccountList];
    }

         /**
	 * erstellt oder updatet den gegeben Account
	 * @var array  formulardaten
	 */
    public function saveAccount($data){
		$this->set('parent_id',$data['parent']);
		$this->set('type', $data['type']);
		$this->set('bookable', array_key_exists('bookable', $data) ? true : false);
		$this->set('description', $data['description']);
        $this->set('lkz', (array_key_exists('lkz', $data) ? 1 : null));
        if ($data['id'] == 0)
            $this->insert();
        else
		    $this->update($data['id']);
            $this->initialize();
    }


    public function checkType($id, $type){
        return ($this->mAccountList[$id]->type == $type);
    }
};

?>