<?php

class KorsupgahPengampu extends \Phalcon\Mvc\Model
{
    public $id;
    public $nama;
    public $id_parent;
    public function initialize()
    {
        $this->setSchema('jaga');
        $this->setSource('korsupgah_pengampu');
        $this->belongsTo('id_parent', 'KorsupgahPengampu', 'id', ['alias' => 'ParentKorsupgahPengampu']);
        $this->hasMany('id', 'KorsupgahPengampu', 'id_parent');
        $this->hasMany("id", "KorsupgahSurvey", "id_pengampu");
    }

    public function toArray($columns = null)
    {
        $result = parent::toArray($columns);

        return $result;
    }

    public function getVerificationProgress()
    {
        $result = $this->toArray();

        // get the surveys
        $result['children'] = $this->KorsupgahPengampu->toArray();
        $result['surveys'] = [];
        $result['questionCount'] = 0;
        if (sizeof($result['children']) === 0) {
            // has no children
            $survey = $this->getKorsupgahSurvey($this);
            $result['surveys'] = array_merge($result['surveys'], $survey['surveys']);
            $result['questionCount'] += $survey['questionCount'] ?? 0;
        } else {
            // has children
            foreach($this->KorsupgahPengampu as $child) {
                $survey = $this->getKorsupgahSurvey($child);
                $result['surveys'] = array_merge($result['surveys'], $survey['surveys']);
                $result['questionCount'] += $survey['questionCount'] ?? 0;
            }
        }
        return $result;
    }

    private function getKorsupgahSurvey($obj)
    {
        $surveys = $obj->KorsupgahSurvey;
        $id_surveys = [];
        $questionCount = 0;
        $verificationCount = 0;
        $result = [
            'questionCount' => 0,
            'surveys' => []
        ];
        foreach($surveys as $survey) {
            // get the questions
            $template = $survey->KorsupgahTemplate;
            $result['questionCount'] += $template->KorsupgahTemplateSubIndikator->count();

            $eachSurvey['id_instansi'] = $survey->toArray()['id_instansi'];

            // get the answers
            $answers = $survey->getDetail()['answers'];
            $answerKeys = ['id', 'status', 'created_at', 'verified_at'];
            foreach($answers as $answer) {
                $eachSurvey['answers'][] = array_intersect_key($answer, array_flip($answerKeys));
            }
            $result['surveys'][] = $eachSurvey;   
        }
        return $result;
    }
}
