<?php

/**
 * Class PancekAnswer
 * @property PancekKomponenIndikator $komponenIndikator
 * @property PancekAnswerAttachment[] $attachments
 * @property PancekFormulir $formulir
 */
class PancekAnswer extends Phalcon\Mvc\Model
{
    public $id;
    public $formulir_id;
    public $komponen_indikator_id;
    public $keterangan;
    public $created_at;
    public $updated_at;
    public $deleted_at;
    public $verify_status;
    public $verified_at;
    public $verified_by;

    const VERIFY_STATUS_DISETUJUI = 'ACCEPTED';
    const VERIFY_STATUS_DIKEMBALIKAN = 'REJECTED';
    const VERIFY_STATUS_UPDATED = 'UPDATED';
    const VERIFY_STATUS_REVISED = 'REVISED';

    public function initialize()
    {
        $this->setSchema("jaga");
        $this->setSource("pancek_answer");

        $this->belongsTo(
            'formulir_id',
            \PancekFormulir::class,
            'id',
            [
                'reusable' => true, // cache related data
                'alias' => 'formulir'
            ]
        );
        $this->belongsTo(
            'komponen_indikator_id',
            \PancekKomponenIndikator::class,
            'id',
            [
                'reusable' => true, // cache related data
                'alias' => 'komponenIndikator',
                'params' => [
                    'conditions' => 'deleted_at IS NULL'
                ],
                'order' => 'id ASC, view_order ASC'
            ]
        );
        $this->hasMany(
            'id',
            \PancekAnswerAttachment::class,
            'answer_id',
            [
                'reusable' => true, // cache related data
                'alias' => 'attachments',
                'params' => [
                    'conditions' => 'deleted_at IS NULL'
                ],
                'order' => 'id DESC'
            ]
        );
    }

    public function getDetail($columns = null, $withKomponenIndikator = false, $withAttachments = true)
    {
        $res = $this->toArray($columns);
        if ($withKomponenIndikator) {
            $res['komponen_indikator'] = $this->komponenIndikator->toDetail();
        }
        if ($withAttachments) {
            $res['attachments'] = [];
            foreach ($this->attachments as $attachment) {
                /** @var $attahment PancekAnswerAttachment */
                array_push($res['attachments'], $attachment->getDetail());
            }
        }

        return $res;
    }



    public function syncAttachments($attachment_ids)
    {
        $attachments = PancekAnswerAttachment::find([
            'conditions' => 'answer_id = :id:',
            'bind' => ['id' => $this->id]
        ]);

        if ($attachments->count() > 0) {
            foreach ($attachments as $attachment) {
                if (!in_array($attachment->attachment_id, $attachment_ids)) {
                    $attachment->forceDelete();
                }
            }
        }
    }
}
