<?php
class CST_Model extends OrderElement_Model{

    public $id, $Name, $Debtor, $Custom, $Status;
    public $Product;

    function __construct()
    {
        // Load parent constructor
        parent::__construct();

        // Default variables
        $this->Status = 'inorder';
    }

    function getProductsFromGroup($group_id)
    {
        $products = array();

        // Prepare query
        // TODO: only get correct CST subtype.
        $pdo_statement = $this->_db->prepare("SELECT p.`id`, p.`PriceExcl`, p.`PricePeriod`, p.`ProductCode`, p.`ProductName`, p.`ProductKeyPhrase`, p.`TaxPercentage`, (p.`PriceExcl` * (1+p.`TaxPercentage`)) as `PriceIncl`  
											 FROM `HostFact_Products` p, `HostFact_GroupRelations` g 
											 WHERE g.`Group`=:group_id AND g.`Type`='product' AND g.`Reference`=p.`id` AND p.`Status`='1' AND p.`ProductType`='cst'
											 ORDER BY `ProductCode` ASC");
        $pdo_statement->bindValue(':group_id', $group_id);

        // Execute statement
        $pdo_statement->execute();
        $result = $pdo_statement->fetchAll();

        foreach($result as $tmp_product){
            $products[$tmp_product->id] = $tmp_product;
        }

        return $products;
    }

    function getCartItem($index, $escaped = true)
    {

        // Get cart item with help of parent function
        $item = parent::getCartItem($index, false);

        // Should we escape output?
        if($escaped)
        {
            $item = escapeArray($item);
        }

        return $item;
    }

    function getProductInfo($productcode)
    {
        // Prepare query
        $pdo_statement = $this->_db->prepare("SELECT * FROM `HostFact_Products` WHERE `ProductCode`=:productcode 
                                    AND `Status`='1' AND `ProductType`='cst' LIMIT 1");
        $pdo_statement->bindValue(':productcode', $productcode);
        $pdo_statement->execute();
        $product = $pdo_statement->fetch();

        if($product)
        {
            $product->PeriodPrices = $this->listCustomProductPrices($productcode, 'productcode');
            return $product;
        }
        else
        {
            return FALSE;
        }
    }

    function getType($id)
    {
        // Prepare query
        $pdo_statement = $this->_db->prepare("SELECT * FROM `HostFact_CST_Types` WHERE `id`=:id LIMIT 1");
        $pdo_statement->bindValue(':id', $id);
        $pdo_statement->execute();
        return $pdo_statement->fetch();
    }

    public function validate($cstTypeRecord)
    {
        if(strlen(trim($this->Name)) === 0 && $cstTypeRecord->HasUniqueFeature)
        {
            $this->Error[] = __('please enter a name', 'cst');
        }

        if ($cstTypeRecord->HasAmount && (empty($this->Number) || !is_numeric($this->Number))) {
            $this->Error[] = __('invalid amount', 'cst');
        }

        return empty($this->Error) ? true : false;
    }

    function addToDatabase($cart_item)
    {
        $order = new Order_Model();

        if(!$product_info = $this->getProductInfo($cart_item['ProductCode']))
        {
            // The parent will add the order element to the database
            return parent::addToDatabase($cart_item);
        }

        // Get debtor
        if($order->get('ExistingCustomer') == 'yes')
        {
            $debtor = new Debtor_Model();
            if($debtor->checkLogin())
            {
                $customer_data = $debtor->show();
                $this->Debtor = $debtor->Identifier;
            }
            else
            {
                // Copy error
                $this->Error = $debtor->Error;
                return false;
            }
        }
        else
        {
            $customer = new Customer_Model();
            $customer_data = $customer->show();
            $this->Debtor = -1;
        }


        // Prepare adding cst into database
        $this->Name	= (isset($cart_item['Name']) && !empty($cart_item['Name'])) ? $cart_item['Name'] : $product_info->ProductName;
        $this->Number = (isset($cart_item['Number'])) ? $cart_item['Number'] : 1;
        $this->Product = $product_info->id;
        $this->Type = $product_info->ProductSubType;
        $this->Status = 'inorder';
        $this->Custom = isset($cart_item['Custom']) && is_array($cart_item['Custom']) ? $cart_item['Custom'] : array();

        global $orderform_settings;
        // Get CST type settings.
        $cstTypeRecord = $this->getType($orderform_settings->OtherSettings->cst->Type);

        // First check values
        if(!$this->validate($cstTypeRecord))
        {
            return FALSE;
        }

        // Prepare query
        $pdo_statement = $this->_db->prepare("INSERT INTO `HostFact_CST_Services` (`Type`, `Debtor`, `Product`, `Name`, `Custom`, `Status`) VALUES (:type, :debtor_id, :product_id, :name, :custom, :status)");

        $pdo_statement->bindValue(':type', $this->Type);
        $pdo_statement->bindValue(':debtor_id', $this->Debtor);
        $pdo_statement->bindValue(':product_id', $this->Product);
        $pdo_statement->bindValue(':name', $this->Name);
        $pdo_statement->bindValue(':custom', json_encode($this->Custom));
        $pdo_statement->bindValue(':status', $this->Status);

        // Execute statement
        $result = $pdo_statement->execute();

        if($result)
        {
            // Store CST ID in case we need to delete them again
            $cst_id = $this->_db->lastInsertId();
            $_SESSION['OrderForm'.ORDERFORM_ID][$this->Type]['Elements'][$cart_item['Index']]['CreatedCST'] = $cst_id;

            $cart_item['ProductType'] = 'cst';
            $cart_item['Reference'] = $cst_id;

            // The parent will add the order element to the database
            return parent::addToDatabase($cart_item);
        }
        else
        {
            // Fix created stuff
            $this->removeFromDatabase($cart_item);
            return false;
        }
    }

    function removeFromDatabase($cart_item)
    {
        // Delete cst
        if(isset($_SESSION['OrderForm'.ORDERFORM_ID][$this->Type]['Elements'][$cart_item['Index']]['CreatedCST']))
        {
            $pdo_statement = $this->_db->prepare("DELETE FROM `HostFact_CST_Services` WHERE `id`=:cst_id AND `Status`='inorder'");
            $pdo_statement->bindValue(':cst_id', $_SESSION['OrderForm'.ORDERFORM_ID][$this->Type]['Elements'][$cart_item['Index']]['CreatedCST']);
            $pdo_statement->execute();
        }

        return parent::removeFromDatabase($cart_item);
    }

    function getCustomFields($serviceType) {
        $pdo_statement = Database_Model::getInstance()->prepare("SELECT * FROM `HostFact_Debtor_Custom_Fields` WHERE `ShowService`='yes' AND `ShowOrderform`='yes' AND `ServiceType`=:type ORDER BY `OrderID` ASC");
        $pdo_statement->bindValue(':type', $serviceType);
        $pdo_statement->execute();
        $pdo_statement->setFetchMode(PDO::FETCH_ASSOC);
        return $pdo_statement->fetchAll();
    }
}