<?php

class KataoPeriod extends BaseKataoPeriod {
    const STATUS_DRAFT = 1;
    const STATUS_ACTIVE = 2;
    const STATUS_ARCHIVED = 3;

    public function __toString() {
        return $this->getName();
    }

    public function getBeginAtStr() {
        return CatalyzDate::formatShort($this->getBeginAt(null));
    }

    public function getFinishAtStr() {
        return CatalyzDate::formatShort($this->getFinishAt(null));
    }

    public function getOrderEndedAtStr() {
        return CatalyzDate::formatShort($this->getOrderEndedAt(null));
    }

    public function getStatusStr() {
        return KataoPeriodPeer::getStatusStr($this->getStatus());
    }

    public function updateAvailableProducts($serialized_suppliers_data = '', $product_ids = array(), $con = null) {
        $criteria = new Criteria();
        $criteria->add(KataoPeriodSupplierPeer::KATAO_PERIOD_ID, $this->getId());
        KataoPeriodSupplierPeer::doDelete($criteria, $con);

        $suppliers_data = Utils::parseOrderedData($serialized_suppliers_data);
        if (!empty($suppliers_data['middle_col'])) {
            foreach ($suppliers_data['middle_col'] as $supplier_id) {
                $katao_period_supplier = new KataoPeriodSupplier();
                $katao_period_supplier->setKataoPeriod($this);
                $katao_period_supplier->setKataoSupplierId(Utils::sanitizeSupplierId($supplier_id));
                $katao_period_supplier->setIncludeAllProducts(true);
                $katao_period_supplier->save($con);
            }
        }
        if (!empty($suppliers_data['right_col'])) {
            foreach ($suppliers_data['right_col'] as $supplier_id) {
                $katao_period_supplier = new KataoPeriodSupplier();
                $katao_period_supplier->setKataoPeriod($this);
                $katao_period_supplier->setKataoSupplierId(Utils::sanitizeSupplierId($supplier_id));
                $katao_period_supplier->setIncludeAllProducts(false);
                $katao_period_supplier->save($con);
            }
        }

        $criteria = new Criteria();
        $criteria->add(KataoPeriodProductPeer::KATAO_PERIOD_ID, $this->getId());
        KataoPeriodProductPeer::doDelete($criteria, $con);

        if (0 < count($product_ids)) {
            foreach ($product_ids as $product_id) {
                $katao_period_product = new KataoPeriodProduct();
                $katao_period_product->setKataoPeriod($this);
                $katao_period_product->setKataoProductId((int)$product_id);
                $katao_period_product->save($con);
            }
        }
    }

    public function activate() {
        try {
            $con = Propel::getConnection();
            $con->begin();

            /* archive previous active period */
            $criteria_update = new Criteria();
            $criteria_update->add(KataoPeriodPeer::STATUS, self::STATUS_ARCHIVED);
            $criteria_where = new Criteria();
            $criteria_where->add(KataoPeriodPeer::STATUS, self::STATUS_ACTIVE);
            BasePeer::doUpdate($criteria_where, $criteria_update, $con);

            /* activate current period */
            $this->setStatus(self::STATUS_ACTIVE);
            $this->save($con);

            $katao_period_suppliers = $this->getKataoPeriodSuppliers();
            $katao_period_products = $this->getKataoPeriodProducts();

            /* create available products for current period and for each node
			with global suppliers and local suppliers available for these nodes */
            foreach (KataoNodePeer::getAll() as/*(KataoNode)*/ $katao_node) {
                foreach ($katao_period_suppliers as/*(KataoPeriodSupplier)*/ $katao_period_supplier) {
                    $katao_node_suppplier = new KataoNodeSupplier();
                    $katao_node_suppplier->setKataoNode($katao_node);
                    $katao_node_suppplier->setKataoPeriod($this);
                    $katao_node_suppplier->setKataoSupplierId($katao_period_supplier->getKataoSupplierId());
                    $katao_node_suppplier->setIncludeAllProducts($katao_period_supplier->getIncludeAllProducts());
                    $katao_node_suppplier->save($con);
                }

                foreach ($katao_period_products as/*(KataoPeriodProduct)*/ $katao_period_product) {
                    $katao_node_product = new KataoNodeProduct();
                    $katao_node_product->setKataoNode($katao_node);
                    $katao_node_product->setKataoPeriod($this);
                    $katao_node_product->setKataoProductId($katao_period_product->getKataoProductId());
                    $katao_node_product->save($con);
                }

                $criteria = new Criteria();
                $criteria->addJoin(KataoSupplierPeer::ID, KataoUserPeer::KATAO_SUPPLIER_ID);
                $criteria->add(KataoSupplierPeer::IS_GLOBAL, false);
                $criteria->add(KataoUserPeer::STATUS, KataoUser::STATUS_ACTIVE);
                foreach ($katao_node->getKataoSupplierNodesJoinKataoSupplier($criteria) as/*(KataoSupplierNode)*/ $katao_supplier_node) {
                    $katao_node_suppplier = new KataoNodeSupplier();
                    $katao_node_suppplier->setKataoNode($katao_node);
                    $katao_node_suppplier->setKataoPeriod($this);
                    $katao_node_suppplier->setKataoSupplierId($katao_supplier_node->getKataoSupplierId());
                    $katao_node_suppplier->setIncludeAllProducts(true);
                    $katao_node_suppplier->save($con);
                }
            }

            /* switch members with new nodes */
            $criteria = new Criteria();
            $criteria->add(KataoMemberPeer::NEXT_KATAO_NODE_ID, null, Criteria::NOT_EQUAL);
            foreach (KataoMemberPeer::doSelect($criteria) as/*(KataoMember)*/ $katao_member) {
				$katao_member_node = new KataoMemberNode();
                $katao_member_node->setKataoMember($katao_member);
                $katao_member_node->setKataoNodeId($katao_member->getKataoNodeId());
                $katao_member_node->save($con);

                $katao_member->setKataoNodeId($katao_member->getNextKataoNodeId());
                $katao_member->setNextKataoNodeId(null);
                $katao_member->save($con);
            }

            $con->commit();
        }
        catch (PropelException $e) {
            $con->rollback();
            throw $e;
        }
    }

    public function getKataoNodeIdsForSupplierOrders() {
        $return = $this->initKataoNodeIdsForOrdersAndInvoices();

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoOrderPeer::KATAO_NODE_ID);
        $criteria->add(KataoOrderPeer::KATAO_PERIOD_ID, $this->getId());
        $criteria->add(KataoOrderPeer::STATUS, array(KataoOrder::STATUS_GENERATED, KataoOrder::STATUS_ADJUSTED), Criteria::NOT_IN);
        $criteria->setDistinct();

        $rs = KataoOrderPeer::doSelectRS($criteria);
        while ($rs->next()) {
            unset($return[$rs->getInt(1)]['available']);
        }

        return $return;
    }

    public function getKataoNodeIdsForMemberInvoices() {
        $return = $this->initKataoNodeIdsForOrdersAndInvoices();

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoInvoicePeer::KATAO_NODE_ID);
        $criteria->add(KataoInvoicePeer::KATAO_PERIOD_ID, $this->getId());
        $criteria->setDistinct();

        $rs = KataoInvoicePeer::doSelectRS($criteria);
        while ($rs->next()) {
            unset($return[$rs->getInt(1)]['available']);
        }

        return $return;
    }

    protected function initKataoNodeIdsForOrdersAndInvoices() {
        $return = array();

        $criteria = new Criteria();
        $criteria->addSelectColumn(KataoNodePeer::ID);
        $criteria->addSelectColumn(KataoNodePeer::CITY);
        $criteria->addJoin(KataoNodePeer::ID, KataoCartPeer::KATAO_NODE_ID);
        $criteria->add(KataoCartPeer::KATAO_PERIOD_ID, $this->getId());
        $criteria->setDistinct();

        $rs = KataoNodePeer::doSelectRS($criteria);
        while ($rs->next()) {
            $return[$rs->getInt(1)] = array('city' => $rs->getString(2), 'available' => true);
        }

        return $return;
    }

    public function isDeletable() {
        return (0 == $this->countKataoCarts()) && (0 == $this->countKataoOrders()) && (0 == $this->countKataoInvoices());
    }

    public function makePeriodCopy() {
        try {
            $con = Propel::getConnection();
            $con->begin();

            $added_year = 1;
            while (KataoPeriodPeer::hasConflictedPeriodDates(strtotime('+' . $added_year . ' year', $this->getBeginAt(null)), strtotime('+' . $added_year . ' year', $this->getFinishAt(null)))) {
                $added_year++;
            }

            $name = sprintf('%s (2)', $this->getName());
            if (false !== strpos($this->getName(), $this->getBeginAt('Y'))) {
                $name = str_replace($this->getBeginAt('Y'), (int)$this->getBeginAt('Y') + $added_year, $this->getName());
            }

            $this_copy = new KataoPeriod();
            $this_copy->setName($name);
            $this_copy->setBeginAt(strtotime('+' . $added_year . ' year', $this->getBeginAt(null)));
            $this_copy->setFinishAt(strtotime('+' . $added_year . ' year', $this->getFinishAt(null)));
            $this_copy->setOrderEndedAt(strtotime('+' . $added_year . ' year', $this->getOrderEndedAt(null)));
            $this_copy->setStatus(self::STATUS_DRAFT);
            $this_copy->setExported(false);
            $this_copy->save($con);

            foreach($this->getKataoPeriodProducts() as/*(KataoPeriodProduct)*/ $katao_period_product) {
                $katao_period_product_copy = new KataoPeriodProduct();
                $katao_period_product_copy->setKataoPeriod($this_copy);
                $katao_period_product_copy->setKataoProductId($katao_period_product->getKataoProductId());
                $katao_period_product_copy->save($con);
            }

            foreach($this->getKataoPeriodSuppliers() as/*(KataoPeriodSupplier)*/ $katao_period_supplier) {
                $katao_period_supplier_copy = new KataoPeriodSupplier();
                $katao_period_supplier_copy->setKataoPeriod($this_copy);
                $katao_period_supplier_copy->setKataoSupplierId($katao_period_supplier->getKataoSupplierId());
                $katao_period_supplier_copy->setIncludeAllProducts($katao_period_supplier->getIncludeAllProducts());
                $katao_period_supplier_copy->save($con);
            }

            $con->commit();

            return $this_copy->getId();
        }
        catch (PropelException $e) {
            $con->rollback();
            throw $e;
        }
    }
}