<?php
namespace Jaga\Models\PAK;

use Jaga\Models\BaseModel;
use Jaga\Traits\JagaTimestamp;
use Jaga\Traits\SoftDelete;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator;

class PAKIsianSekolahAttachment extends BaseModel
{
    use JagaTimestamp, SoftDelete;
    
    const FILE_TYPE_DOCUMENT = 1;
    const FILE_TYPE_IMAGE = 2;

    public static $throwableModelName = 'Attachment Isian Sekolah';

    public function initialize()
    {
        $this->setSchema("jaga");
        $this->setSource("pak_isian_sekolah_attachment");
        $this->belongsTo(
            "isian_detail_id", 
            "Jaga\Models\PAK\PAKIsianSekolahDetail", 
            "id"
        );
        $this->belongsTo(
            "attachment_id", 
            \Attachments::class, 
            "id",
            [
                 'reusable' => true, // cache related data
                 'alias'    => 'attachment',
            ]
        );
    }

    public function validation()
    {
        $validator = new Validation();

        $validator->add(
            'attachment_id',
            new UniquenessValidator([
                'model' => $this,
                'message' => 'Sorry, That attachment is already taken',
            ])
        );

        return $this->validate($validator);
    }

    public function toArray($columns = null)
    {
        $result = parent::toArray($columns);
        $attachment = $this->attachment ? : null;
        $result['file'] = empty($attachment) ? null : $attachment->toArray(['id','uuid','filename','created_at']);

        return $result;
    }

    public function getDetail($columns = null)
    {
        $result = $this->toArray($columns = null);

        return $result;
    }
}