<?php

class Subscription_Model_Subscription_Application extends Core_Model_Default {

    protected $_app;
    protected $_subscription;

    public function __construct($params = array()) {
        parent::__construct($params);
        $this->_db_table = 'Subscription_Model_Db_Table_Subscription_Application';
        return $this;
    }

    public function save() {

        parent::save();

        if($this->isActive() == $this->getApplication()->isLocked()) {
            $this->getApplication()
                ->setIsLocked(!$this->isActive())
                ->save()
            ;
        }

    }

    function getSubscriptionsList(){
        return $this->getTable()->getSubscriptionsList();
    }

    public function getSubscription() {
        if(!$this->_subscription) {
            $this->_subscription = new Subscription_Model_Subscription();
            $this->_subscription->find($this->getSubscriptionId());
        }

        return $this->_subscription;
    }

    public function getApplication() {

        if(!$this->_app) {
            $this->_app = new Application_Model_Application();
            $this->_app->find($this->getAppId());
        }

        return $this->_app;
    }

    public function isActive() {
        return (bool) $this->getData("is_active");
    }

    public function create($app_id, $subscription_id) {

        $this->find($app_id, "app_id");

        if($this->getId()) {
            $this->setCreatedAt(null)
                ->setUpdatedAt(null)
            ;
        }

        $this->setSubscriptionId($subscription_id)
            ->setAppId($app_id)
            ->setIsActive(1)
        ;

        $this->update();

        return $this;

    }

    public function update() {

        $subscription = $this->getSubscription();

        if($subscription->getPaymentFrequency()) {

            $expire_at = new Siberian_Date($this->getExpireAt());

            if ($subscription->getPaymentFrequency() == Subscription_Model_Subscription::MONTHLY_FRENQUENCY) {
                $expire_at->addMonth(1);
            } else if ($subscription->getPaymentFrequency() == Subscription_Model_Subscription::YEARLY_FRENQUENCY) {
                $expire_at->addYear(1);
            }

            $this->setExpireAt($expire_at->toString("yyyy-MM-dd HH:mm:ss"));
        } else {
            $this->setExpireAt(null);
        }

        $this->save();

        return $this;

    }
}
