<?php

if (!defined('sugarEntry') || !sugarEntry)
    die('Not A Valid Entry Point');

/* * ***************************************************************************
 * The contents of this fi le are subject to the RECIPROCAL PUBLIC LICENSE
 * Version 1.1 ("License"); You may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://opensource.org/licenses/rpl.php. Software distributed under the
 * License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied.
 *
 * You may:
 * a) Use and distribute this code exactly as you received without payment or
 *    a royalty or other fee.
 * b) Create extensions for this code, provided that you make the extensions
 *    publicly available and document your modifications clearly.
 * c) Charge for a fee for warranty or support or for accepting liability
 *    obligations for your customers.
 *
 * You may NOT:
 * a) Charge for the use of the original code or extensions, including in
 *    electronic distribution models, such as ASP (Application Service
 *    Provider).
 * b) Charge for the original source code or your extensions other than a
 *    nominal fee to cover distribution costs where such distribution
 *    involves PHYSICAL media.
 * c) Modify or delete any pre-existing copyright notices, change notices,
 *    or License text in the Licensed Software
 * d) Assert any patent claims against the Licensor or Contributors, or
 *    which would in any way restrict the ability of any third party to use the
 *    Licensed Software.
 *
 * You must:
 * a) Document any modifications you make to this code including the nature of
 *    the change, the authors of the change, and the date of the change.
 * b) Make the source code for any extensions you deploy available via an
 *    Electronic Distribution Mechanism such as FTP or HTTP download.
 * c) Notify the licensor of the availability of source code to your extensions
 *    and include instructions on how to acquire the source code and updates.
 * d) Grant Licensor a world-wide, non-exclusive, royalty-free license to use,
 *    reproduce, perform, modify, sublicense, and distribute your extensions.
 *
 * The Original Code is: CommuniCore
 *                       Olavo Farias
 *                       2006-04-7 olavo.farias@gmail.com
 *
 * The Initial Developer of the Original Code is CommuniCore.
 * Portions created by CommuniCore are Copyright (C) 2005 CommuniCore Ltda
 *
 * All Rights Reserved.
 *
 * ****************************************************************************** */

require_once('data/SugarBean.php');
require_once('include/utils.php');

class EcmService extends SugarBean {

    var $field_name_map = array();
    // STANDARD FIELDS
    var $id;
    var $date_entered;
    var $date_modified;
    var $modified_user_id;
    var $assigned_user_id;
    var $name;
    var $description;
    //TABLE COLUMNS
    var $number;
    var $document_no;
    var $parent_type;
    var $parent_name;
    var $parent_id;
    var $type;
    var $status;
    var $register_date;
    var $parent_address_street;
    var $parent_address_city;
    var $parent_address_postalcode;
    var $parent_address_country;

    /**
     * Article type items  subtotal value.
     *
     * @var float
     */
    var $articles_subtotal;

    /**
     * Article type items  total value.
     *
     * @var float
     */
    var $articles_total;

    /**
     * Services type items subtotal value.
     *
     * @var float
     */
    var $services_subtotal;

    /**
     * Services type items total value.
     *
     * @var float
     */
    var $services_total;
    var $discount;
    var $to_vatid;
    var $ecmlanguage;
    var $to_is_vat_free;
    var $header_text;
    var $footer_text;
    var $ads_text;
    var $template_id;
    var $template_name;
    var $email_id;
    var $parent_name_copy;
    var $parent_contact_name;
    var $parent_contact_title;
    var $ecmpaymentcondition_id;
    var $ecmpaymentcondition_name;
    var $ecmpaymentcondition_text;
    var $ecmdeliverycondition_id;
    var $ecmdeliverycondition_name;
    var $ecmdeliverycondition_text;
    var $validtill_date;
    var $order_origin;
    var $contact_id;
    var $contact_name;
    var $show_images_on_offers;
    var $currency_symbol;
    var $currency_id;
    var $template;
    var $pdf;

    /**
     * Article type items list.
     *
     * @var array
     */
    var $position_list = array();

    /**
     * Service type items list.
     *
     * @var array
     */
    var $services_list = array();

    /**
     * Income type items list.
     * @var array
     */
    public $income_list = array();
    //

    var $parser;
    var $account;
    var $contact;
    var $user;
    var $mfp;
    //added 4.03.2009
    var $pricebook_id;
    var $show_recipient_code;
    // RELATED FIELDS
    var $created_by;
    var $created_by_name;
    var $modified_by_name;
    var $assigned_user_name;
    // SUBPANELS RELATED
    // MODULE OBJECT DETAILS
    var $module_dir = "EcmServices";
    var $table_name = "ecmservices";
    var $object_name = "EcmService";
    //RELATED TABLE NAMES
    // USED TO RETRIEVE RELATED FIELDS FROM FORM POSTS.
    var $additional_column_fields = array(
        'assigned_user_name',
        'assigned_user_id',
        'modified_user_id',
        'created_by',
    );
    //RELATIONSHIP FIELDS
    var $relationship_fields = array(
        'note_id' => 'notes',
        'email_id' => 'emails'
    );

    function EcmService() {
        parent::SugarBean();

        $this->setupCustomFields('EcmServices');

        foreach ($this->field_defs as $field) {
            $this->field_name_map[$field['name']] = $field;
        }
    }

    var $new_schema = true;

    function get_summary_text() {
        return "$this->name";
    }

    function create_list_query($order_by, $where, $show_deleted = 0) {
        // Fill in the assigned_user_name
        $custom_join = $this->custom_fields->getJOIN();

        $query = "SELECT ecmservices.*, users.user_name AS assigned_user_name";

        if ($custom_join) {
            $query .= $custom_join['select'];
        }

        $query .= "FROM ecmservices LEFT JOIN users ON ecmservices.assigned_user_id = users.id";

        $query .= "  ";

        if ($custom_join) {

            $query .= $custom_join['join'];
        }

        $where_auto = '1 = 1';

        if ($show_deleted == 0) {
            $where_auto = " $this->table_name.deleted = 0 ";
        } else if ($show_deleted == 1) {
            $where_auto = " $this->table_name.deleted = 1 ";
        }

        if ($where != "")
            $query .= "WHERE $where AND " . $where_auto;
        else
            $query .= "where " . $where_auto;

        if (substr_count($order_by, '.') > 0) {
            $query .= " ORDER BY $order_by";
        } else if ($order_by != "")
            $query .= " ORDER BY $order_by";
        else
            $query .= " ORDER BY ecmservices.name";

        return $query;
    }

    function create_export_query($order_by, $where) {
        $custom_join = $this->custom_fields->getJOIN();

        $query = "SELECT ecmservices.*, users.user_name assigned_user_name";

        if ($custom_join) {
            $query .= $custom_join['select'];
        }

        $query .= " FROM ecmservices ";
        $query .= " LEFT JOIN users ON ecmservices.assigned_user_id=users.id";

        if ($custom_join) {
            $query .= $custom_join['join'];
        }

        $query .= "";

        $where_auto = " ecmservices.deleted=0";

        if ($where != "")
            $query .= " where $where AND " . $where_auto;
        else
            $query .= " where " . $where_auto;

        if ($order_by != "")
            $query .= " ORDER BY $order_by";
        else
            $query .= " ORDER BY ecmservices.name";

        return $query;
    }

    function fill_in_additional_list_fields() {

    }

    function fill_in_additional_detail_fields() {
        global $app_list_strings;

        $invoiceOutQuery = 'SELECT DISTINCT i.* FROM `ecminvoiceouts` AS i LEFT JOIN `ecminvoiceoutitems` AS ii ON i.`id` = ii.`ecminvoiceout_id` WHERE ii.`parent_doc_id` = \'' . $this->id . '\';';

        //echo $invoiceOutQuery;

        $stockDocOutQuery = 'SELECT DISTINCT o.* FROM `ecmstockdocouts` AS o LEFT JOIN `ecmstockdocoutitems` AS oi ON o.`id` = oi.`ecmstockdocout_id` WHERE oi.`parent_doc_id` = \'' . $this->id . '\';';

        //echo $stockDocOutQuery;

        $invoiceOutResult = $this->db->fetchByAssoc($this->db->query($invoiceOutQuery));
        $stockDocOutResult = $this->db->fetchByAssoc($this->db->query($stockDocOutQuery));

        if (false == is_null($invoiceOutResult))
            $this->fk_parent_id = '<a href="index.php?module=EcmInvoiceOuts&action=DetailView&record=' . $invoiceOutResult['id'] . '" target="new">' . $invoiceOutResult['name'] . '</a>';
        else
            $this->fk_parent_id = $app_list_strings['fk_parent_id_default'];

        if (false == is_null($stockDocOutResult))
            $this->wz_parent_id = '<a href="index.php?module=EcmStockDocOuts&action=DetailView&record=' . $stockDocOutResult['id'] . '" target="new">' . $stockDocOutResult['name'] . '</a>';
        else
            $this->wz_parent_id = $app_list_strings['wz_parent_id_default'];

        //var_dump($this->fk_parent_id);
        //var_dump($this->wz_parent_id);
        //exit;
        //FILL IN THE ASSIGNED_USER_NAME
        $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
        $this->created_by_name = get_assigned_user_name($this->created_by);

        $this->modified_by_name = get_assigned_user_name($this->modified_user_id);

        $result = $this->db->query("SELECT status, parent_id, contact_id, template_id, assigned_user_id FROM ecmservices WHERE id='$this->id'");

        if (is_resource($result)) {
            $row = $this->db->fetchByAssoc($result);
            if ($row) {
                $this->status = $row['status'];
                $this->parent_id = $row['parent_id'];
                $this->contact_id = $row['contact_id'];
                $this->template_id = $row['template_id'];
                $this->assigned_user_id = $row['assigned_user_id'];
            }
        }
    }

    function get_list_view_data() {
        global $current_language;

        $this->fill_in_additional_detail_fields();
        $app_list_strings = return_app_list_strings_language($current_language);
        $mod_strings = return_module_language($current_language, 'EcmServices');
        $the_array = parent::get_list_view_data();

        // THE NEW LISTVIEW CODE ONLY FETCHES COLUMNS THAT WE'RE DISPLAYING AND NOT ALL
        // THE COLUMNS SO WE NEED THESE CHECKS.

        $the_array['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);

        list($total, $subtotal) = $this->getTotalSubtotal();
        ;

        $the_array['TOTAL'] = $total;
        $the_array['PDF_URL'] = '';

        $the_array['OPTIONS'] = $this->ListIconsView();

				$the_array['NUMBER'] = '';
        return $the_array;
    }

    function getStatusMenuInfo($inJSON = true) {
        global $app_list_strings;
        $arr = array();

        foreach ($app_list_strings['ecmservices_status_dom'] as $key => $value) {
            $arr[$key] = array(
                'enabled' => '<div><img src="modules/EcmServices/images/' . $key . '.gif" />' . $value . '</div>',
                'disabled' => '<div><img src="modules/EcmServices/images/' . $key . '.gif" />' . $value . '</div>',
            );
        }

        $json = getJSONobj();
        if ($inJSON)
            return str_replace('&quot;', '\"', $json->encode($arr));
        else
            return $arr;
    }

    function generateOptions($icon, $module = '', $action = '') {
        global $app_strings;

        $tmp = '';
        if ($icon == "confirming") {
            if ($this->ACLAccess('import')) {
                $tmp .= '<span id="confirmingListEcmService_' . $this->id . '" style="display:' . ($this->ACLAccess('confirming') ? '' : 'none') . ';"><img border="0" src="modules/EcmServices/images/accept_enabled.gif" title="' . translate('LBL_LIST_ACCEPT', 'Ecmservices') . '" onClick="list_setQuoteStatus(\'' . $this->id . '\',\'s30\');" style="cursor:pointer;" />&nbsp;';
                $tmp .= '<img border="0" src="modules/EcmServices/images/reject_enabled.gif" title="' . translate('LBL_LIST_REJECT', 'EcmServices') . '" onClick="list_setQuoteStatus(\'' . $this->id . '\',\'s40\');" style="cursor:pointer;" />&nbsp;&nbsp;&nbsp;|</span>';
            }
        } else
        if ($icon == 'send_to_confirm') {

            //send to confirm
            if ($this->ACLAccess('send_to_confirm'))
                $tmp = '<img border="0" id="send_to_confirm_' . $this->id . '" src="modules/EcmServices/images/sendtoconfirm_enabled.gif" title="' . translate('LBL_LIST_SEND_TO_CONFIRM', 'EcmService') . '" style="cursor:pointer;" onClick="list_setQuoteStatus(\'' . $this->id . '\',\'s20\');" />';
            else
                $tmp = '<img border="0" id="send_to_confirm_' . $this->id . '" src="modules/EcmServices/images/sendtoconfirm_disabled.gif" title="' . translate('LBL_LIST_SEND_TO_CONFIRM', 'EcmServices') . '" />';
        } else
        if ($icon == "convert_to_invoice") {

            //convert to invoice
            if ($this->ACLAccess('quote_to_invoice'))
                $tmp = '<img border="0" id="convert_to_invoice_' . $this->id . '" src="modules/EcmServices/images/convert_enabled.gif" title="' . translate('LBL_LIST_TO_INVOICE', 'EcmServices') . '" onClick="javascript:window.location=\'index.php?module=EcmInvoiceOuts&action=EditView&out_id=' . $this->id . '&out_module=EcmServices&return_module=EcmServices&return_action=index\';" style="cursor:pointer;" />';
            else
                $tmp = '<img border="0" id="convert_to_invoice_' . $this->id . '" src="modules/EcmServices/images/convert_disabled.gif" title="' . translate('LBL_LIST_TO_INVOICE', 'EcmServices') . '" />';
        } else
        if ($icon == 'convert_to_service') {
            if ($this->ACLAccess('quote_to_service'))
                $tmp = '<img border="0" id="convert_to_service_' . $this->id . '" src="modules/EcmServices/images/create_services_enabled.gif" title="' . translate('LBL_LIST_TO_SERVICE', 'EcmServices') . '" onClick="javascript:window.location=\'index.php?module=EcmServices&action=EditView&out_id=' . $this->id . '&out_module=EcmServices&return_module=EcmServices&return_action=index\';" style="cursor:pointer;" />';
            else
                $tmp = '<img border="0" id="convert_to_service_' . $this->id . '" src="modules/EcmServices/images/create_services_disabled.gif" title="' . translate('LBL_LIST_TO_SERVICE', 'EcmServices') . '" />';
        } else
        if ($icon == 'pdf') {

            //pdf
            if ($this->ACLAccess('pdf_toolbar')) {
                $tmp = '<img border="0" src="modules/EcmServices/images/pdf.gif" title="' . translate('LBL_LIST_PREVIEW_PDF', 'EcmServices') . '" onClick="EcmPreviewPDF(\'index.php?module=EcmServices&action=previewPDF&method=I&record=' . $this->id . '&to_pdf=1\',{zoom:75,toolbar:1});" style="cursor:pointer" />';
            } else {
                $tmp = '<img border="0" src="modules/EcmServices/images/pdf.gif" title="' . translate('LBL_LIST_PREVIEW_PDF', 'EcmServices') . '" onClick="EcmPreviewPDF(\'index.php?module=EcmServices&action=previewPDF&method=I&record=' . $this->id . '&to_pdf=1\',{zoom:75,toolbar:0});" style="cursor:pointer" />';
            }
        } else
        if ($icon == 'download') {

            //download
            if ($this->ACLAccess('pdf_toolbar')) {
                $tmp = '<img border="0" src="modules/EcmServices/images/download_enabled.gif" title="' . translate('LBL_LIST_DOWNLOAD_PDF', 'EcmServices') . '" onClick="window.location=\'index.php?module=EcmServices&action=previewPDF&method=D&record=' . $this->id . '&to_pdf=1\';" style="cursor:pointer"/>';
            } else {
                $tmp = '<img border="0" src="modules/EcmServices/images/download_disabled.gif" title="' . translate('LBL_LIST_DOWNLOAD_PDF', 'EcmServices') . '"/>';
            }
        } else

        if ($icon == 'duplicate') {

            //duplicate
            $tmp = '<a href="index.php?module=EcmServices&action=EditView&record=' . $this->id . '&isDuplicate=true"><img border="0" src="modules/EcmServices/images/duplicate.jpg" title="' . translate('LBL_LIST_DUPLICATE', 'EcmServices') . '" /></a>';
        } else
        if ($icon == 'edit') {

            //edit
            if ($this->ACLAccess('edit'))
                $tmp = '<img border="0" id="edit_' . $this->id . '" src="modules/EcmServices/images/edit_inline_enabled.gif" title="' . $app_strings['LBL_EDIT_BUTTON'] . '" onClick="javascript:window.location=\'index.php?module=EcmServices&action=EditView&record=' . $this->id . '&return_module=' . $_REQUEST['module'] . '&return_action=' . $_REQUEST['action'] . '&return_id=' . $_REQUEST['record'] . '\';" style="cursor:pointer;" />';
            else
                $tmp = '<img border="0" id="edit_' . $this->id . '" src="modules/EcmServices/images/edit_inline_disabled.gif" title="' . $app_strings['LBL_EDIT_BUTTON'] . '" />';
        } else
        if ($icon == 'send_email') {

            //send_email
            if ($this->ACLAccess('send_email'))
                $tmp = '<img border="0" id="sendemail_' . $this->id . '" src="modules/EcmServices/images/send_email_enabled.gif" title="' . translate('LBL_SENDEMAIL_BUTTON', 'EcmServices') . '" onClick="' . $this->createSendEmailLink() . '" style="cursor:pointer;" />';
            else
                $tmp = '<img border="0" id="sendemail_' . $this->id . '" src="modules/EcmServices/images/send_email_disabled.gif" title="' . translate('LBL_SENDEMAIL_BUTTON', 'EcmServices') . '" />';
        } else if ($icon == 'view') {
            $tmp = '<img border="0" src="themes/Sugar/images/view_inline.gif" onClick="javascript:window.location=\'index.php?module=' . $this->module_dir . '&action=DetailView&record=' . $this->id . '&return_module=' . $_REQUEST['module'] . '&return_action=' . $_REQUEST['action'] . '&return_id=' . $_REQUEST['record'] . '\';" title="' . $app_strings['LBL_DETAIL_BUTTON'] . '" />';
        }

        return $tmp;
    }

    function getEmailTemplateId($what) {
        $GLOBALS['db'] = new MysqlManager();
        $GLOBALS['db']->connect();

        $query = "SELECT `id` FROM `email_templates` WHERE `name` LIKE 'QuoteTemplate" . $what . "%' LIMIT 1";
        $result = $GLOBALS['db']->query($query);
        if (is_resource($result)) {
            $row = $GLOBALS['db']->fetchByAssoc($result);
            if (is_array($row)) {
                return $row['id'];
            }
        }
        return '';
    }

    function createSendEmailLink() {
        require_once('modules/EcmEmails/EcmEmailsDataCreator.php');

        $eedc = new EcmEmailsDataCreator();
        if (isset($this->contact_id) && $this->contact_id != '') {
            $eedc->addToModule('Contacts', $this->contact_id);
            $eedc->setEmailTemplateId($this->getEmailTemplateId("Contact"));
        } else {
            $eedc->addToModule('Accounts', $this->parent_id);
            $eedc->setEmailTemplateId($this->getEmailTemplateId("Account"));
        }

        global $current_user;

        $eedc->setFromModule('Users', $current_user->id);
        $eedc->addAssigned('Accounts', $this->parent_id);
        $eedc->addAssigned('Contacts', $this->contact_id);
        $eedc->addAssigned('EcmDocumentTemplates', $this->template_id);
        $eedc->addAssigned('Users', '');
        $eedc->addAssigned($this->module_dir, $this->id);

        $eedc->addAttachmentBySugar($this->createPdfFileName(), $this->module_dir, "previewPDF", array("record" => $this->id, "method" => "S", "to_pdf" => "1"), array("method" => "I"));
        return $eedc->createJavaScriptAction();
    }

    function ListIconsView() {
        if (isset($_REQUEST['module']) && $_REQUEST['module'] != '' && isset($_REQUEST['action'])) {
            $module = $_REQUEST['module'];
            $action = $_REQUEST['action'];

            $glue = "&nbsp;";
            $viewIcons = array();
            if ($module == $this->module_dir) //This module, action ListView or index
                $viewIcons = array('send_email', 'download', 'pdf', 'duplicate', 'edit');
            else
            if ($module == "Home") { //This is for a Home module for Dashlets
                $glue = "&nbsp;";
                $viewIcons = array('download', 'pdf', 'duplicate', 'edit', 'view');
            } else { //this is for subpanels, popups
                $glue = "&nbsp;";
                $viewIcons = array('download', 'pdf', 'edit');
            }

            $arr = array();
            foreach ($viewIcons as $value) {
                $tmp = $this->generateOptions($value);
                if ($tmp != '')
                    $arr[] = $tmp;
            }

            return '<span id="optionsListEcmService_' . $this->id . '">' . implode($glue, $arr) . '<script language="javascript">var ListQuotesModule="' . $module . '"; var ListQuotesAction="' . $action . '";</script></span>';
        }
        return '';
    }

    function createPdfFileName($format = true) {
        global $mod_strings;

        $arr1 = array('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' ');
        $arr2 = array('', '', '', '', '', '\'', '[', ']', '', '_');

        $tmp = $this->document_no;

        if ($format)
            $tmp = str_replace($arr1, $arr2, $mod_strings['LBL_PDF_FILENAME'] . $tmp . '.pdf');

        else
            $tmp = $mod_strings['LBL_PDF_FILENAME'] . $tmp . '.pdf';

        //$mod = return_module_language($current_language, 'EcmInvoiceOuts');
        //return urlencode(
//      return $mod['LBL_PDF_INVOICE_FILE_NAME'].$tmp.'.pdf';//);

        return $tmp; //);
    }

    /**

      BUILDS A GENERIC SEARCH BASED ON THE QUERY STRING USING OR.

      DO NOT INCLUDE ANY $THIS-> BECAUSE THIS IS CALLED ON WITHOUT HAVING THE CLASS INSTANTIATED.

     */
    function build_generic_where_clause($the_query_string) {
        $where_clauses = array();

        $the_query_string = PearDatabase::quote(from_html($the_query_string));

        array_push($where_clauses, "ecmservices.name like '$the_query_string%'");

        $the_where = "";

        foreach ($where_clauses as $clause) {

            if ($the_where != "")
                $the_where .= " or ";

            $the_where .= $clause;
        }

        return $the_where;
    }

    function set_notification_body($xtpl, $simplemodule) {
        global $mod_strings, $app_list_strings;

        $xtpl->assign("NAME", $simplemodule->name);
        $xtpl->assign("DESCRIPTION", $simplemodule->description);

        return $xtpl;
    }

    function bean_implements($interface) {
        switch ($interface) {
            case 'ACL':
                return true;
                break;
        }

        return false;
    }

    function save($check_notify = FALSE) {
        global $current_user;

        if (($this->fetched_row && $this->fetched_row['template_id'] != $this->template_id) || (empty($this->id) || $this->id == '')) {
            $this->number = $this->generateNumber();
            $this->document_no = $this->formatNumber();
			
		//add 0
		$date = substr($this->number,0,8);
		$number = substr($this->number,8,strlen($this->number));
	
		if (strlen($number)<5) {
			while(strlen($number)!=5)
				$number = '0'.$number;
		}
	
		$this->number = $date.$number;
        }

        if (isset($this->ecmpaymentcondition_id) && $this->ecmpaymentcondition_id != '')
            $this->ecmpaymentcondition_text = EcmService::getTranslation('EcmPaymentConditions', $this->ecmpaymentcondition_id, $this->ecmlanguage);
        else
            $this->ecmpaymentcondition_text = '';

        if (isset($this->ecmdeliverycondition_id) && $this->ecmdeliverycondition_id != '')
            $this->ecmdeliverycondition_text = EcmService::getTranslation('EcmDeliveryConditions', $this->ecmdeliverycondition_id, $this->ecmlanguage);
        else
            $this->ecmdeliverycondition_text = '';

        //list($total, $subtotal) = $this->getTotalSubtotal();
        //list($articles_total, $articles_subtotal) = $this->getArticlesTotalSubtotal();
        //list($services_total, $services_subtotal) = $this->getServicesTotalSubtotal();

        list($total, $subtotal) = $this->getTotalSubtotalLocal();
        list($articles_total, $articles_subtotal) = $this->getArticlesTotalSubtotalLocal();
        list($services_total, $services_subtotal) = $this->getServicesTotalSubtotalLocal();

        $this->total = $total;
        $this->articles_total = $articles_total;
        $this->services_total = $services_total;

        $this->subtotal = $subtotal;
        $this->articles_subtotal = $articles_subtotal;
        $this->services_subtotal = $services_subtotal;

        $return_id = parent::save($check_notify);

        $this->savePositions($return_id);
        $this->saveServices($return_id);
        $this->saveIncomes($return_id);

        return $return_id;
    }

    /**
     * Close.
     *
     * Change service status to 'closed'.
     *
     * @return string
     */
    public function close() {
        $this->deleteReservations();
    
        $this->status = 'closed';
        return $this;
    }

    /**
     * Save stock doc out.
     *
     * Add WZ with income_list.
     *
     * @return string
     */
    public function saveStockDocOut() {
        global $mod_strings;
    
        //if (!isset($this->position_list) || !is_array($this->position_list))
        //    $this->position_list = $this->getPositionList(true);
        //if (!isset($this->services_list) || !is_array($this->services_list))
        //    $this->services_list = $this->getServicePositionList(true);
        //if (!isset($this->income_list) || !is_array($this->income_list))
        $this->income_list = $this->getIncomePositionList(true);

        include_once 'modules/EcmStockDocOuts/EcmStockDocOut.php';
        $stockDocOut = new EcmStockDocOut();

		// informacje o kontrahencie
		$stockDocOut->parent_id = $this->parent_id;
		$stockDocOut->parent_type = $this->parent_type;
		$stockDocOut->parent_name = $this->parent_name;
		$stockDocOut->parent_contact_name = $this->parent_contact_name;
		$stockDocOut->parent_contact_title = $this->parent_contact_title;
		$stockDocOut->parent_address_street = $this->parent_address_street;
		$stockDocOut->parent_address_city = $this->parent_address_city;
		$stockDocOut->parent_address_postalcode = $this->parent_address_postalcode;
		$stockDocOut->parent_address_country = $this->parent_address_country;
        $stockDocOut->contact_name = $this->parent_contact_name;
        //
        $stockDocOut->stock_id = $this->pw_stock_id;
        $stockDocOut->stock_name = $this->pw_stock_name;
        $stockDocOut->assigned_user_id = $this->assigned_user_id;
        $stockDocOut->ecmlanguage = $this->ecmlanguage;
        $stockDocOut->currency_id = $this->currency_id;
        $stockDocOut->template_id = $this->template_id;
        $stockDocOut->template_name = $this->template_name;
        $stockDocOut->status = 'accepted';
        $stockDocOut->name = sprintf(@$mod_strings['SERVICE_WZ_NAME'], $this->document_no);
        $stockDocOut->register_date = $GLOBALS['timedate']->to_display_date(date("Y-m-d"));

        $stockDocOut->position_list = array();

        foreach ($this->income_list as $i) {
            $i['parent_doc_id'] = $this->id;
            $i['parent_doc_type'] = 'EcmServices';
            
            array_push($stockDocOut->position_list, $i);
        }

        $id = $stockDocOut->save();
        return $id;
    }

    /**
     * Save invoice out.
     *
     * Add FK with positions and services.
     *
     * @return string
     * @DEPRECATED
     */
     /*
    public function saveInvoiceOut() {
        //if (!isset($this->position_list) || !is_array($this->position_list))
        $this->position_list = $this->getPositionList(true);

        //if (!isset($this->services_list) || !is_array($this->services_list))
        $this->services_list = $this->getServicePositionList(true);

        //if (!isset($this->income_list) || !is_array($this->income_list))
        //    $this->income_list = $this->getIncomePositionList(true);

        include_once 'modules/EcmInvoiceOuts/EcmInvoiceOut.php';
        $invoiceOut = new EcmInvoiceOut();

		//add mz 2013-02-05
		//informacje o kontrahencie
		$invoiceOut->parent_id = $this->parent_id;
		$invoiceOut->parent_type = $this->parent_type;
		$invoiceOut->parent_name = $this->parent_name;
		$invoiceOut->parent_contact_name = $this->parent_contact_name;
		$invoiceOut->parent_contact_title = $this->parent_contact_title;
		$invoiceOut->parent_address_street = $this->parent_address_street;
		$invoiceOut->parent_address_city = $this->parent_address_city;
		$invoiceOut->parent_address_postalcode = $this->parent_address_postalcode;
		$invoiceOut->parent_address_country = $this->parent_address_country;
        $invoiceOut->contact_name = $this->parent_contact_name;
		//typ faktury
		$invoiceOut->type = 'normal';
		//end mz
        $invoiceOut->stock_id = $this->stock_id;
        $invoiceOut->stock_name = $this->stock_name;
        $invoiceOut->assigned_user_id = $this->assigned_user_id;
        $invoiceOut->ecmlanguage = $this->ecmlanguage;
        $invoiceOut->currency_id = $this->currency_id;
        $invoiceOut->template_id = $this->template_id;
        $invoiceOut->template_name = $this->template_name;
        //lepiej dać status registered, żeby ew. można było wprowadzić jakieś zmiany po automatycznym wystawieniu
		$invoiceOut->status = 'accepted';
        $invoiceOut->name = 'Faktura zlecenia serwisowego ' . $this->document_no;
        
        $invoiceOut->register_date = $invoiceOut->sell_date = $invoiceOut->payment_date = $GLOBALS['timedate']->to_display_date(date("Y-m-d"));

        $invoiceOut->position_list = array();

        foreach ($this->position_list as $p) {
            $p['parent_doc_id'] = $this->id;
            $i['parent_doc_type'] = 'EcmServices';
            
            array_push($invoiceOut->position_list, $p);
        }

        foreach ($this->services_list as $s) {
            $s['parent_doc_id'] = $this->id;
            $i['parent_doc_type'] = 'EcmServices';
            
            array_push($invoiceOut->position_list, $s);
        }

        //var_dump($this->position_list);
        //var_dump($this->services_list);
        //echo '<pre>' . var_export($invoiceOut->position_list, true) . PHP_EOL . PHP_EOL;
        //exit;

        $id = $invoiceOut->save();
        return $id;
    }
    */
    
    /**
     * Save stock doc inside in.
     *
     * Add PW with income_list.
     *
     * @return string
     */
    public function saveStockDocInsideIn() {
        global $mod_strings;
    
        //if (!isset($this->position_list) || !is_array($this->position_list))
        //    $this->position_list = $this->getPositionList(true);
        //if (!isset($this->services_list) || !is_array($this->services_list))
        //    $this->services_list = $this->getServicePositionList(true);
        //if (!isset($this->income_list) || !is_array($this->income_list))
        $this->income_list = $this->getIncomePositionList(true);

        include_once 'modules/EcmStockDocInsideIns/EcmStockDocInsideIn.php';
        $stockDocInsideIn = new EcmStockDocInsideIn();

        // Dane kontrahenta.
		$stockDocInsideIn->parent_id = $this->parent_id;
		$stockDocInsideIn->parent_type = $this->parent_type;
		$stockDocInsideIn->parent_name = $this->parent_name;
		$stockDocInsideIn->parent_contact_name = $this->parent_contact_name;
		$stockDocInsideIn->parent_contact_title = $this->parent_contact_title;
		$stockDocInsideIn->parent_address_street = $this->parent_address_street;
		$stockDocInsideIn->parent_address_city = $this->parent_address_city;
		$stockDocInsideIn->parent_address_postalcode = $this->parent_address_postalcode;
		$stockDocInsideIn->parent_address_country = $this->parent_address_country;
        $stockDocInsideIn->contact_name = $this->parent_contact_name;
        
        // Misc.
        $stockDocInsideIn->stock_id = $this->pw_stock_id;
        $stockDocInsideIn->stock_name = $this->pw_stock_name;
        $stockDocInsideIn->assigned_user_id = $this->assigned_user_id;
        $stockDocInsideIn->ecmlanguage = $this->ecmlanguage;
        $stockDocInsideIn->currency_id = $this->currency_id;
        $stockDocInsideIn->template_id = $this->template_id;
        $stockDocInsideIn->template_name = $this->template_name;
        $stockDocInsideIn->status = 'accepted';
        $stockDocInsideIn->name = sprintf(@$mod_strings['SERVICE_PW_NAME'], $this->document_no);
        $stockDocInsideIn->register_date = $GLOBALS['timedate']->to_display_date(date("Y-m-d"));
        
        // Positions.
        $stockDocInsideIn->position_list = $this->income_list;

        $id = $stockDocInsideIn->save();
        return $id;
    }

    /**
     * Save stock doc inside out.
     *
     * Add RW with position_list.
     *
     * @return string
     * @DEPRECATED
     */
    /*
    public function saveStockDocInsideOut() {
        //if (!isset($this->position_list) || !is_array($this->position_list))
        $this->position_list = $this->getPositionList(true);
        //if (!isset($this->services_list) || !is_array($this->services_list))
        //    $this->services_list = $this->getServicePositionList(true);
        //if (!isset($this->income_list) || !is_array($this->income_list))
        //    $this->income_list = $this->getIncomePositionList(true);

        include_once("modules/EcmStockDocInsideOuts/EcmStockDocInsideOut.php");
        $stockDocInsideOut = new EcmStockDocInsideOut();

        //
		$stockDocInsideOut->parent_id = $this->parent_id;
		$stockDocInsideOut->parent_type = $this->parent_type;
		$stockDocInsideOut->parent_name = $this->parent_name;
		$stockDocInsideOut->parent_contact_name = $this->parent_contact_name;
		$stockDocInsideOut->parent_contact_title = $this->parent_contact_title;
		$stockDocInsideOut->parent_address_street = $this->parent_address_street;
		$stockDocInsideOut->parent_address_city = $this->parent_address_city;
		$stockDocInsideOut->parent_address_postalcode = $this->parent_address_postalcode;
		$stockDocInsideOut->parent_address_country = $this->parent_address_country;
        $stockDocInsideOut->contact_name = $this->parent_contact_name;
        //
        $stockDocInsideOut->type = 3; // Naprawa.
        //
        $stockDocInsideOut->stock_id = $this->stock_id;
        $stockDocInsideOut->stock_name = $this->stock_name;
        $stockDocInsideOut->assigned_user_id = $this->assigned_user_id;
        $stockDocInsideOut->ecmlanguage = $this->ecmlanguage;
        $stockDocInsideOut->currency_id = $this->currency_id;
        $stockDocInsideOut->template_id = $this->template_id;
        $stockDocInsideOut->template_name = $this->template_name;
        $stockDocInsideOut->status = 'accepted';
        $stockDocInsideOut->name = "RW zlecenia serwisowego " . $this->document_no;
        $stockDocInsideOut->register_date = $GLOBALS['timedate']->to_display_date(date("Y-m-d"));
        $stockDocInsideOut->type = $this->type;
        $stockDocInsideOut->position_list = $this->position_list;

        //var_dump($stockDocInsideOut->position_list);
        //exit;

        $id = $stockDocInsideOut->save();
        return $id;
    }
    */
    
    /**
     * Total and subtotal locally stored values calculator.
     */
    function getTotalSubtotalLocal() {
        $r = array(
            'total' => 0.0,
            'subtotal' => 0.0,
        );
    
        foreach($this->position_list as $v) {
            $tSubTotal = $tTotal = $v['quantity'] * $v['price'] * (1 - $v['discount'] / 100);
            $tSubTotal *= (1 + $v['vat_value'] / 100);

            $r['total'] += $tTotal;
            $r['subtotal'] += $tSubTotal;
        }
        
        foreach($this->services_list as $v) {
            $tSubTotal = $tTotal = $v['quantity'] * $v['price'] * (1 - $v['discount'] / 100);
            $tSubTotal *= (1 + $v['vat_value'] / 100);;

            $r['total'] += $tTotal;
            $r['subtotal'] += $tSubTotal;
        }
    
        return array(
            str_replace('.', ',', @$r['total']),
            str_replace('.', ',', @$r['subtotal']),
        );
    }
    
    /**
     * All type items total getter.
     *
     * Get total price with discount and vat included.
     *
     * @global type $db
     * @return string
     */
    function getTotalSubtotal() {
        global $db;

        $query = '
                SELECT
                    SUM(
                        i.`quantity` * i.`price` * (1 - i.`discount` / 100)
                    ) as total,
                    SUM(
                        i.`quantity` * i.`price` * (1 - i.`discount` / 100) * (1 + i.`ecmvat_value` / 100)
                    ) as subtotal
                FROM
                    `ecmserviceitems` as i
                WHERE
                    i.`ecmservice_id` = \'' . $this->id . '\'
                AND
                    i.`deleted` = \'0\'
                ';

        $r = $db->fetchByAssoc($db->query($query));

        return array(
            str_replace('.', ',', @$r['total']),
            str_replace('.', ',', @$r['subtotal']),
        );
    }
    
    function getArticlesTotalSubtotalLocal() {
        $r = array(
            'total' => 0.0,
            'subtotal' => 0.0,
        );
    
        foreach($this->position_list as $v) {
            $tSubTotal = $tTotal = $v['quantity'] * $v['price'] * (1 - $v['discount'] / 100);
            $tSubTotal *= (1 + $v['vat_value'] / 100);;

            $r['total'] += $tTotal;
            $r['subtotal'] += $tSubTotal;
        }
    
        return array(
            str_replace('.', ',', @$r['total']),
            str_replace('.', ',', @$r['subtotal']),
        );
    }

    /**
     * Article type items total getter.
     *
     * Get total price with discount and vat included.
     *
     * @global type $db
     * @return string
     */
    function getArticlesTotalSubtotal() {
        global $db;

        $query = '
                SELECT
                    SUM(
                        i.`quantity` * i.`price` * (1 - i.`discount` / 100)
                    ) as total,
                    SUM(
                        i.`quantity` * i.`price` * (1 - i.`discount` / 100) * (1 + i.`ecmvat_value` / 100)
                    ) as subtotal
                FROM
                    `ecmserviceitems` as i
                WHERE
                    i.`ecmservice_id` = \'' . $this->id . '\'
                AND
                    i.`product_type` != \'service\'
                AND
                    i.`deleted` = \'0\'
                ';

        $r = $db->fetchByAssoc($db->query($query));

        return array(
            str_replace('.', ',', @$r['total']),
            str_replace('.', ',', @$r['subtotal']),
        );
    }

    function getServicesTotalSubtotalLocal() {
        $r = array(
            'total' => 0.0,
            'subtotal' => 0.0,
        );
        
        foreach($this->services_list as $v) {
            $tSubTotal = $tTotal = $v['quantity'] * $v['price'] * (1 - $v['discount'] / 100);
            $tSubTotal *= (1 + $v['vat_value'] / 100);;

            $r['total'] += $tTotal;
            $r['subtotal'] += $tSubTotal;
        }
    
        return array(
            str_replace('.', ',', @$r['total']),
            str_replace('.', ',', @$r['subtotal']),
        );
    }
    
    /**
     * Service type items total getter.
     *
     * Get total price with discount and vat included.
     *
     * @global type $db
     * @return string
     */
    function getServicesTotalSubtotal() {
        global $db;

        $query = '
                SELECT
                    SUM(
                        i.`quantity` * i.`price` * (1 - i.`discount` / 100)
                    ) as total,
                    SUM(
                        i.`quantity` * i.`price` * (1 - i.`discount` / 100) * (1 + i.`ecmvat_value` / 100)
                    ) as subtotal
                FROM
                    `ecmserviceitems` as i
                WHERE
                    i.`ecmservice_id` = \'' . $this->id . '\'
                AND
                    i.`product_type` = \'service\'
                AND
                    i.`deleted` = \'0\'
                ';

        $r = $db->fetchByAssoc($db->query($query));

        return array(
            str_replace('.', ',', @$r['total']),
            str_replace('.', ',', @$r['subtotal']),
        );
    }

    // ***************************Start Managing Positions************************* //

    function constructInsertQuery($data, $table = '') {
        if ($table == '' && isset($this->object_name) && $this->object_name != '') {
            $table = strtolower($this->object_name) . "items";
        } else {
            return "";
        }

        $keys = array();
        $values = array();
        foreach ($data as $key => $value) {
            $keys[] = $key;

            if (is_array($value))
                $values[] = $value[1] . str_replace("'", "\'", $value[0]) . $value[1];
            else
                $values[] = "'" . str_replace("'", "\'", $value) . "'";
        }

        $q = "insert into `$table` (`";
        $q .= implode('`, `', $keys);
        $q .= "`) values (";
        $q .= implode(", ", $values);
        $q .= ");";

        return $q;
    }

    /**
     * Incomes type items saver.
     *
     * @global type $current_user
     * @global type $timedate
     * @global type $db
     *
     * @param type $id
     * @param type $services_list
     *
     * @return void
     */
    function saveIncomes($id = null, $income_list = null) {
        global $current_user, $db;

        if ($income_list == null)
            $income_list = $this->income_list;

        if ($id == null)
            $id = $this->id;

        $iCounter = count($income_list);

        if ($iCounter > 0)
            $this->deleteAssignedIncomes($id);

        $arr = array();
        $income = 0;

        for ($i = 0; $i < $iCounter; $i++) {
            if ($income_list[$i]['name'] == '')
                continue;

            $p = $income_list[$i];

            require_once("modules/EcmVats/EcmVat.php");

            $vats = new EcmVat();
            $vats->retrieve($p['vat_id']);

            $p['vat_name'] = $vats->name;

            require_once("modules/Currencies/Currency.php");

            $curr = new Currency();
            $curr->retrieve($p['currency_id']);

            $p['currency_name'] = $curr->name;

            $guid = create_guid();
            $pr = $db->fetchByAssoc($db->query("select unit_name from ecmproducts where id='" . $id . "'"));
            $arr = array(
                'id' => $guid,
                'date_entered' => array('NOW()', ''),
                'date_modified' => array('NOW()', ''),
                'modified_user_id' => $current_user->id,
                'assigned_user_id' => $current_user->id,
                'created_by' => $current_user->id,
                'deleted' => '0',
                strtolower($this->object_name) . '_id' => $id,
                'ecmproduct_id' => $p['id'],
                'item_id' => $p['item_id'],
                'position' => $income,
                'code' => $p['code'],
                'name' => $p['name'],
                'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
                'price' => ((empty($p['price']) || $p['price'] == '') ? 0 : $p['price']),
                'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
                'total' => ((empty($p['total']) || $p['total'] == '') ? 0 : $p['total']),
                'ecmvat_id' => $p['vat_id'],
                'ecmvat_name' => $p['vat_name'],
                'ecmvat_value' => $p['vat_value'],
                'currency_id' => $p['currency_id'],
                'currency_name' => $p['currency_name'],
                'recipient_code' => $p['recipient_code'],
                'dd_unit_name' => $p['unit_name'],
                'dd_unit_id' => $p['unit_name'],
                'product_type' => 'income',
            );

            $query = $this->constructInsertQuery($arr);
            //echo $query . PHP_EOL;

            $this->db->query($query);

            //change temp reservation into income reservation
            $this->db->query("update ecmreservations set doc_id='" . $id . "',item_id='" . $guid . "',doc_type='EcmServices', temp_item_id=NULL, temp_doc_id=NULL, session_id=NULL where temp_item_id='" . $p['temp_item_id'] . "'");


            //start debug
            require_once('include/firebugphp/FirePHP.class.php');

            ob_start();
            $firephp = FirePHP::getInstance(true);
            $firephp->log("update ecmreservations set doc_id='" . $id . "',item_id='" . $guid . "',doc_type='EcmServices', temp_item_id=NULL, temp_doc_id=NULL, session_id=NULL where temp_item_id='" . $p['temp_item_id'] . "'", 'PZ');

            //end debug
            //$this->saveParams($arr['id'],$arr['ecmproduct_id']);
            $income++;
        }
    }

    /**
     * Services type items saver.
     *
     * @global type $current_user
     * @global type $timedate
     * @global type $db
     *
     * @param type $id
     * @param type $services_list
     *
     * @return void
     */
    function saveServices($id = null, $services_list = null) {
        global $current_user, $timedate, $db;

        if ($services_list == null)
            $services_list = $this->services_list;

        if ($id == null)
            $id = $this->id;

        $iCounter = count($services_list);

        if ($iCounter > 0)
            $this->deleteAssignedServices($id);

        $arr = array();
        $service = 0;

        for ($i = 0; $i < $iCounter; $i++) {
            if ($services_list[$i]['name'] == '')
                continue;

            $p = $services_list[$i];

            require_once("modules/EcmVats/EcmVat.php");

            $vats = new EcmVat();
            $vats->retrieve($p['vat_id']);

            $p['vat_name'] = $vats->name;

            require_once("modules/Currencies/Currency.php");
            $curr = new Currency();
            $curr->retrieve($p['currency_id']);

            $p['currency_name'] = $curr->name;

            $guid = create_guid();
            $pr = $db->fetchByAssoc($db->query("select unit_name from ecmproducts where id='" . $id . "'"));
            $arr = array(
                'id' => $guid,
                'date_entered' => array('NOW()', ''),
                'date_modified' => array('NOW()', ''),
                'modified_user_id' => $current_user->id,
                'assigned_user_id' => $current_user->id,
                'created_by' => $current_user->id,
                'deleted' => '0',
                strtolower($this->object_name) . '_id' => $id,
                'ecmproduct_id' => $p['id'],
                'item_id' => $p['item_id'],
                'position' => $service,
                'code' => $p['code'],
                'name' => $p['name'],
                'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
                'price' => ((empty($p['price']) || $p['price'] == '') ? 0 : $p['price']),
                'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
                'total' => ((empty($p['total']) || $p['total'] == '') ? 0 : $p['total']),
                'ecmvat_id' => $p['vat_id'],
                'ecmvat_name' => $p['vat_name'],
                'ecmvat_value' => $p['vat_value'],
                'currency_id' => $p['currency_id'],
                'currency_name' => $p['currency_name'],
                'recipient_code' => $p['recipient_code'],
                'dd_unit_name' => $p['unit_name'],
                'dd_unit_id' => $p['unit_name'],
                'product_type' => 'service',
            );

            $query = $this->constructInsertQuery($arr);
            $this->db->query($query);

            //change temp reservation into service reservation
            $this->db->query("update ecmreservations set doc_id='" . $id . "',item_id='" . $guid . "',doc_type='EcmServices', temp_item_id=NULL, temp_doc_id=NULL, session_id=NULL where temp_item_id='" . $p['temp_item_id'] . "'");

            //start debug
            require_once('include/firebugphp/FirePHP.class.php');

            ob_start();
            $firephp = FirePHP::getInstance(true);
            $firephp->log("update ecmreservations set doc_id='" . $id . "',item_id='" . $guid . "',doc_type='EcmServices', temp_item_id=NULL, temp_doc_id=NULL, session_id=NULL where temp_item_id='" . $p['temp_item_id'] . "'", 'PZ');

            //end debug
            //$this->saveParams($arr['id'],$arr['ecmproduct_id']);
            $service++;
        }
    }

    /**
     * Articles type items saver.
     *
     * @global type $current_user
     * @global type $timedate
     * @global type $db
     *
     * @param type $id
     * @param type $services_list
     *
     * @return void
     */
    function savePositions($id = null, $position_list = null) {
        global $current_user, $timedate, $db;

        if ($position_list == null)
            $position_list = $this->position_list;

        if ($id == null)
            $id = $this->id;

        if (count($position_list) > 0)
            $this->deleteAssignedPositions($id);

        $arr = array();
        $position = 0;

        for ($i = 0; $i < count($position_list); $i++) {
            if ($position_list[$i]['name'] == '')
                continue;

            $p = $position_list[$i];


            require_once("modules/EcmVats/EcmVat.php");
            $vats = new EcmVat();
            $vats->retrieve($p['vat_id']);
            $p['vat_name'] = $vats->name;

            require_once("modules/Currencies/Currency.php");
            $curr = new Currency();
            $curr->retrieve($p['currency_id']);
            $p['currency_name'] = $curr->name;

            $guid = create_guid();
            $pr = $db->fetchByAssoc($db->query("select unit_name from ecmproducts where id='" . $id . "'"));
            $arr = array(
                'id' => $guid,
                'date_entered' => array('NOW()', ''),
                'date_modified' => array('NOW()', ''),
                'modified_user_id' => $current_user->id,
                'assigned_user_id' => $current_user->id,
                'created_by' => $current_user->id,
                'deleted' => '0',
                strtolower($this->object_name) . '_id' => $id,
                'ecmproduct_id' => $p['id'],
                'item_id' => $p['item_id'],
                'position' => $position,
                'code' => $p['code'],
                'name' => $p['name'],
                'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
                'price' => ((empty($p['price']) || $p['price'] == '') ? 0 : $p['price']),
                'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
                'total' => ((empty($p['total']) || $p['total'] == '') ? 0 : $p['total']),
                'ecmvat_id' => $p['vat_id'],
                'ecmvat_name' => $p['vat_name'],
                'ecmvat_value' => $p['vat_value'],
                'currency_id' => $p['currency_id'],
                'currency_name' => $p['currency_name'],
                'recipient_code' => $p['recipient_code'],
                'dd_unit_name' => $p['unit_name'],
                'dd_unit_id' => $p['unit_name'],
                'product_type' => 'article',
            );

            $query = $this->constructInsertQuery($arr);
            $this->db->query($query);

            //change temp reservation into service reservation
            $this->db->query("update ecmreservations set doc_id='" . $id . "',item_id='" . $guid . "',doc_type='EcmServices', temp_item_id=NULL, temp_doc_id=NULL, session_id=NULL where temp_item_id='" . $p['temp_item_id'] . "'");

            //start debug
            require_once('include/firebugphp/FirePHP.class.php');

            ob_start();
            $firephp = FirePHP::getInstance(true);
            $firephp->log("update ecmreservations set doc_id='" . $id . "',item_id='" . $guid . "',doc_type='EcmServices', temp_item_id=NULL, temp_doc_id=NULL, session_id=NULL where temp_item_id='" . $p['temp_item_id'] . "'", 'PZ');
            //end debug
            //$this->saveParams($arr['id'],$arr['ecmproduct_id']);

            $position++;
        }
    }

    function saveParams($item_id, $ecmproduct_id) {
        global $db;

        $w = $db->query("select name,symbol,unit,value,type from ecmproductparams where ecmproduct_id='" . $ecmproduct_id . "' and deleted='0'");

        while ($r = $db->fetchByAssoc($w)) {
            $set = $r;

            $set['id'] = create_guid();
            $set['date_modified'] = date("Y-m-d H:i:s");
            $set['modified_user_id'] = $_SESSION['authenticated_user_id'];
            $set['deleted'] = 0;
            $set['ecmservice_id'] = $this->id;
            $set['ecmproduct_id'] = $ecmproduct_id;
            $set['item_id'] = $item_id;

            $s = array();

            foreach ($set as $k => $v) {
                $s[] = $k . "='" . $v . "'";
            }

            $db->query("insert into ecmserviceitemsparams set " . implode(",", $s));
        }
    }

    function getPosition($position) {
        if (!is_array($position))
            return '';

        global $timedate;
        global $db;

        $rq = "select q.document_no,q.id from ecmquotes as q inner join ecmquoteitems as i on i.ecmquote_id=q.id where i.id='" . $position['item_id'] . "'";

        $r = $db->fetchByAssoc($db->query($rq));

        $rsq = "select sum(quantity) as q from ecmstockdocoutitems where item_id='" . $position['id'] . "'";

        $rs = $db->fetchByAssoc($db->query($rsq));

        $prq = "select unit_name from ecmproducts where id='" . $position['ecmproduct_id'] . "'";

        $pr = $db->fetchByAssoc($db->query($prq));

        $rrq = 'SELECT quantity FROM `ecmreservations` AS r WHERE r.`item_id` = \'' . $position['id'] . '\' AND r.`doc_id` = \'' . $this->id . '\';';

        $rr = $db->fetchByAssoc($db->query($rrq));

        $return_array = array();

        $return_array['id'] = $position['ecmproduct_id'];
        $return_array['ecmquote_id'] = $r['id'];
        $return_array['ecmquote_name'] = $r['document_no'];
        $return_array['iid'] = $position['id'];
        $return_array['item_id'] = $position['item_id'];
        $return_array['position'] = $position['position'];
        $return_array['code'] = $position['code'];
        $return_array['name'] = $position['name'];
        $return_array['quantity'] = $position['quantity'];
        $return_array['price'] = $position['price'];
        $return_array['discount'] = $position['discount'];
        $return_array['total'] = $position['total'];
        $return_array['unit_id'] = $position['dd_unit_id'];
        $return_array['unit_name'] = $pr['unit_name'];
        $return_array['vat_id'] = $position['ecmvat_id'];
        $return_array['vat_name'] = $position['ecmvat_name'];
        $return_array['vat_value'] = $position['ecmvat_value'];
        $return_array['category_id'] = $position['ecmproductcategory_id'];
        $return_array['currency_id'] = $position['currency_id'];
        $return_array['currency_name'] = $position['currency_name'];
        $return_array['recipient_code'] = $position['recipient_code'];
        //$return_array['temp_item_id'] = $position['temp_item_id'];
        $return_array['temp_item_id'] = $position['id'];
        //$return_array['temp_date'] = $position['temp_date'];
        //$return_array['rq'] = $position['rq'];
        $return_array['rq'] = $rr['quantity'];
        $return_array['type'] = $position['product_type'];

        if ($rs['q'] < $position['quantity'])
            $return_array['check'] = $position['id'];

        include_once("modules/EcmStockOperations/EcmStockOperation.php");

        $op = new EcmStockOperation();
        $return_array['stock'] = $op->getStock($position['ecmproduct_id']);

        return $return_array;
    }

    function getPositionList($returnarray = false) {
        if (isset($this->id) && $this->id != '') {
            $objectName = strtolower($this->object_name);
            $query = '
                SELECT
                    i.*
                FROM
                    `' . $objectName . 'items` AS i
                WHERE
                    `' . $objectName . '_id` = \'' . $this->id . '\'
                AND
                    i.`product_type` = \'article\'
                ORDER BY
                    position ASC
                ';

            $r = $this->db->query($query);
            $return_array = array();
            if ($r) {
                while ($w = $this->db->fetchByAssoc($r)) {
                    $return_array[] = $this->getPosition($w);
                }

                $json = getJSONobj();

                return $returnarray ? $return_array : $json->encode($return_array);
            }
        }

        return $returnarray ? false : '[]';
    }

    /**
     * Service type items getter.
     *
     * @param boolean $returnarray
     * @return array | string
     */
    function getServicePositionList($returnarray = false) {
        if (isset($this->id) && $this->id != '') {
            $objectName = strtolower($this->object_name);

            $query = '
                SELECT
                    i.*
                FROM
                    `' . $objectName . 'items` AS i
                WHERE
                    `' . $objectName . '_id` = \'' . $this->id . '\'
                AND
                    i.`product_type` = \'service\'
                ORDER BY
                    position ASC
                ';

            $r = $this->db->query($query);
            $return_array = array();

            if ($r) {
                while ($w = $this->db->fetchByAssoc($r)) {
                    $return_array[] = $this->getPosition($w);
                }

                $json = getJSONobj();

                return $returnarray ? $return_array : $json->encode($return_array);
            }
        }

        return $returnarray ? false : '[]';
    }

    /**
     * Income type items getter.
     *
     * @param boolean $returnarray
     * @return array | string
     */
    function getIncomePositionList($returnarray = false) {
        if (isset($this->id) && $this->id != '') {
            $objectName = strtolower($this->object_name);

            $query = '
                SELECT
                    i.*
                FROM
                    `' . $objectName . 'items` AS i
                WHERE
                    `' . $objectName . '_id` = \'' . $this->id . '\'
                AND
                    i.`product_type` = \'income\'
                ORDER BY
                    position ASC
                ';

            $r = $this->db->query($query);
            $return_array = array();

            if ($r) {
                while ($w = $this->db->fetchByAssoc($r)) {
                    $return_array[] = $this->getPosition($w);
                }

                $json = getJSONobj();

                return $returnarray ? $return_array : $json->encode($return_array);
            }
        }

        return $returnarray ? false : '[]';
    }

    /**
     * Assigned article type items deleter.
     *
     * @return boolean
     */
    function deleteAssignedPositions() {
        if (isset($this->id) && $this->id != '') {
            $r = true;
            $objectName = strtolower($this->object_name);

            //$paramsQuery = 'DELETE FROM `' . $objectName . 'itemsparams` WHERE `' . $objectName . '_id`=\'' . $this->id . '\'';
            $itemsQuery = 'DELETE FROM `' . $objectName . 'items` WHERE `' . $objectName . '_id`=\'' . $this->id . '\' AND `product_type` = \'article\'';

            //$r &= $this->db->query($paramsQuery);
            $r &= $this->db->query($itemsQuery);

            return $r;
        }

        return false;
    }

    /**
     * Assigned service type items deleter.
     *
     * @return boolean
     */
    function deleteAssignedServices() {
        if (isset($this->id) && $this->id != '') {
            $r = true;
            $objectName = strtolower($this->object_name);

            //$paramsQuery = 'DELETE FROM `' . $objectName . 'itemsparams` WHERE `' . $objectName . '_id`=\'' . $this->id . '\'';
            $itemsQuery = 'DELETE FROM `' . $objectName . 'items` WHERE `' . $objectName . '_id`=\'' . $this->id . '\' AND `product_type` = \'service\'';

            //$r &= $this->db->query($paramsQuery);
            $r &= $this->db->query($itemsQuery);

            return $r;
        }

        return false;
    }

    /**
     * Assigned income type items deleter.
     *
     * @return boolean
     */
    function deleteAssignedIncomes() {
        if (isset($this->id) && $this->id != '') {
            $r = true;
            $objectName = strtolower($this->object_name);

            //$paramsQuery = 'DELETE FROM `' . $objectName . 'itemsparams` WHERE `' . $objectName . '_id`=\'' . $this->id . '\'';
            $itemsQuery = 'DELETE FROM `' . $objectName . 'items` WHERE `' . $objectName . '_id`=\'' . $this->id . '\' AND `product_type` = \'income\'';

            //$r &= $this->db->query($paramsQuery);
            $r &= $this->db->query($itemsQuery);

            return $r;
        }

        return false;
    }

    //***************************End Managing Positions*************************//

    static function getTranslation($module, $id, $language) {
        if (isset($id) && $id != '' && isset($module) && $module != '') {
            global $beanList, $beanFiles;
            $file = $beanFiles[$beanList[$module]];
            if (file_exists($file)) {
                require_once($file);
                $bean = new $beanList[$module]();
                $bean->retrieve($id);
                if (isset($bean->id) && $bean->id != '') {
                    if (isset($bean->translations[$language]) && $bean->translations[$language] != '')
                        return $bean->translations[$language];
                }
            }
        }
        return null;
    }

    function getTemplateList() {
        global $db;
        $query = "select `id`,`name` from `ecmdocumenttemplates` where `deleted`='0' order by `name`";

        $result = $db->query($query);

        $arr = array();

        if ($result)
            while ($row = $db->fetchByAssoc($result))
                $arr[$row['id']] = $row['name'];

        return $arr;
    }

    function setTemplate() {
        if (!isset($this->template_id) || $this->template_id == '')
            return null;

        if (isset($this->template))
            return $this->template;

        require_once('modules/EcmDocumentTemplates/EcmDocumentTemplate.php');

        $this->template = new EcmDocumentTemplate();
        //$this->template->retrieve($this->template_id);
        $this->template->retrieve($this->template_id, true, false);

        if (isset($this->template->id) && $this->template->id != '') {
            $this->template->format_all_fields();
        } else {
            $this->template = null;
        }

        return $this->template;
    }

    function generateNumber() {
        $this->setTemplate();
        $this->number = isset($this->template) ? $this->template->generateNumber($this->table_name) : '';

        return $this->number;
    }

    function formatNumber() {
        $this->setTemplate();

        $this->document_no = isset($this->template) ? $this->template->formatNumber($this->number, $this->module_dir) : '';
        return $this->document_no;
    }

    function formatDocumentNumber($documentNumber = '', $code = '') {
        return isset($this->template) ? $this->template->formatDocumentNumber($documentNumber, $code) : '';
    }

    function DrawPositions($pdf = null) {
        global $mod_strings;
        if (!isset($this->position_list) || !is_array($this->position_list))
            $this->position_list = $this->getPositionList(true);

        $calc = $this->calculate($this->position_list, $this->services_list, true);
        $this->position_list = $this->formatPositions($this->position_list);

        require_once('modules/Currencies/Currency.php');
        $currency = new Currency();
        $currency->retrieve($this->currency_id);

        $calc['articles_total'] .= ' ' . $currency->iso4217;
        $calc['articles_subtotal'] .= ' ' . $currency->iso4217;

        $calc['services_total'] .= ' ' . $currency->iso4217;
        $calc['services_subtotal'] .= ' ' . $currency->iso4217;

        if ($calc['discount']) {
            $calc['total2'] .= ' ' . $currency->iso4217;
            $calc['discount']['value'] .= ' ' . $currency->iso4217;
        }

        if (isset($calc['vats']) && is_array($calc['vats']) && count($calc['vats']) > 0)
            foreach ($calc['vats'] as $key => $value)
                $calc['vats'][$key] .= ' ' . $currency->iso4217;

        $name_w = 47;
        $image_w = 10;
        $recipient_code_w = 10;

        if ($this->show_images_on_offers) {
            $name_w -= $image_w;
        }
        if ($this->show_recipient_code) {
            $name_w -= $recipient_code_w;
        }

        if ($calc['draw_discount']) {
            $name_w -= 8;
        }

        /*
          if($calc['draw_vat']) {
          $name_w -= 8;
          }
         */

        $table = array();
        if ($this->show_images_on_offers)
            $table[0]['image'] = array('width' => $image_w, 'value' => $mod_strings['LBL_PDF_LIST_IMAGE'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'R');

        $table[0]['position'] = array('width' => 5, 'value' => $mod_strings['LBL_PDF_LIST_POSITION'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
        $table[0]['code'] = array('width' => 12, 'value' => $mod_strings['LBL_PDF_LIST_CODE'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
        if ($this->show_recipient_code)
            $table[0]['recipient_code'] = array('width' => $recipient_code_w, 'value' => $mod_strings['LBL_PDF_LIST_RECIPIENT_CODE'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'C');

        //$table[0]['unit'] = array('width' => 10, 'value' => $mod_strings['LBL_PDF_LIST_UNIT'],'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
        $table[0]['description'] = array('width' => $name_w, 'value' => $mod_strings['LBL_PDF_LIST_DESCRIPTION'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
        $table[0]['quantity'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_QUANTITY'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
        $table[0]['unit_price'] = array('width' => 14, 'value' => $mod_strings['LBL_PDF_LIST_PRICE'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
        if ($calc['draw_discount'])
            $table[0]['discount'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_DISCOUNT'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'R');
        //if($calc['draw_vat']) $table[0]['vat_id'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_VAT'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'R');
        $table[0]['articles_total'] = array('width' => 14, 'value' => $mod_strings['LBL_PDF_LIST_TOTAL'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'R');

        $i = 1;

        if ($this->position_list != '')
            foreach ($this->position_list as $p) {
                if ($this->show_images_on_offers) {
                    if (file_exists($this->getProductImage($p['id']))) {
                        $table[$i]['image'] = array('width' => $image_w, 'value' => '', 'border' => 0, 'align' => 'R', 'image_path' => $this->getProductImage($p['id']));
                        //$iarr[]=$this->getProductImage($p['id']);
                    }
                    else
                        $table[$i]['image'] = array('width' => $image_w, 'value' => '', 'border' => 0, 'align' => 'R');
                }
                $table[$i]['position'] = array('width' => 5, 'value' => $i, 'border' => 0, 'align' => 'C',);
                $table[$i]['code'] = array('width' => 12, 'value' => $p['code'], 'border' => 0, 'align' => 'C',);

                if ($this->show_recipient_code)
                    $table[$i]['recipient_code'] = array('width' => $recipient_code_w, 'value' => $p['recipient_code'], 'border' => 0, 'align' => 'C',);

                //$table[$i]['unit'] = array('width' => 10, 'value' => $p['unit_id'], 'border' => 0, 'align' => 'C', );

                /*
                  if($this->ecmlanguage=="en_us"){
                  $r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select short_description from ecmproduct_language_en_view where ecmproduct_id='".$p['id']."'"));
                  $dname=$r['short_description'];
                  }
                  elseif($this->ecmlanguage=="ge_ge"){
                  $r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select short_description from ecmproduct_language_de_view where ecmproduct_id='".$p['id']."'"));
                  $dname=$r['short_description'];
                  }
                  else $dname=$p['name'];
                 */

                $table[$i]['description'] = array('width' => $name_w, 'value' => htmlspecialchars_decode($p['name']), 'border' => 0, 'align' => 'L',);
                $table[$i]['quantity'] = array('width' => 8, 'value' => $p['quantity'], 'border' => 0, 'align' => 'C',);
                $table[$i]['unit_price'] = array('width' => 14, 'value' => $p['price'], 'border' => 0, 'align' => 'C',);
                if ($calc['draw_discount'])
                    $table[$i]['discount'] = array('width' => 8, 'value' => $p['discount'], 'border' => 0, 'align' => 'R',);

                //if($calc['draw_vat']) $table[$i]['vat_id'] = array('width' => 8, 'value' => $p['vat_name'], 'border' => 0, 'align' => 'R', );
                $table[$i]['articles_total'] = array('width' => 14, 'value' => $p['articles_total'], 'border' => 0, 'align' => 'R',);
                $i++;
            }
        $starttab = $pdf->GetY() + 10;
        $pdf->DrawTable($table, array(0));
        $endtab = $pdf->GetY();
        //for($n=0;$n<$i;$n++){
        //if(file_exists($iarr[$n]))$pdf->Image($iarr[$n],$pdf->GetX()+1,$starttab+$n*18+1,15,0);
        //}
        $pdf->SetY($endtab);
        //total, vat, subtotal

        $pdf->Ln(4);
        $pr = ($pdf->fw - $pdf->lMargin - $pdf->rMargin) / 100;
        //$pdf->SetX($pdf->fw-$pdf->rMargin-$pr*34);
        $table = array();

        /* if($calc['vats']) {
          $table[] = array(
          'subtotal1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_TOTAL'], 'background' => array(255,255,255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9),
          'subtotal2' => array('width' => 34, 'value' => $calc['articles_subtotal'], 'border' => 0, 'overflow' => 1, 'align' => 'R', 'font-size' => 9), );

          foreach($calc['vats'] as $key => $value){
          $r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name from ecmvats where id='".$key."'"));
          $vvn=$r['name'];
          $table[] = array(
          'vat1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_VAT'].' ('.$vvn.')', 'background' => array(255,255,255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9),
          'vat2' => array('width' => 34, 'value' => $value, 'border' => 0, 'overflow' => 1, 'align' => 'R', 'font-size' => 9), );
          }
          } */

        if (isset($calc['discount'])) {
            $table[] = array(
                'total21' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_TOTAL'], 'background' => array(255, 255, 255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9, 'font-style' => 'b'),
                'total22' => array('width' => 34, 'value' => $calc['total2'], 'border' => 0, 'overflow' => 1, 'align' => 'R', 'font-size' => 9),);
            $table[] = array(
                'discount1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_DISCOUNT'] . ' ' . $calc['discount']['procent'], 'background' => array(255, 255, 255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9, 'font-style' => 'b'),
                'discount2' => array('width' => 34, 'value' => $calc['discount']['value'], 'border' => 0, 'overflow' => 1, 'align' => 'R', 'font-size' => 9),);
        }

        $table[] = array(
            'total1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_END_TOTAL'], 'background' => array(233, 233, 233), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9, 'font-style' => 'b'),
            'total2' => array('width' => 34, 'value' => $calc['articles_total'], 'border' => 0, 'background' => array(233, 233, 233), 'overflow' => 1, 'align' => 'R', 'font-size' => 9, 'font-style' => 'b'),);

        $pdf->DrawTable($table);
    }

    function getProductImage($pr_id) {
        $query = "SELECT `product_picture` FROM `ecmproducts` WHERE `id`='$pr_id'";
        $result = $GLOBALS['db']->query($query);
        if (is_resource($result)) {
            $result = $GLOBALS['db']->fetchByAssoc($result);
            if (isset($result['product_picture']) && $result['product_picture'] != '')
                return 'modules/EcmProducts/upload/images/' . $result['product_picture'];
        }
        return '';
    }

    function DrawMainPDF($pdf, $type) {
        global $mod_strings;

        $arr = $this->template->getTemplateFile($_REQUEST['module']);

        $pdf->setAutoPageBreak(false, 40);

        /*
        $_x = 'YToxNjp7czoxNjoiRWNtRGVsaXZlcnlOb3RlcyI7czoyOiJlNSI7czoxMjoiRWNtRG9jdW1lbnRzIjtzOjI6ImU1IjtzOjE1OiJFY21JbnNpZGVPcmRlcnMiO3M6MjoiZTUiO3M6MTQ6IkVjbUludm9pY2VPdXRzIjtzOjI6ImU1IjtzOjE3OiJFY21QdXJjaGFzZU9yZGVycyI7czoyOiJlNSI7czo5OiJFY21RdW90ZXMiO3M6Nzoic2Fhc2NybSI7czoxNDoiRWNtUmVjZWlwdE91dHMiO3M6MjoiZTUiO3M6MTE6IkVjbVJlY2VpcHRzIjtzOjI6ImU1IjtzOjg6IkVjbVNhbGVzIjtzOjI6ImU1IjtzOjE5OiJFY21TdG9ja0RvY0NvcnJlY3RzIjtzOjI6ImU1IjtzOjE0OiJFY21TdG9ja0RvY0lucyI7czoyOiJlNSI7czoyMDoiRWNtU3RvY2tEb2NJbnNpZGVJbnMiO3M6MjoiZTUiO3M6MjE6IkVjbVN0b2NrRG9jSW5zaWRlT3V0cyI7czoyOiJlNSI7czoxNjoiRWNtU3RvY2tEb2NNb3ZlcyI7czoyOiJlNSI7czoxNToiRWNtU3RvY2tEb2NPdXRzIjtzOjI6ImU1IjtzOjEyOiJFY21UZW1wbGF0ZXMiO3M6MjoiZTUiO30=';
        $x = 'YToxNzp7czoxNjoiRWNtRGVsaXZlcnlOb3RlcyI7czoyOiJlNSI7czoxMjoiRWNtRG9jdW1lbnRzIjtzOjI6ImU1IjtzOjE1OiJFY21JbnNpZGVPcmRlcnMiO3M6MjoiZTUiO3M6MTQ6IkVjbUludm9pY2VPdXRzIjtzOjI6ImU1IjtzOjE3OiJFY21QdXJjaGFzZU9yZGVycyI7czoyOiJlNSI7czo5OiJFY21RdW90ZXMiO3M6Nzoic2Fhc2NybSI7czoxNDoiRWNtUmVjZWlwdE91dHMiO3M6MjoiZTUiO3M6MTE6IkVjbVJlY2VpcHRzIjtzOjI6ImU1IjtzOjg6IkVjbVNhbGVzIjtzOjI6ImU1IjtzOjExOiJFY21TZXJ2aWNlcyI7czoyOiJlNSI7czoxOToiRWNtU3RvY2tEb2NDb3JyZWN0cyI7czoyOiJlNSI7czoxNDoiRWNtU3RvY2tEb2NJbnMiO3M6MjoiZTUiO3M6MjA6IkVjbVN0b2NrRG9jSW5zaWRlSW5zIjtzOjI6ImU1IjtzOjIxOiJFY21TdG9ja0RvY0luc2lkZU91dHMiO3M6MjoiZTUiO3M6MTY6IkVjbVN0b2NrRG9jTW92ZXMiO3M6MjoiZTUiO3M6MTU6IkVjbVN0b2NrRG9jT3V0cyI7czoyOiJlNSI7czoxMjoiRWNtVGVtcGxhdGVzIjtzOjI6ImU1Ijt9';
        $a = unserialize(base64_decode($x));
        //$a['EcmServices'] = 'e5';
        //ksort($a);
        
        echo '<pre>' . var_export($a, true);
        //echo '<pre>' .(base64_encode(serialize($a))) . '</pre>';
        exit;
        */
        
        switch (strtolower($type)) {
            default:
            case 'income':
                include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subheader_income.php");
                //include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subfooter_income.php");

                break;
            case 'fault':
                include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subheader_fault.php");
                //include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subfooter_fault.php");

                break;
            case 'val':
                include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subheader_val.php");
                //include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subfooter_service.php");

                break;
            case 'qty':
                include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subheader_qty.php");
                //include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subfooter_service.php");

                break;
            case 'warranty':
                include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subheader_warranty.php");
                //include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subfooter_warranty.php");

                break;
        }

        //include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subheader.php");
        //$this->DrawPositions($pdf);
        include_once("modules/EcmDocumentTemplates/templates/" . $arr[0] . "/" . $arr[1] . "/subfooter.php");
    }

    /**
     * Pdf getter.
     *
     * Retrieve pdf stream.
     */
    function getPDF($id = null, $method = 'I', $name = null, $type = null) {
        global $sugar_config;

        if ($id != null) {
            $this->retrieve($id);

            if ($this->id == '')
                return;
        }

        global $mod_strings;

        require_once('modules/EcmTexts/EcmText.php');

        if (isset($this->ecmlanguage) && $this->ecmlanguage != '') {
            $data = EcmText::LoadText(null, null, "EcmServices", $this->ecmlanguage);

            if (isset($data[0]) && isset($data[0]['data']) && isset($data[0]['data']['labels'])) {
                $data = $data[0]['data']['labels'];

                foreach ($data as $key => $value) {
                    $mod_strings[$value['label']] = $value['translation'];
                }
            }
        }

        $this->format_all_fields();

        $this->setTemplate();

        $type = $_REQUEST['type'];

        if (isset($this->template->id) && $this->template->id != '') {
            $this->template->setPDF($this->template_id);

            //echo '<pre>dump:pl:' . var_export($this->position_list, true) . PHP_EOL;
            //echo '<pre>dump:sl:' . var_export($this->services_list, true) . PHP_EOL;
            //echo '<pre>dump:il:' . var_export($this->income_list, true) . PHP_EOL;
            //echo '<pre>dump:pl:' . var_export($this->calculate($this->position_list, $this->services_list), true) . PHP_EOL;
            ///return;

            $this->DrawMainPDF($this->template->pdf, $type);

            header("Content-type: application/pdf");
            $this->template->outputPDF((($name) ? $name : $this->createPdfFileName()), $method);
        }
    }

    /**
     * Calculate.
     *
     * Calculate positions(articles) and services totals.
     *
     * @param array $position_list
     * @param array $services_list
     * @param bolean $format
     * @return array | boolean
     */
    function calculate($position_list, $services_list, $format = false) {
        //echo '<pre>' . var_export($position_list, true);
        //echo '<pre>' . var_export($services_list, true);
        //return;

        if (!is_array($position_list) || !count($position_list))
            return false;

        if (!is_array($services_list) || !count($services_list))
            return false;

        $result = array(
            'articles_total' => 0.0,
            'articles_subtotal' => 0.0,
            //
            'services_total' => 0.0,
            'services_subtotal' => 0.0,
            //
            'articles_vats' => false,
            'services_vats' => false,
            //
            'articles_draw_vat' => false,
            'services_draw_vat' => false,
            //
            'articles_draw_discount' => false,
            'services_draw_discount' => false,
        );

        $articles_vats = array();
        $services_vats = array();

        foreach ($position_list as $p) {
            if (!isset($articles_vats[$p['vat_id']]))
                $articles_vats[$p['vat_id']] = 0;

            $articles_vats[$p['vat_id']] += floatval($p['total']);

            $result['articles_subtotal'] += floatval($p['total']);

            if (!$result['articles_draw_discount'] && floatval($p['discount']) > 0)
                $result['articles_draw_discount'] = true;
        }

        foreach ($services_list as $s) {
            if (!isset($services_vats[$s['vat_id']]))
                $services_vats[$s['vat_id']] = 0;

            $services_vats[$s['vat_id']] += floatval($s['total']);

            $result['services_subtotal'] += floatval($s['total']);

            if (!$result['services_draw_discount'] && floatval($s['discount']) > 0)
                $result['services_draw_discount'] = true;
        }

        $result['articles_total'] = $result['articles_subtotal'];
        $result['services_total'] = $result['services_subtotal'];

        if (!$this->to_is_vat_free) {
            $articles_vats2 = array();
            $services_vats2 = array();

            foreach ($articles_vats as $key => $value) {
                $query = 'SELECT value FROM ecmvats WHERE id = \'' . $key . '\';';
                $res = $GLOBALS['db']->query($query);

                $r = $GLOBALS['db']->fetchByAssoc($res);
                $vva = $r['value'];

                if (!$format)
                    $articles_vats2[$key] = $value * (floatval($vva) / 100);
                else
                    $articles_vats2[$key] = format_number($value * (floatval($vva) / 100));

                $result['articles_total'] += $value * (floatval($vva) / 100);
            }

            foreach ($services_vats as $key => $value) {
                $query = 'SELECT value FROM ecmvats WHERE id = \'' . $key . '\';';
                $res = $GLOBALS['db']->query($query);

                $r = $GLOBALS['db']->fetchByAssoc($res);
                $vva = $r['value'];

                if (!$format)
                    $services_vats2[$key] = $value * (floatval($vva) / 100);
                else
                    $services_vats2[$key] = format_number($value * (floatval($vva) / 100));

                $result['services_total'] += $value * (floatval($vva) / 100);
            }

            asort($articles_vats2, SORT_NUMERIC);
            asort($services_vats2, SORT_NUMERIC);

            $result['articles_vats'] = $articles_vats2;
            $result['services_vats'] = $services_vats2;

            if (count($result['articles_vats']) > 1)
                $result['articles_draw_vat'] = true;

            if (count($result['services_vats']) > 1)
                $result['services_draw_vat'] = true;
        }

        /* */
        $discount = $this->discount;

        if (!is_float($discount))
            $discount = unformat_number($discount);

        if ($discount > 0) {
            $result['discount'] = array(
                'procent' => format_number(floatval($discount)) . '%',
                //
                'articles_value' => $result['articles_total'] * $discount / 100,
                'services_value' => $result['services_total'] * $discount / 100,
            );

            //$result['total2'] = $result['articles_total'];
            $result['articles_total'] -= $result['discount']['articles_value'];
            $result['services_total'] -= $result['discount']['services_value'];
        }

        if ($format) {
            if (@$result['discount']['articles_value'] > 0 && @$result['discount']['services_value'] > 0) {
                $result['discount']['articles_value'] = format_number($result['discount']['articles_value']);
                $result['discount']['services_value'] = format_number($result['discount']['services_value']);
//                $result['total2'] = format_number($result['total2']);
            }

            $result['articles_total'] = format_number($result['articles_total']);
            $result['services_total'] = format_number($result['services_total']);

            $result['articles_subtotal'] = format_number($result['articles_subtotal']);
            $result['services_subtotal'] = format_number($result['services_subtotal']);
        }

        //echo '<pre>' . var_export($result, true);
        //exit;

        return $result;
    }
    
    /**
     * Delete reservated items.
     */
    function deleteReservations() {
        global $db;
        
        $query = 'DELETE FROM `ecmreservations` WHERE `doc_id` = \'' . $focus->id . '\';';
        
        $result = $db->query($query);
        return $result;
    }
    
    /**
     * Unreservate reservated items.
     */
    function unreserve() {
        session_start();
        
        global $db;
        
        $query = 
        '
        UPDATE 
            `ecmreservations` AS r 
        SET 
            r.`session_id` = \''. session_id() . '\',
            r.`temp_doc_id` = r.`doc_id`, 
            r.`temp_item_id` = r.`item_id`, 
            r.`doc_id` = NULL, 
            r.`item_id` = NULL 
        WHERE 
            r.`doc_id` = \'' . $this->id . '\' 
        ;';
        
        $result = $db->query($query);
        return $result;
    }
        
    function formatPositions($position_list) {
        if (!is_array($position_list) || count($position_list) == 0)
            return false;

        global $app_list_strings;

        require_once('modules/Currencies/Currency.php');
        foreach ($position_list as $key => $value) {

            $position_list[$key]['unit_id'] = $app_list_strings['ecmproducts_unit_dom'][$value['unit_id']];

            $position_list[$key]['category_id'] = $app_list_strings['ecmproducts_category_dom'][$value['category_id']];

            //$position_list[$key]['vat_id'] = format_number($value['vat_id']).'%';

            $position_list[$key]['discount'] = format_number($value['discount']) . '%';

            if (isset($currency) && ($currency->id == $this->currency_id)) {

            } else {
                $currency = new Currency();
                $currency->retrieve($this->currency_id);
            }
            $position_list[$key]['price'] = format_number($value['price']) . ' ' . $currency->iso4217;

            $position_list[$key]['articles_total'] = format_number($value['articles_total']) . ' ' . $currency->iso4217;

            //$position_list[$key]['price'] = format_number($value['price']).' PLN';
            //$position_list[$key]['articles_total'] = format_number($value['articles_total']).' PLN';

            $this->currency_symbol = $currency->iso4217;
        }
        return $position_list;
    }

    function loadParser() {
        $this->template->mfp->clear();
        $this->template->mfp->add("EcmServices", "quote_", $this);
        $this->template->mfp->add("Users", "user_", $this->setUser());

        if ($this->setAccount() != null)
            $this->template->mfp->add("Accounts", 'account_', $this->account);

        if ($this->setContact() != null)
            $this->template->mfp->add("Contacts", 'contact_', $this->contact);

        $this->template->mfp->add("EcmDocumentTemplates", "documenttemplate_", $this->template);
    }

    function loadParserarray($name = '') {
        require_once('modules/EcmDocumentTemplates/ModuleFieldsParser/ModuleFieldsParser.php');
        $mfp = new ModuleFieldsParser();
        $mfp->clear();

        global $app_list_strings;

        $mfp->add("EcmServices", "quote_", '', $app_list_strings['moduleList']['EcmServices']);
        $mfp->add("Users", "user_", '', $app_list_strings['moduleList']['Users']);
        $mfp->add("Accounts", 'account_', '', $app_list_strings['moduleList']['Accounts']);
        $mfp->add("Contacts", 'contact_', '', $app_list_strings['moduleList']['Contacts']);
        $mfp->add("EcmDocumentTemplates", "documenttemplate_", '', $app_list_strings['moduleList']['EcmDocumentTemplates']);

        if ($name == '') {
            $mfp_arr = array(
                'header' => $mfp->getFormHTML(false, 'header'),
                'footer' => $mfp->getFormHTML(false, 'footer'),
                'ads' => $mfp->getFormHTML(false, 'ads'),
            );
        } else
            $mfp_arr = $mfp->getFormHTML(false, $name);
        return $mfp_arr;
    }

    function setAccount() {
        require_once('modules/Accounts/Account.php');
        $this->account = new Account();
        $this->account->retrieve($this->parent_id);
        return $this->account;
    }

    function setContact() {
        require_once('modules/Contacts/Contact.php');
        $us = new Contact();
        $us->retrieve($this->contact_id);
        $this->contact = $us;
        return $this->contact;
    }

    function setUser() {
        if (is_object($this->user))
            return $this->user;

        require_once('modules/Users/User.php');

        $us = new User();

        global $current_user;

        $us->retrieve(($this->assigned_user_id) ? $this->assigned_user_id : $current_user->id);

        if (isset($us->id) && $us->id != '') {
            $this->user = $us;
        }
        else
            $this->user = null;

        return $this->user;
    }

    function doNotAccepted() {
        global $current_user;
        $cq = $current_user->getPreference('confirm_quotes');
        if (isset($cq) && $cq) {
            $query = "UPDATE `ecmservices` SET `status` = 'not_accepted',`accepted` = '0' WHERE CONVERT( `id` USING utf8 ) = '" . $this->id . "' LIMIT 1 ;";
            $result = $this->db->query($query);
            if ($result) {
                $this->status = 'not_accepted';
                $this->accepted = 0;
            }
        }
    }

    function ACLAccess($view, $is_owner = 'not_set') {
        global $current_user;

        $file = 'modules/EcmGroupServices/EcmGroupService.php';
        if (file_exists($file)) {
            require_once($file);
            $cc = EcmGroupService::loadSettings(true);
        } else
            return true;

        if (is_admin($current_user)) {
            switch ($view) {
                case 'confirming':
                    return ($this->status == "s20");
                case 'send_to_confirm':
                    return ($this->status == "s10");
                case 'pdf_toolbar':
                    return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
            }
            return true;
        }

        if ($is_owner == 'not_set') {
            $is_owner = $this->isOwner($current_user->id);
        }

        //if we don't implent acls return true
        if (!$this->bean_implements('ACL'))
            return true;
        $view = strtolower($view);

        if ($cc['user_manager_role']) { //Manager
            switch ($view) {
                case 'list':
                case 'index':
                case 'listview':
                    return ACLController::checkAccess($this->module_dir, 'list', true);
                case 'edit':
                case 'save':
                case 'popupeditview':
                case 'editview':
                    return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner));
                case 'view':
                case 'detail':
                case 'detailview':
                    return ACLController::checkAccess($this->module_dir, 'view', $is_owner);
                case 'delete':
                    return ACLController::checkAccess($this->module_dir, 'delete', $is_owner);
                case 'export':
                    return ACLController::checkAccess($this->module_dir, 'export', $is_owner);
                case 'import':
                    return ACLController::checkAccess($this->module_dir, 'import', true);
                case 'send_to_confirm':
                    return ($this->status == "s10");
                case 'can_commit':
                    return true;
                case 'confirming':
                    return ($this->status == "s20");
                case 'auto_commiting':
                    return true;
                case 'pdf_toolbar':
                    return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
            }
        } else
        if ($cc['user_representative_extra_role']) { //Representative Extra
            switch ($view) {
                case 'list':
                case 'index':
                case 'listview':
                    return ACLController::checkAccess($this->module_dir, 'list', true);
                case 'edit':
                    return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40"));
                case 'save':
                case 'popupeditview':
                case 'editview':
                    return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner));
                case 'view':
                case 'detail':
                case 'detailview':
                    return ACLController::checkAccess($this->module_dir, 'view', $is_owner);
                case 'delete':
                    return (ACLController::checkAccess($this->module_dir, 'delete', $is_owner) && $this->status == "s10");
                case 'export':
                    return ACLController::checkAccess($this->module_dir, 'export', $is_owner);
                case 'import':
                    return ACLController::checkAccess($this->module_dir, 'import', true);
                case 'quote_to_service':
                case 'quote_to_invoice':
                    return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60");
                case 'send_to_confirm':
                    return ($this->status == "s10");
                case 'send_email':
                    return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
                case 'can_commit':
                    return true;
                case 'confirming':
                    return false;
                case 'auto_commiting':
                    return true;
                case 'pdf_toolbar':
                    return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
            }
        } else
        if ($cc['user_representative_role']) { //Representative
            switch ($view) {
                case 'list':
                case 'index':
                case 'listview':
                    return ACLController::checkAccess($this->module_dir, 'list', true);
                case 'edit':
                    return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40"));
                case 'save':
                case 'popupeditview':
                case 'editview':
                    return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner));
                case 'view':
                case 'detail':
                case 'detailview':
                    return ACLController::checkAccess($this->module_dir, 'view', $is_owner);
                case 'delete':
                    return (ACLController::checkAccess($this->module_dir, 'delete', $is_owner) && $this->status == "s10");
                case 'export':
                    return ACLController::checkAccess($this->module_dir, 'export', $is_owner);
                case 'import':
                    return ACLController::checkAccess($this->module_dir, 'import', true);
                case 'quote_to_service':
                case 'quote_to_invoice':
                    return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60");
                case 'send_to_confirm':
                    return ($this->status == "s10");
                case 'send_email':
                    return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
                case 'can_commit':
                    return false;
                case 'confirming':
                    return false;
                case 'auto_commiting':
                    return false;
                case 'pdf_toolbar':
                    return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
            }
        }
        //if it is not one of the above views then it should be implemented on the page level
        return true;
    }

    function getUserSatusAccess() {
        global $current_user;
        require_once('modules/EcmServices/StatusAccess.php');

        $file = 'modules/EcmGroupServices/EcmGroupService.php';
        if (file_exists($file)) {
            require_once($file);
            $cc = EcmGroupService::loadSettings(true);
        }
    }

    static function setStatus($record, $status) {
        global $app_list_strings, $mod_strings;

        $arr = array();

        require_once('modules/EcmServices/EcmService.php');
        $focus = new EcmService();

        if ($focus->ACLAccess('auto_commiting') && $status == "s20")
            $status = "s30";

        $query = "UPDATE ecmservices SET status='$status' WHERE id='$record' AND deleted='0'";
        $result = $GLOBALS['db']->query($query);

        if (!$result) {
            $arr['message'] = $mod_strings["LBL_STATUS_" . $status . "_FAIL_MESSAGE"];
        } else {
            $arr['record'] = $record;
            $arr['status'] = array('text' => $app_list_strings['ecmservices_status_dom'][$status], 'code' => $status, 'image' => EcmService::CreateImgStatus($record, $status));
            $arr['message'] = $mod_strings["LBL_STATUS_" . $status . "_SET_MESSAGE"];
            if (isset($_REQUEST['ListQuotesModule']) && $_REQUEST['ListQuotesModule'] != '' && isset($_REQUEST['ListQuotesAction']) && $_REQUEST['ListQuotesAction'] != '') {

                $m_old = $_REQUEST['module'];
                $a_old = $_REQUEST['action'];
                $_REQUEST['module'] = $_REQUEST['ListQuotesModule'];
                $_REQUEST['action'] = $_REQUEST['ListQuotesAction'];

                $focus->id = $record;
                $focus->status = $status;
                $arr['list_images'] = $focus->ListIconsView();

                $_REQUEST['module'] = $m_old;
                $_REQUEST['action'] = $a_old;
            }
        }

        if (isset($status)) {
            $file = 'modules/EcmGroupServices/EcmGroupService.php';
            $cc = array();
            if (file_exists($file)) {
                require_once($file);
                $cc = EcmGroupService::loadSettings(true);
            }

            if ($status == 's20')
                if (isset($cc['default_manager_role_id']) && $cc['default_manager_role_id'] != '')
                    foreach ($cc['default_manager_role_id'] as $key => $manager_role_id) {
                        EcmService::SetReminder($record, 'EcmServices', $arr['status']['image'] . ' ' . $arr['status']['text'], $manager_role_id);
                    }

            if (($status == 's30' || $status == 's40')) { // && !$focus->ACLAccess('auto_commiting')
                EcmService::SetReminder($record, 'EcmServices', $arr['status']['image'] . '<span style="display:inline;">&nbsp;' . $arr['status']['text'] . '</span>');
            }
            if ($status == 's10') {
                //deleting before reminders
                $query = "DELETE FROM `ecmreminders` WHERE `parent_id`='$record'";
                $GLOBALS['db']->query($query);
            }
        }
        return $arr;
    }

    static function SetReminder($parent_id, $parent_name, $status, $role_id = '') {
        $file = 'modules/EcmReminders/EcmReminder.php';

        if (file_exists($file)) {

            $name = 'EcmServices - Status Change';
            $query = "SELECT name, assigned_user_id FROM ecmservices WHERE id='$parent_id' LIMIT 1";
            $result = $GLOBALS['db']->query($query);
            if ($result) {
                $row = $GLOBALS['db']->fetchByAssoc($result);
                if ($row && isset($row['name']))
                    $name = $row['name'];
                if ($row && isset($row['assigned_user_id']) && $row['assigned_user_id'] != '')
                    $assigned_user_id = $row['assigned_user_id'];
            }

            if (!isset($assigned_user_id) || $assigned_user_id == '') {
                global $current_user;
                $assigned_user_id = $current_user->id;
            }

            //deleting before reminders
            $query = "DELETE FROM `ecmreminders` WHERE `parent_id`='$parent_id'";
            if (isset($role_id) && $role_id != '')
                $query .= " AND `role_id`='$role_id'"; else
                $query .= " AND `role_id` IS NULL";
            $GLOBALS['db']->query($query);

            require_once($file);
            $reminder = new EcmReminder();
            $reminder->assigned_user_id = $assigned_user_id;
            $reminder->name = $name;
            $reminder->reminder_time = 0;
            $reminder->parent_id = $parent_id;
            $reminder->parent_name = $parent_name;
            $reminder->role_id = $role_id;
            $reminder->status = $status;
            global $timedate;
            $reminder->date_start = $timedate->to_display_date_time(gmdate('Y-m-d H:i:s'));
            $reminder->save(FALSE);
        }
    }

}