<?php

class DNSZone extends PhonalisaRecord
{

    public $ttl = 604800;
    public $fqdn;
    public $position;

    public static function myAttributes()
    {
        return array(
            'ttl' => 'ttl',
            'fqdn' => 'fqdn',
            'position' => 'position'
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Job the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('ttl, fqdn, position', 'safe'),
            array('ttl', 'numerical', 'integerOnly' => true),
            array('fqdn', 'ext.PhonalisaValidators.domainName')
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'ttl' => __('DNS_ZONE_TTL'),
            'fqdn' => __('DNS_ZONE_FQDN')
        );
    }

    public function afterDelete()
    {
        $dnsRecordModels = DNSRecord::model()->findAllByAttributes(array('dnsZone' => $this->id));
        foreach ($dnsRecordModels as $dnsRecordModel) {
            $dnsRecordModel->delete();
        }
        return parent::afterDelete();
    }

    public function afterSave()
    {
        if ($this->isNewRecord) {
            $this->createDefaultDNSRecords(DNSRecordType::A, cfg('PROV_HOST'), 'ns', '0');
            $this->createDefaultDNSRecords(DNSRecordType::NS, 'ns.' . $this->fqdn, '@', '1');
            $this->createDefaultDNSRecords(DNSRecordType::A, cfg('PROV_HOST'), 'pbx', '2');
            $this->createDefaultDNSRecords(DNSRecordType::CNAME, 'pbx', 'jabber', '3');
        }
        return parent::afterSave();
    }

    public function createDefaultDNSRecords($type, $host, $name, $position)
    {
        $model = new DNSRecord();
        $model->type = $type;
        $model->host = $host;
        $model->name = $name;
        $model->position = $position;
        $model->dnsZone = $this->id;
        $model->save();
    }
}
