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

require_once 'include/upload_file.php';

class EcmFkVatRegister extends SugarBean
{

    /**
     * Register name.
     *
     * @var stiring
     */
    var $table_name = "ecmfkvatregisters";

    /**
     * Object name.
     *
     * @var stiring
     */
    var $object_name = "EcmFkVatRegister";

    /**
     * Additional column fields.
     *
     * @var stiring
     */
    var $additional_column_fields = array();

    /**
     * Module directory.
     *
     * @var stiring
     */
    var $module_dir = 'EcmFkVatRegisters';

    // ~

    /**
     * Constructor.
     *
     * @return void
     */
    function EcmFkVatRegister()
    {
        parent::SugarBean();
        $this->setupCustomFields('EcmFkVatRegisters');
    }

    /**
     * Rotations updater.
     *
     * @example Na status zaksięgowany można zmienić tylko te pozycje w rejestrach, które się bilansują.
     *
     *          Jeśli jest księgowanie na koncie po stronie WN należy pole OMmm_WN, gdzie mm jest miesiącem
     *
     *          księgowania daty dat_dok (np. 05,11) zwiększyć o wartość kwota:
     *
     *          1. Konto aktywne, aktywno-pasywne i rozrachunkowe – pole SMmm_WN i następne pola aż do
     *
     *          SM12_WN zwiększyć o wartość pola kwota.
     *
     *          2. Konto pasywne – pole SMmm_MA i następne pola aż do SM12_MA zmniejszyć o wartość
     *
     *          pola kwota.
     *
     *          Zmiana następuje także na koncie syntetycznym dla danego konta analitycznego. Np. zapis na
     *
     *          koncie 401-01-02 zmienia także kwoty na koncie syntetycznym 400.
     *
     *          Jeśli jest księgowanie na koncie po stronie MA należy pole OMmm_MA, gdzie mm jest miesiącem
     *
     *          księgowania daty dat_dok (np. 05,11) zwiększyć o wartość kwota:
     *
     *          1. Konto pasywne, aktywno-pasywne i rozrachunkowe – pole SMmm_MA i następne pola aż do
     *
     *          SM12_MA zwiększyć o wartość pola kwota.
     *
     *          2. Konto aktywne – pole SMmm_WN i następne pola aż do SM12_WN zmniejszyć o wartość
     *
     *          pola kwota.
     *
     *          Zmiana następuje także na koncie syntetycznym dla danego konta analitycznego. Np. zapis na
     *
     *          koncie 401-01-02 zmienia także kwoty na koncie syntetycznym 400.
     *
     * @todo check what happens when new year arrives at EcmBankAccount::updateRotationWn/updateRotationMa concretes.
     *
     * @param array $position_list
     * @return EcmFkVatRegister
     */
    function updateRotations(array $position_list = array())
    {
        // dump(1);
        // exit;
        require_once 'modules/EcmBankAccounts/EcmBankAccount.php';

        if (true == empty($position_list)) {
            $position_list = $this->getPositionList(true);
        }

        // mysqldump -u root -p --no-data crm ecmsymbols ecmidentifiers ecmrotations ecmfkvats ecmfkvatregisters ecmfkvatregisteritems ecmfkvatkinds ecmbankaccounts ecmfkvattables ecmfkvattableitems ecmfkbooks ecmfkbookitems > fk-data.sql
        $date = DateTime::createFromFormat('Y-m-d', $this->dat_dok);

        $year = (int) $date->format('Y');
        $month = (int) $date->format('m');

        // dump($date, $year, $month);
        // exit;

        // WN accounts.
        foreach ($position_list as $key => $value) {
            // dump($value);
            // exit;

            $tmpAccount = new EcmBankAccount();
            $tmpAccount->retrieve($value['i_acc_wn']);

            // dump($tmpAccount->toArray());
            // exit;

            if (! $tmpAccount->id) {
                continue;
            }

            // type @ 1 - Bilansowe; 2 - Pozabilansowe;
            if (! $tmpAccount->type > 1) {
                continue;
            }

            $tmpAccount->updateRotationWn($year, $month, $value['i_amount_real']);

            if ($tmpAccount->analytic != '') {
                $syntheticAcc = new EcmBankAccount();
                $syntheticAcc->retrieve(array(
                    'synthetic' => $tmpAccount->synthetic,
                    'analytic' => null
                ));

                $syntheticAcc->updateRotationWn($year, $month, $value['i_amount_real']);
                // exit;
            } else {
                // dump(2);
                // exit;
            }
        }

        // MA accounts.
        foreach ($position_list as $key => $value) {
            // dump($value);
            // exit;

            $tmpAccount = new EcmBankAccount();
            $tmpAccount->retrieve($value['i_acc_ma']);

            // dump($tmpAccount->toArray());
            // exit;

            if (! $tmpAccount->id) {
                continue;
            }

            // type @ 1 - Bilansowe; 2 - Pozabilansowe;
            if (! $tmpAccount->type > 1) {
                continue;
            }

            $tmpAccount->updateRotationMa($year, $month, $value['i_amount']);

            if ($tmpAccount->analytic != '') {
                $syntheticAcc = new EcmBankAccount();
                $syntheticAcc->retrieve(array(
                    'synthetic' => $tmpAccount->synthetic,
                    'analytic' => null
                ));

                $syntheticAcc->updateRotationMa($year, $month, $value['i_amount']);
                // exit;
            } else {
                // dump(2);
                // exit;
            }
        }

        return $this;
    }

    /**
     * Deprecated! @h
     *
     * function saveBooks(array $position_list = array(), $check_notify = false)
     * {
     * // dump(1);
     * // exit;
     *
     * require_once 'modules/EcmFkBooks/EcmFkBook.php';
     *
     * if (true == empty($position_list)) {
     * $position_list = $this->getPositionList(true);
     * }
     *
     * $books = array();
     *
     * dump($position_list);
     * exit();
     *
     * foreach ($position_list as $key => &$value) {
     * // dump($value);
     * // exit;
     *
     * // continue;
     * // dump($this->toArray());
     *
     * $tmpBook = new EcmFkBook();
     *
     * $date = new DateTime();
     *
     * // BOF: Setup.
     * // $tmpBook->id = create_guid();
     * $tmpBook->date_entered = $date->format('Y-m-d');
     * // $tmpBook->date_modified = '';
     * $tmpBook->date_book = $value['i_dat_dok'];
     * $tmpBook->date_document = $date->format('Y-m-d');
     * $tmpBook->document_year = $date->format('Y');
     * // $tmpBook->modified_user_id = '';
     * $tmpBook->created_by = '1';
     * $tmpBook->description = ($this->description ? (' ' . $this->description) : '') . $value['i_name'];
     * // $tmpBook->description = ($this->description ? (PHP_EOL . $this->description) : '') . $value['i_name'];
     * $tmpBook->deleted = '0';
     * $tmpBook->book_date = $date->format('Y-m-d');
     * $tmpBook->book_name = $this->nr_dok;
     * $tmpBook->book_number = $this->nr_par;
     * // $tmpBook->book_amount = $value['i_amount'];
     * $tmpBook->book_acc_ma = $value['i_acc_ma'];
     * $tmpBook->book_acc_wn = $value['i_acc_wn'];
     * $tmpBook->book_position = $value['position'];
     * $tmpBook->book_symbol = $this->sym_dok_id;
     * // $tmpBook->book_identifier = $this->ident_k_id;
     * $tmpBook->book_identifier = $this->ident_k;
     * $tmpBook->ident_k = $this->ident_k;
     * // $tmpBook->spar_tr = '';
     * $tmpBook->miesiac = (int) $date->format('m');
     * $tmpBook->kwota_wal = $value['i_amount_curr'];
     * // $tmpBook->rezerwa = '';
     * // $tmpBook->zm_spar = '';
     * $tmpBook->kurs_wal = $value['i_kurs_wal'];
     * $tmpBook->symb_wal = $value['i_symb_wa'];
     * $tmpBook->dat_zgo = $this->dat_zgo;
     * // $tmpBook->sym_oper = '';
     * // $tmpBook->book_identifier_id = '';
     * // EOF: Setup.
     *
     * $tmpBook->ecmfkvatregisteritem_id = $value['id'];
     *
     * if (true == is_array($value['i_amount'])) {
     *
     * foreach ($value['i_amount'] as $k => $v) {
     * $tmpV = $v;
     *
     * // $tmpV['id'] = create_guid();
     * // $tmpV['sys_par'] = $v['id'];
     *
     * // unset($v['id']);
     *
     * $tmpV = array(
     * // 'id' => 'd192c409-1c4b-1ba1-40da-5243fb8058ba',
     * 'date_entered' => date("Y-m-d"),
     * // 'date_modified' => NULL,
     * // 'created_by' => 'd9c0007b-1247-5e82-31b6-4f168a01d290',
     * // 'modified_user_id' => NULL,
     * // 'ecmfkbook_id' => 'bfab0e01-4cdd-881f-803f-5243fbf15ab2',
     * // 'nr_sys' => '',
     * // 'kwota_wn' => '0.00',
     * // 'kwota_ma' => '0.00',
     * // 'sym_par' => '',
     * // 'nr_par' => '',
     * // 'poz_par' => '',
     * // 'sys_par' => '826e9d3b-8941-7b3d-90b0-51d525fcec17',
     * // 'dat_par' => '0000-00-00',
     * // 'id_par' => '',
     * // 'spar_m_wn' => '',
     * 'spar_m_ma' => '',
     * 'rezerwa' => '',
     * 'sym_dok_id' => '',
     * 'sym_dok' => '',
     * 'nr_dok' => '',
     * 'poz_dok' => '',
     * 'id_wn' => '',
     * 'id_ma' => '',
     * 'dat_wn' => '',
     * 'dat_ma' => '',
     * 'dat_1wez' => '',
     * 'dat_2wez' => '',
     * 'dat_notao' => '',
     * 'pom_rok' => ''
     * );
     *
     * exit();
     *
     * $tmpBook->position_list[] = $tmpV;
     * }
     * } else {
     * $tmpBook->book_amount = $value['i_amount'];
     * }
     *
     * dump($tmpBook->toArray(), $tmpBook->position_list);
     * exit();
     *
     * $bookId = $tmpBook->save(true);
     * $books[] = $bookId;
     *
     * dump($bookId);
     * exit();
     *
     * // $value['ecmfkbook_id'] = $bookId;
     * }
     *
     * dump($books);
     * exit();
     *
     * // $this->savePositions($this->id, $positions);
     * // $this->save($position_list);
     *
     * return $check_notify ? $books : $this;
     * }
     */

    /**
     * Save.
     *
     * $withBooks flag is passed to savePositions
     * see description there.
     *
     * @param string $check_notify
     * @param string $withBooks
     * @return unknown
     */
    function save($check_notify = false, $withBooks = true)
    {
        if (! $this->nr_sys) {
            $this->nr_sys = $this->generateNrSys();
        }

        // dump($this->nr_sys);
        // exit;

        $date = new DateTime($this->dat_dok);
        $this->year = $date->format('Y');
        $this->month = $date->format('m');

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

        $this->savePositions($return_id, null, $withBooks);

        if ($this->status == '2') {
            $this->updateRotations();
        }

        // dump($this->toArray());
        // exit;

        return $return_id;
    }

    /**
     * Save positions.
     *
     * when withbooks flag is on, perform duplication of register item to book.
     *
     * this duplication is mostly done by merging register with its position.
     *
     * when register type is equal to 1, registers positions are handled differently.
     * these registers have subpositions that are transfered to book items.
     *
     *
     * @param string $id
     * @param string $position_list
     * @param string $withBooks
     * @return number
     */
    function savePositions($id = null, $position_list = null, $withBooks = true)
    {
        // dump($this->generateNrSys());
        // exit();
        global $current_user, $timedate;

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

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

        if (count($position_list) > 0) {
            $this->deleteAssignedPositions($id, $withBooks);
        }

        $position = 0;

        // dump('position_list', $position_list);
        // exit;

        for ($i = 0, $ic = count($position_list); $i < $ic; $i ++) {
            $p = $position_list[$i];
            $arr = array();

            // dump('focus', $this->toArray());
            // dump('Posted', $p);
            // exit;

            // ~

            $date = new DateTime($this->dat_dok);

            $vatRegisterItem = array(
                // 'id' => create_guid(),
                // 'ecmfkbook_id' => '',
                'date_entered' => $date->format('Y-m-d'),
                // 'date_modified' => '',
                // 'modified_user_id' => '',
                'created_by' => 'd9c0007b-1247-5e82-31b6-4f168a01d290',
                'deleted' => '0',
                'ecmfkvatregister_id' => $this->id,
                'nr_sys' => $date->getTimestamp(),
                'code' => $p['i_code'],
                'ecmfkvattable_id' => $p['ecmfkvattable_id'],
                'name' => $p['i_name'],
                'amounts' => $p['i_amount'],
                'amount' => $p['i_amount_real'],
                'amount_wn' => $p['i_amount_wn'],
                'amount_ma' => $p['i_amount_ma'],
                'acc_wn' => $p['i_acc_wn'],
                'acc_ma' => $p['i_acc_ma'],
                'dat_dok' => $date->format('Y-m-d'),
                'sp_zap' => $p['i_sp_zap'],
                'il_dni' => $p['i_il_dni'],
                'dat_zap' => $p['i_dat_zap'],
                'kwota_wa' => $p['i_kwota_wa'],
                'symb_wa' => $p['i_symb_wa'],
                'kurs_wal' => $p['i_kurs_wal'],
                'position' => $i + 1,
                'symbol' => $this->sym_dok_id, // $p['sym_dok'], // ?
                'nr_dok' => $this->nr_dok, // $p['nr_dok'],
                'book_number' => $p['book_number'], // nr sys
                'description' => $p['i_description'],
                'sys_par' => $p['sys_par']
            );

            // $vatRegisterItemCustom = $vatRegisterItem['custom'];
            // unset($vatRegisterItem['custom']);
            // dump($vatRegisterItemCustom);

            // dump($vatRegisterItem);
            // exit;

            $vatRegisterItem['id'] = create_guid();

            if (true == is_array($amountArr = $vatRegisterItem['amounts'])) {
                $positions = array();

                foreach ($amountArr as $aKey => $aValue) {
                    $tmpVatRegisterItem = $vatRegisterItem;
                    $tmpVatRegisterItem['id'] = create_guid();

                    // hax
                    // $tmpVatRegisterItem['sys_par'] = $aValue['sys_par'];
                    $tmpVatRegisterItem['sys_par'] = $aValue['book_number'];

                    // $tmpVatRegisterItem['type'] = $aValue['type'];
                    // $tmpVatRegisterItem['symbol'] = $aValue['symbol'];
                    // $tmpVatRegisterItem['book_number'] = $aValue['book_number'];
                    // $tmpVatRegisterItem['amount'] = $aValue['book_amount'];
                    $tmpVatRegisterItem['book_amount'] = $aValue['book_amount'];

                    // $tmpVatRegisterItem['amount_wn'] = null;
                    // $tmpVatRegisterItem['amount_ma'] = null;

                    $tmpVatRegisterItem['book_number'] = null;
                    $tmpVatRegisterItem['amounts'] = null;

                    // dump('Parsed ' . $aKey, $tmpVatRegisterItem);
                    $positions[] = $tmpVatRegisterItem;
                }

                $vatRegisterItem['amounts'] = null;

                $arr[] = array(
                    'focus' => $vatRegisterItem,
                    'positions' => $positions
                );
            } else {
                $vatRegisterItem['amount'] = $vatRegisterItem['amounts'];
                $vatRegisterItem['amounts'] = null;

                // dump('Parsed', $vatRegisterItem);
                $arr[] = array(
                    'focus' => $vatRegisterItem,
                    'positions' => null
                );
            }

            // dump('Parsed', $arr);
            // dump('With books', $withBooks);
            // continue;
            // exit();

            if (true == $withBooks) {
                // dump ('arr', $arr );
                // exit;

                $n = 1;

                foreach ($arr as $k => &$v) {
                    if ($v['focus']['book_number'] == '') {
                        $n ++;
                    }

                    // dump('kv', $k, $v, $n);
                    // continue;
                    // exit();

                    $focus = $v['focus'];
                    $positions = @$v['positions'];

                    // dump('Focus', $focus);
                    // dump('type', $this->type);
                    // dump('Positions', $positions);
                    // dump($this->toArray());
                    // exit;

                    $tmpBook = new EcmFkBook();

                    // BOF: Setup.
                    // $tmpBook->id = create_guid();
                    $tmpBook->date_entered = $date->format('Y-m-d');
                    // $tmpBook->date_modified = '';
                    $tmpBook->date_book = $date->format('Y-m-d');
                    $tmpBook->date_document = $date->format('Y-m-d');
                    $tmpBook->document_year = $date->format('Y');
                    // $tmpBook->modified_user_id = '';
                    $tmpBook->created_by = '1';

                    if ($this->type == '1') {
                        $tmpBook->description = $this->description . (($description = $focus['description']) ? (PHP_EOL . $description) : '');
                    } else {
                        $tmpBook->description = $this->description . (($name = $focus['name']) ? (PHP_EOL . $name) : '');
                    }

                    $tmpBook->deleted = $focus['deleted'];
                    $tmpBook->book_date = $date->format('Y-m-d');
                    $tmpBook->book_name = $focus['nr_dok'];
                    $tmpBook->book_number = $focus['book_number'];

                    if ($this->type == '1') {
                        if($this->amount) {
                            $tmpBook->book_amount = $focus['amount'];
                        } else {
                            if ($focus['amount_ma']) {
                                $tmpBook->book_amount = $focus['amount_ma'];
                            } else {
                                $tmpBook->book_amount = $focus['amount_wn'];
                            }
                        }
                    } else {
                        $tmpBook->book_amount = $focus['amount'];
                    }

                    $tmpBook->book_acc_ma = $focus['acc_ma'];
                    $tmpBook->book_acc_wn = $focus['acc_wn'];
                    $tmpBook->book_position = $focus['position'];
                    $tmpBook->book_symbol = $focus['symbol'];
                    $tmpBook->book_identifier = $this->ident_k;
                    // $tmpBook->ident_k = $this->ident_k;
                    $tmpBook->spar_tr = $this->spar_tr;
                    $tmpBook->miesiac = $date->format('m');
                    $tmpBook->kwota_wal = $focus['kwota_wa'];
                    $tmpBook->rezerwa = $this->reserve;
                    // $tmpBook->zm_spar = $focus['zm_spar'];
                    $tmpBook->kurs_wal = $focus['kurs_wal'];
                    $tmpBook->symb_wal = $focus['symb_wa'];
                    $tmpBook->dat_zgo = $this->dat_zgo;
                    $tmpBook->sym_oper = $this->sym_oper;
                    $tmpBook->book_identifier_id = $this->ident_k_id;
                    $tmpBook->status = $this->status;
                    $tmpBook->ecmfkvatregisteritem_id = $focus['id'];
                    $tmpBook->ecmfkvatregister_id = $id;
                    // EOF: Setup.

//                     dump($this->toArray(), $tmpBook->toArray());
//                     exit;

                    if ($positions) {
                        $bookPositions = array();

                        foreach ($positions as $pppk => $pppv) {

                            // dump('pppv', $pppv);
                            // exit;

                            $bp = array(
                                // 'i_id' => '',
                                'i_date_entered' => $pppv['date_entered'],
                                // 'i_date_modified' => $pppv[''],
                                'i_created_by' => 'i_1',
                                // 'i_modified_user_id' => $pppv[''],
                                // 'i_ecmfkbook_id' => $pppv[''],
                                'i_nr_sys' => $date->getTimestamp(),
                                // 'i_kwota_wn' => $pppv['amount'],
                                // 'i_kwota_ma' => $pppv['amount'],
                                'i_sym_par' => $pppv['sym_par'],
                                'i_nr_par' => $pppv['nr_par'],
                                'i_poz_par' => $pppv['poz_par'],
                                'i_sys_par' => $pppv['sys_par'],
                                'i_dat_par' => $pppv['dat_par'],
                                'i_id_par' => $pppv['id_par'],
                                // 'i_spar_m_wn' => $pppv['spar_m_wn'],
                                // 'i_spar_m_ma' => $pppv['spar_m_ma'],
                                'i_rezerwa' => $pppv['rezerwa'],
                                'i_sym_dok_id' => $pppv['sym_dok_id'],
                                'i_sym_dok' => $pppv['sym_dok'],
                                'i_nr_dok' => $pppv['nr_dok'],
                                'i_poz_dok' => $pppv['poz_dok'],
                                'i_id_wn' => $pppv['id_wn'],
                                'i_id_ma' => $pppv['id_ma'],
                                'i_dat_wn' => $pppv['dat_wn'],
                                'i_dat_ma' => $pppv['dat_ma'],
                                'i_dat_1wez' => $pppv['dat_1wez'],
                                'i_dat_2wez' => $pppv['dat_2wez'],
                                'i_dat_notao' => $pppv['dat_notao'],
                                'i_pom_rok' => $pppv['pom_rok']
                            );

                            // dump('focus', $focus);

                            /*
                             *
                             */
                            if ($focus['amount_wn']) {
                                $bp['i_spar_m_wn'] = '1';
                                $bp['i_kwota_wn'] = $pppv['book_amount'];
                            } else {
                                $bp['i_spar_m_wn'] = '';
                                $bp['i_kwota_wn'] = 0;
                            }

                            if ($focus['amount_ma']) {
                                $bp['i_spar_m_ma'] = '1';
                                $bp['i_kwota_ma'] = $pppv['book_amount'];
                            } else {
                                $bp['i_spar_m_ma'] = '';
                                $bp['i_kwota_ma'] = 0;
                            }

                            // $pppv['kwota_wn'] = $pppv['i_amount_wn'];
                            // $pppv['kwota_ma'] = $pppv['i_amount_ma'];

                            // dump('bp', $bp);
                            // exit;

                            $bookPositions[] = $bp;
                        }

                        $tmpBook->position_list = $bookPositions;
                    } else {
                        // ?
                    }

                    // dump('add book', $tmpBook->toArray());
                    // dump('add book positions', $tmpBook->position_list);
                    // exit;

                    // $result = $tmpBook->save(true, $n);
                    $result = $tmpBook->save(true);
                    // dump('added book', $tmpBook->toArray());

                    // dump('Result', $result);
                    // exit;

                    $v['focus']['ecmfkbook_id'] = $result;
                    $v['focus']['book_number'] = $tmpBook->book_number;
                }
            }

            // dump('Parsed after books', $arr);
            // exit();

            foreach ($arr as $ak => $av) {
                $focus = $av['focus'];
                $positions = $av['positions'];

                // dump($focus);
                // dump($positions);
                // exit;
                // continue;

                if ($positions) {
                    foreach ($positions as $pk => $pv) {
                        // dump('add', $pv);
                        $pv['ecmfkbook_id'] = $focus['ecmfkbook_id'];
                        $pv = array_filter($pv, 'strlen');

                        // dump($pv);
                        // exit;
                        // unset($pv['sys_par']);

                        $q = $this->constructInsertQuery($pv);

                        // dump('1', $q);
                        // exit;

                        $result = $this->db->query($q);
                        $position ++;
                    }
                } else {
                    // unset($focus['sys_par']);

                    $focus = array_filter($focus, 'strlen');

                    // dump('add', $focus);
                    // exit;

                    $q = $this->constructInsertQuery($focus);
                    // dump($q);
                    // exit;

                    $result = $this->db->query($q);
                    $position ++;
                }
            }
        }

        // exit();

        return $position;
    }

    /**
     * System number generator.
     *
     * just iterate
     *
     * @return integer
     */
    function generateNrSys()
    {
        $database = $this->db;

        // ~

        $field = 'nr_sys';
        $query = 'select `t`.`' . $field . '` as `number` from `' . strtolower($this->object_name) . 's`  as `t` where `t`.`' . $field . '` is not null order by `t`.`' . $field . '` desc limit 0, 1;';

        dump($query);

        // ~

        $result = $database->query($query);
        $results = $database->fetchByAssoc($result);

        // Increment and output new number.
        $number = (int) $results['number'];
        $number ++;

        return $number;
    }

    /**
     * Insert query builder.
     *
     * @param unknown $data
     * @param string $table
     * @return string
     */
    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;
    }

    function deleteAssignedPositions($withBooks = true)
    {
        if (isset($this->id) && $this->id != '') {

            $r = false;

            if (true == $withBooks) {
                $delBooksQuery = '
				delete b from ecmfkbooks as b

					join ecmfkvatregisteritems as vri on b.id = vri.ecmfkbook_id
					join ecmfkvatregisters as vr on vr.id = vri.ecmfkvatregister_id

				where vr.id = \'' . $this->id . '\';';

                // dump($delBooksQuery);
                // exit;

                $ddr = $this->db->query($delBooksQuery);

                // dump($delBooksQuery, $dr);

                $r &= $ddr;
            }

            // $query = "DELETE FROM `".strtolower($this->object_name)."itemsparams` WHERE `".strtolower($this->object_name)."_id`='".$this->id."'";
            // $r = $this->db->query($query);
            $dquery = "DELETE FROM `" . strtolower($this->object_name) . "items` WHERE `" . strtolower($this->object_name) . "_id`='" . $this->id . "'";
            // echo $query;exit;
            $dr = $this->db->query($dquery);

            $r &= $dr;

            if ($r) {
                return true;
            }
        }

        return false;
    }

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

        // echo $this->template->getTemplateFile('subheader_' . $type . '.php');
        // exit;
        // dump(get_class($pdf));exit;
        // $pdf->SetAutoPageBreak(false);
        $pdf->SetAutoPageBreak(true, $this->bMargin + $this->tMarign + 25);

        switch (strtolower($type)) {
            default:
                include ($this->template->getTemplateFile('subheader_d.php'));
                include ($this->template->getTemplateFile('subfooter_d.php'));
                break;

            case 'ac':
            case 'r':
            case 'd':
            case 'pk1':
            case 'pk2':
            case 'pk3':
            case 's_symbol1':
            case 's_symbol2':
            case 's_identifier1':
            case 's_identifier2':
                include ($this->template->getTemplateFile('subheader_' . $type . '.php'));
                include ($this->template->getTemplateFile('subfooter_' . $type . '.php'));

                break;
        }

        return;
    }

    /**
     * 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');

        // echo '<pre>' . var_export($this->ecmlanguage, true) . '</pre>';exit;
        // 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();

        // dump(__LINE__);
        // exit;

        $this->setTemplate();

        $type = $type ?  : @$_REQUEST['type'];

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

        switch (strtolower($type)) {
            default:
            case 'ac':
            case 'd':
                $this->template->setPDF($this->template_id, array(
                    'L'
                ));
                break;
            case 'r':
            case 'pk1':
            case 'pk2':
            case 'pk3':
                $this->template->setPDF($this->template_id, array(
                    'P'
                ));
                break;
        }

        // dump(__LINE__);
        // exit;
        // dump($this->template);
        // exit;
        // $this->template->pdf->SetAutoPageBreak(true, 40);

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

        $this->template->outputPDF(1, $method);
        // }
    }

    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_id = "ef0c4dea-ddf3-de51-9d08-512257d4b675";
        // $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;

            // dump($this->template);
            // exit;

        return $this->template;
    }

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

    function is_authenticated()
    {
        return $this->authenticated;
    }

    function fill_in_additional_list_fields()
    {
        $this->fill_in_additional_detail_fields();
    }

    function fill_in_additional_detail_fields()
    {
        // $vatYear = DateTime::createFromFormat('Y-m-d', $this->date_document);
        // $this->vat_year = $vatYear ? $bookYear->format('Y') : false;
        goto jump;

        global $theme;
        global $current_language;
        global $timedate;
        global $locale;

        parent::fill_in_additional_detail_fields();

        $mod_strings = return_module_language($current_language, 'EcmFkVatRegisters');

        $query = "SELECT filename,revision,file_ext FROM ecmfkvatregister_revisions WHERE id='$this->document_revision_id'";

        $result = $this->db->query($query);
        $row = $this->db->fetchByAssoc($result);

        // popuplate filename
        if (isset($row['filename']))
            $this->filename = $row['filename'];
            // $this->latest_revision = $row['revision'];
        if (isset($row['revision']))
            $this->revision = $row['revision'];

            // populate the file url.
            // image is selected based on the extension name <ext>_icon_inline, extension is stored in ecmfkvatregister_revisions.
            // if file is not found then default image file will be used.
        global $img_name;
        global $img_name_bare;
        if (! empty($row['file_ext'])) {
            $img_name = SugarThemeRegistry::current()->getImageURL(strtolower($row['file_ext']) . "_image_inline.gif");
            $img_name_bare = strtolower($row['file_ext']) . "_image_inline";
        }

        // set default file name.
        if (! empty($img_name) && file_exists($img_name)) {
            $img_name = $img_name_bare;
        } else {
            $img_name = "def_image_inline"; // todo change the default image.
        }
        if ($this->ACLAccess('DetailView')) {
            $this->file_url = "<a href='index.php?entryPoint=download&id=" . basename(UploadFile::get_url($this->filename, $this->ecmfkvatregister_revision_id)) . "&type=EcmFkVatRegisters' target='_blank'>" . SugarThemeRegistry::current()->getImage($img_name, 'alt="' . $mod_strings['LBL_LIST_VIEW_DOCUMENT'] . '"  border="0"') . "</a>";
            $this->file_url_noimage = basename(UploadFile::get_url($this->filename, $this->ecmfkvatregister_revision_id));
        } else {
            $this->file_url = "";
            $this->file_url_noimage = "";
        }

        // get last_rev_by user name.
        $query = "SELECT first_name,last_name, ecmfkvatregister_revisions.date_entered as rev_date FROM users, document_revisions WHERE users.id = document_revisions.created_by and document_revisions.id = '$this->document_revision_id'";
        $result = $this->db->query($query, true, "Eror fetching user name: ");
        $row = $this->db->fetchByAssoc($result);
        if (! empty($row)) {
            $this->last_rev_created_name = $locale->getLocaleFormattedName($row['first_name'], $row['last_name']);

            $this->last_rev_create_date = $timedate->to_display_date_time($row['rev_date']);
        }

        global $app_list_strings;
        if (! empty($this->status_id)) {
            // _pp($this->status_id);
            $this->status = $app_list_strings['ecmfkvatregister_status_dom'][$this->status_id];
        }
        $this->related_doc_name = EcmFkVatRegister::get_ecmfkvatregister_name($this->related_doc_id);
        $this->related_doc_rev_number = EcmFkVatRegisterRevision::get_ecmfkvatregister_revision_name($this->related_doc_rev_id);
        $this->save_file = basename($this->file_url_noimage);

        jump:
    }

    function generateIdent($ident)
    {
        global $db;

        $number = '';

        $like = '%';

        /* BOF: Ident query. */
        $identQ = 'select i.type, i.filter, i.regex from ecmidentifiers as i where i.id = \'' . $ident . '\' limit 0, 1';

        $identResult = $db->query($identQ);
        $identResults = $db->fetchByAssoc($identResult);

        // dump($identQ, $identResults);
        // exit;
        /* EOF: Ident query. */

        /* BOF: Counting query. */
        list ($iType, $iFilter, $iRegex) = array_values($identResults);
        $regex = getIdentNumber(false, $iType, $iFilter, $iRegex);

        // dump($regex);
        // exit;

        $countQ = '
            select
                  count(*) as count
                #, i.type
                #, i.filter
                #, i.regex
            from
                ecmfkvatregisters  as r
            join ecmidentifiers as i on i.id = r.ident_k_id
            where
            #    i.id = \'' . $ident . '\'
            #and
                r.ident_k regexp \'' . $regex . '\'
            #order by
            #    r.dat_dok desc
            ;
        ';
        /* EOF: Counting query. */

        // dump($countQ);
        // exit;

        $countResult = $db->query($countQ);
        $countResults = $db->fetchByAssoc($countResult);

        // dump($result, $results);
        // exit;
        /* EOF: Counting query. */

        if ($countResult->num_rows > 0) {
            // dump($c, $iType, $iFilter, $iRegex);
            // exit;
            $count = $countResults['count'];
            return getIdentNumber($count + 1, $iType, $iFilter, $iRegex);
        }

        return '';
    }

    function generateNumber($type)
    {
        global $db;

        $number = '';

        $like = '%';

        switch (intval($type)) {
            default:
            case 2:
                break;
            case 1:
                $like .= '/' . date('m/Y');
                break;
            case 0:
                $like .= '/' . date('Y');
                break;
        }

        $q = '
            select
                count(*) as c

            from
                ecmfkvatregisters  as r

            #join ecmsymbols as s on s.id = r.sym_doc_id

            where
            #    s.type = \'' . $type . '\'
            #and
                r.nr_dok like \'' . $like . '\'

            order by
                r.dat_dok desc
            ;
        ';

        // dump($q);
        // exit;

        $result = $db->query($q);
        $results = $db->fetchByAssoc($result);

        if ($result->num_rows > 0) {
            switch (intval($type)) {
                default:
                case 2:
                    break;
                case 1:
                    return ($results['c'] + 1) . '/' . date('m/Y');
                    break;
                case 0:
                    return ($results['c'] + 1) . '/' . date('Y');
                    break;
            }
        }

        return '';
    }

    function list_view_parse_additional_sections(& $list_form, $xTemplateSection)
    {
        return $list_form;
    }

    function create_export_query(&$order_by, &$where, $relate_link_join = '')
    {
        $custom_join = $this->custom_fields->getJOIN(true, true, $where);
        if ($custom_join)
            $custom_join['join'] .= $relate_link_join;
        $query = "SELECT
						ecmfkvatregisters.*";
        if ($custom_join) {
            $query .= $custom_join['select'];
        }
        $query .= " FROM ecmfkvatregisters ";
        if ($custom_join) {
            $query .= $custom_join['join'];
        }

        $where_auto = " ecmfkvatregisters.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 ecmfkvatregisters.document_name";

        return $query;
    }

    /**
     * getter method for ecmbanksymbolount record.
     */
    function get_symbol_array($id, array $select = array())
    {
        global $db;

        array_walk($select, function (&$value, $key)
        {
            $value = 's.`' . $value . '`';
        });

        $selectStatement = implode(', ', $select);

        $q = 'SELECT ' . (strlen($selectStatement) ? $selectStatement : 's.*') . ' FROM ecmsymbols AS s WHERE id = \'' . $id . '\' LIMIT 1;';

        $r = $db->query($q);
        $rr = $db->FetchByAssoc($r);

        if ($rr) {
            return $rr;
        }

        return false;
    }

    /**
     * Concentrate get_symbol_array method.
     */
    function get_symbol_symbol($id)
    {
        static $symbols = array();
        return $symbols[$id] ?  : ($symbols[$id] = end($this->get_symbol_array($id, array(
            'symbol'
        ))));
    }

    /**
     * getter method for ecmbankaccount record.
     */
    function get_acc_array($id, array $select = array())
    {
        global $db;

        array_walk($select, function (&$value, $key)
        {
            $value = 'ba.`' . $value . '`';
        });

        $selectStatement = implode(', ', $select);

        $q = 'SELECT ' . (strlen($selectStatement) ? $selectStatement : 'ba.*') . ' FROM ecmbankaccounts AS ba WHERE id = \'' . $id . '\' LIMIT 1;';

        $r = $db->query($q);
        $rr = $db->FetchByAssoc($r);

        if ($rr) {
            return $rr;
        }

        return false;
    }

    /**
     * Concentrate get_acc_array method.
     */
    function get_acc_code($id)
    {
        static $codes = array();
        return $codes[$id] ?  : ($codes[$id] = end($this->get_acc_array($id, array(
            'code'
        ))));
    }

    // ~
    function get_user_acc_array($id, $type, array $select = array())
    {
        global $db;

        array_walk($select, function (&$value, $key)
        {
            $value = 'ba.`' . $value . '`';
        });

        $selectStatement = implode(', ', $select);

        $q = 'SELECT ' . (strlen($selectStatement) ? $selectStatement : 'ba.*') . ' FROM accounts AS a JOIN ecmbankaccounts AS ba ON ba.id = ';

        switch (strtolower($type)) {
            default:
                break;
            case '0':
            case 'ogólny':
                break;
            case '1':
            case 'płatniczy':
                break;
            case '2':
            case 'sprzedaży':
                $q .= 'a.recipient_account';
                break;
            case '3':
            case 'zakupu':
                $q .= 'a.supplier_account';
                break;
        }

        $q .= ' WHERE a.id = \'' . $id . '\' LIMIT 1;';

        // dump($id, $type, strtolower($type), $select);
        // dump($q);
        // exit;

        $r = $db->query($q);
        $rr = $db->FetchByAssoc($r);

        if ($rr) {
            return $rr;
        }

        return false;
    }

    function get_user_acc_code($id, $type)
    {
        static $codes = array();
        $key = $id . '_' . $type;

        return $codes[$key] ?  : ($codes[$key] = end($this->get_user_acc_array($id, $type, array(
            'code'
        ))));
    }

    // ~
    function get_list_view_data()
    {
        $this->fill_in_additional_detail_fields();

        $ecmfkvatregister_fields = $this->get_list_view_array();

        // dump($ecmfkvatregister_fields);
        // exit;

        // $vatYear = DateTime::createFromFormat('d.m.Y', $this->date_document);
        // $ecmfkvatregister_fields['YEAR'] = $vatYear ? $bookYear->format('Y') : false;

        $ecmfkvatregister_fields['ACC'] = $this->get_user_acc_code($ecmfkvatregister_fields['ACC'], $ecmfkvatregister_fields['TYPE']) ?  : '000';
        // $ecmfkvatregister_fields['ACC'] = $this->get_acc_code($ecmfkvatregister_fields['ACC']) ? : '000';
        $ecmfkvatregister_fields['SYM_DOK_ID'] = $this->get_symbol_symbol($ecmfkvatregister_fields['SYM_DOK_ID']) ?  : '-';

        // $ecmfkvatregister_fields['IDENTIFIER'] = $ecmfkvatregister_fields['IDENTIFIER'] ? : '-';

        // dump($ecmfkvatregister_fields);
        // exit;

        // $ecmfkvatregister_fields['ACC_MA_CODE'] = '';
        // $ecmfkvatregister_fields['ACC_MA_CODE'] = '';
        // echo '<pre>' . var_export($this->field_defs, true) . '</pre>';
        // echo '<pre>' . var_export($ecmfkvatregister_fields, true) . '</pre>';
        // exit;

        return $ecmfkvatregister_fields;
    }

    function mark_drelationships_deleted($id)
    {
        // do nothing, this call is here to avoid default delete processing since
        // delete.php handles deletion of ecmfkvatregister revisions.
    }

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

        return false;
    }

    // static function.
    function get_ecmfkvatregister_name($doc_id)
    {
        if (empty($doc_id))
            return null;

        $db = DBManagerFactory::getInstance();
        $query = "select ecmfkvatregister_name from documents where id='$doc_id'";
        $result = $db->query($query);
        if (! empty($result)) {
            $row = $db->fetchByAssoc($result);
            if (! empty($row)) {
                return $row['ecmfkvatregister_name'];
            }
        }
        return null;
    }

    function getPosition($position, $stockOperations = false)
    {
        static $vatkind, $regAccount;

        if (! $reg) {
            $q = 'select';
        }

        if (! is_array($position))
            return '';

        $return_array = array();

        // dump($position);
        // exit;

        $return_array['id'] = $position['id'];
        $return_array['ecmfkvattable_id'] = $position['ecmfkvattable_id'];
        $return_array['i_acc_ma'] = $position['acc_ma'];
        $return_array['i_acc_ma_code'] = $position['acc_ma_code'];
        $return_array['i_acc_ma_name'] = $position['acc_ma_name'];
        $return_array['i_acc_ma_type'] = $position['acc_ma_type'];
        $return_array['i_acc_ma_kind'] = $position['acc_ma_kind'];
        $return_array['i_acc_wn'] = $position['acc_wn'];
        $return_array['i_acc_wn_code'] = $position['acc_wn_code'];
        $return_array['i_acc_wn_name'] = $position['acc_wn_name'];
        $return_array['i_acc_wn_type'] = $position['acc_wn_type'];
        $return_array['i_acc_wn_kind'] = $position['acc_wn_kind'];
        $return_array['i_account_acc_ma'] = $position['account_acc_ma'];
        $return_array['i_account_acc_wn'] = $position['account_acc_wn'];
        $return_array['i_amount'] = $position['amount'];
        $return_array['i_amount_real'] = $position['amount'];
        $return_array['i_code'] = $position['code'];
        $return_array['i_dat_dok'] = $position['dat_dok'];
        $return_array['i_dat_zap'] = $position['dat_zap'];
        $return_array['i_il_dni'] = $position['il_dni'];
        $return_array['i_kurs_wal'] = $position['kurs_wal'];
        $return_array['i_name'] = $position['name'];
        $return_array['i_sp_zap'] = $position['sp_zap'];
        $return_array['i_symb_wa'] = $position['symb_wa'];
        // 02-09-13 mh
        $return_array['kwota_wa'] = $position['kwota_wa'];
        // 23-09-13
        $return_array['nr_dok'] = $position['nr_dok'];
        $return_array['symbol'] = $position['symbol'];
        $return_array['position'] = $position['position'];
        $return_array['ecmfkbook_id'] = $position['ecmfkbook_id'];
        $return_array['i_position'] = $position['position'];

        $return_array['book_name'] = $position['book_name'];
        $return_array['book_number'] = $position['book_number'];
        $return_array['book_amount'] = $position['book_amount'];

        $return_array['i_amount_wn'] = $position['amount_wn'];
        $return_array['i_amount_ma'] = $position['amount_ma'];

        $return_array['i_description'] = $position['description'];

        $return_array['sys_par'] = $position['sys_par'];

        $return_array['book_symbol'] = $position['book_symbol'];
        $return_array['book_name'] = $position['book_name'];
        $return_array['book_number'] = $position['book_number'];
        $return_array['b_book_number'] = $position['b_book_number'];

        // $return_array['type'] = 'wn';

        if (! $vatkind) {
            // require_once '/modules/EcmFkVatKinds/EcmFkVatKind.php';

            $vatKind = new EcmFkVatKind();
            $vatKind->retrieve($this->ecmfkvatkind_id);
        }

        if (! $regAccount) {
            // require_once '/modules/EcmBankAccounts/EcmBankAccount.php';

            $regAccount = new EcmBankAccount();
            $regAccount->retrieve($vatKind->acc);
        }

        // dump($regAccount->toArray());
        // dump($position);
        // exit();

        /*
         * if ($position['type_wn'] == '1' && $position['type_ma'] == '1') { $return_array['type'] = 'b'; } elseif ($position['type_wn'] == '1') { $return_array['type'] = 'ma'; // $return_array['type'] = 'wn'; } elseif ($position['type_ma'] == '1') { $return_array['type'] = 'wn'; // $return_array['type'] = 'ma'; } else { // }
         */

        // dump($position, $return_array);
        // exit;

        return $return_array;
    }

    function getPositionList($array = false)
    {
        if (isset($this->id) && $this->id != '') {
            $query = '
                SELECT

                  vri.*

				, IF(b.book_acc_wn = acc_wn.id, 1, 0) as type_wn
				, IF(b.book_acc_ma = acc_ma.id, 1, 0) as type_ma

                , vt.id as ecmfkvattable_id
                , acc_wn.`code` AS acc_wn_code
                , acc_ma.`code` AS acc_ma_code
                , acc_wn.`name` AS acc_wn_name
                , acc_ma.`name` AS acc_ma_name
                , acc_wn.`type` AS acc_wn_type
                , acc_ma.`type` AS acc_ma_type
                , acc_wn.`kind` AS acc_wn_kind
                , acc_ma.`kind` AS acc_ma_kind
                , vri.name

                #  vt.ecmfkvattable_id
                #, vri.acc_ma
                #, acc_ma.code as i_acc_ma_code
                #, acc_ma.name as i_acc_ma_name
                #, acc_ma.type as i_acc_ma_type
                #, vri.i_acc_wn
                #, acc_wn.code as i_acc_wn_code
                #, acc_wn.name as i_acc_wn_name
                #, acc_wn.type as i_acc_wn_type
                #, vt.account_acc_ma as account_acc_ma
                #, vt.account_acc_wn as account_acc_wn
                #, vri.amount
                #, vt.code
                #, vri.dat_dok
                #, vri.il_dni
                #, vri.kurs_wal
                #, vri.name
                #, vri.sp_zap
                #, vri.symb_wa
                , vri.kwota_wa
                , vri.nr_dok
                , vri.symbol
                , vri.position
                , vri.book_number
                , vri.book_amount

                #, b.book_amount

                , vri.sys_par
                , bs.symbol as book_symbol
                , b.book_name
                , b.book_number as b_book_number
                #, b.book_amount

                FROM `ecmfkvatregisteritems` AS vri

                LEFT JOIN `ecmbankaccounts` AS acc_wn
                ON acc_wn.`id` = vri.`acc_wn`

                LEFT JOIN `ecmbankaccounts` AS acc_ma
                ON acc_ma.`id` = vri.`acc_ma`

				LEFT JOIN `ecmfkvattables` AS vt
				ON vt.`id` = vri.`ecmfkvattable_id`

                LEFT JOIN ecmfkbooks as b
                on b.book_number = vri.sys_par

                LEFT JOIN ecmsymbols as bs
                on bs.id = b.book_symbol

                WHERE
                vri.`ecmfkvatregister_id` = \'' . $this->id . '\'

                ORDER BY
                vri.`code` asc
                ;
            ';

            // dump($query);
            // dump($this->type);
            // exit;

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

            // dump($this->type);
            // exit;

            if ($r) {
                if ($this->type == '1') {
                    while ($w = $this->db->fetchByAssoc($r)) {
                        $tmp = $this->getPosition($w, $stockOperations);

                        // dump($tmp);
                        // continue;

                        if (array_key_exists($p = $tmp['position'], $return_array)) {
                            if ($tmp['i_amount']) {

                                if ($tmp['sys_par']) {

                                    $return_array[$p]['i_amount'][] = array(
                                        'sys_par' => $tmp['sys_par'],
                                        'book_name' => $tmp['book_name'],
                                        'type' => $tmp['type'],
                                        'book_symbol' => $tmp['book_symbol'],
                                        'book_number' => $tmp['b_book_number'],
                                        // 'book_amount' => $tmp['i_amount']
                                        'book_amount' => $tmp['book_amount']
                                    );
                                }
                            }
                        } else {
                            if ($tmp['i_amount']) {
                                // $tmp['i_amount'] = array();

                                if ($tmp['sys_par']) {

                                    $tmp['i_amount'] = array(
                                        array(
                                            'sys_par' => $tmp['sys_par'],
                                            'book_name' => $tmp['book_name'],
                                            'type' => $tmp['type'],
                                            'book_symbol' => $tmp['book_symbol'],
                                            'book_number' => $tmp['b_book_number'],
                                            // 'book_amount' => $tmp['i_amount']
                                            'book_amount' => $tmp['book_amount']
                                        )
                                    );
                                }
                            }

                            $return_array[$p] = $tmp;
                        }

                        $return_array[$p]['i_amount'] = $return_array[$p]['i_amount'] ?  : array();
                    }
                } else {
                    while ($w = $this->db->fetchByAssoc($r)) {
                        $return_array[] = $this->getPosition($w, $stockOperations);
                    }
                }

                // dump(array_values($return_array));
                // exit;

                $json = getJSONobj();
                return $array ? array_values($return_array) : $json->encode(array_values($return_array));
            }
        }

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