<?php

// ini_set('display_errors', '1');
// error_reporting(E_ALL);

// echo '<pre>REQUEST: ' . var_export($_REQUEST, true) . '</pre>';
// echo '<pre>POST: ' . var_export($_POST, true) . '</pre>';
// echo '<pre>' . var_export($_SESSION, true) . '</pre>';
// echo '<pre>Session: ' . var_export($_SESSION['EcmFkVatRegisters2_ECMFKVATREGISTER_ORDER_BY'], true) . '</pre>';

class EcmFkVatRegistersController extends SugarController {

    /**
     * Force include some js used in module.
     */
    public function post_ListView() {
        echo '<script type="text/javascript" src="include/JSON.js"></script>';
        echo '<script type="text/javascript" src="modules/EcmProducts/mintajax.js"></script>';
        echo '<script type="text/javascript" src="modules/EcmFkVatRegisters/EcmFkVatRegisters.js"></script>';
        echo '<script type="text/javascript" src="modules/EcmFkVatRegisters/EcmFkVatRegistersListView.js"></script>';
        // dump($_REQUEST);
    }

    // public function action_ListView() {
        // echo '<script type="text/javascript" src="modules/EcmFkVatRegisters/EcmFkVatRegistersListView.js"></script>';
    // }

    /**
     * Select options populator.
     *
     * Fill up select in listview with corresponding vatkinds (with provided type, mapped further @see $fktypemap).
     *
     * Functionality handles using stored last queries and selecting proper options.
     */
    public function action_populatenames() {
        global $db, $current_user;

        // Map differences within register types and kind items.
        $fktypemap = array_flip(array(
            1 => 2,
            2 => 3,
            3 => 1,
            4 => 0,
        ));

        $qPreferences = $current_user->getPreference('EcmFkVatRegistersQ');
        $selected = array();

        switch (@$_GET['src']) {
            default:
                break;

            case 'report':
            case 'EditView':
                $selected = (array) @$_GET['forceselect'] ? : array();
                break;

            case 'ListView':
                $selected = (array) $qPreferences['ecmfkvatkind_id_basic'];
                break;
        }

        // echo var_export($selected, true);
        // exit;

        $data = @explode(',', $_GET['data']) ? : array();

        // var_export($data);
        // die();

        array_walk($data, function(&$value, $key) use ($fktypemap) {
                    $value = '\'' . $value . '\'';
                });

        $string = '';
        $stringParts = array();

        $q = '
            SELECT
            i.id,
            i.title
            FROM ecmfkvatkinditems AS i
            join ecmfkvatkinds AS k
            on k.id = i.ecmfkvatkind_id
            ' . ((count($data) > 0) ? ('WHERE k.id IN (' . implode(', ', $data) . ')') : '') . '
            ;
        ';

        // echo $q;
        // die();

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

        if ($result) {
            while ($row = $db->fetchByAssoc($result)) {
                // var_export(in_array($row['id'], $selected));
                // die();

                $isSelected = in_array($row['id'], $selected) ? ' selected' : '';

                $tmp = sprintf('<option value="%s"%s>%s</option>', $row['id'], $isSelected, $row['title']);
                $stringParts[] = $tmp;
            }
        }

        // die();
        // var_export($stringParts);
        // die();

        $string .= implode(PHP_EOL, $stringParts);

        echo (string) $string;
        die();
    }

    /**
     * @see action_populatenames
     *
     * different query (?)
     */
    public function action_populatekinds() {
        global $db, $current_user;

        $fktypemap = array_flip(array(
            1 => 2,
            2 => 3,
            3 => 1,
            4 => 0,
        ));

        $qPreferences = $current_user->getPreference('EcmFkVatRegistersQ');
        $selected = array();

        switch (@$_GET['src']) {
            default:
                break;

            case 'report':
            case 'EditView':
                $selected = (array) @$_GET['forceselect'] ? : array();
                break;

            case 'ListView':
                $selected = (array) $qPreferences['ecmfkvatkind_id_basic'];
                break;
        }

        // echo var_export($selected, true);
        // exit;

        $data = @explode(',', $_GET['data']) ? : array();

        // var_export($data);
        // die();

        array_walk($data, function(&$value, $key) use ($fktypemap) {
                    $value = $fktypemap[$value];
                });

        $string = '';
        $stringParts = array();

        $q = '
            SELECT
            k.id,
            k.name
            FROM ecmfkvatkinds AS k
            ' . ((count($data) > 0) ? ('WHERE type IN (' . implode(', ', $data) . ')') : '') . '
            ;
        ';

        // echo $q;
        // die();

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

        if ($result) {
            while ($row = $db->fetchByAssoc($result)) {
                // var_export(in_array($row['id'], $selected));
                // die();

                $isSelected = in_array($row['id'], $selected) ? ' selected' : '';

                $tmp = sprintf('<option value="%s"%s>%s</option>', $row['id'], $isSelected, $row['name']);
                $stringParts[] = $tmp;
            }
        }

        // die();
        // var_export($stringParts);
        // die();

        $string .= implode(PHP_EOL, $stringParts);

        echo (string) $string;
        die();
    }

    /**
     * Update positions.
     *
     * magic things happens here.
     *
     * iterate through items and fetch its licz/zal user friendly forms.
     * depending on that forms (transformed) recalculate and add other positions.
     *
     * @hint calculated decresing, returned ascending by key.
     * @hint data are $_POST'ed because of response length limits. didnt test on longer data list
     */
    public function action_updatepositions() {
        global $db;

        $fktypemap = array_flip(array(
            1 => 2,
            2 => 3,
            3 => 1,
            4 => 0,
        ));

        static $data = array();
        static $licz = array();
        static $zal = array();

        $json = getJSONobj();

        /* BOF: Data preparation. */
        $dat_zap = @$_GET['dat_zap'];
        $type = @$_GET['type'] ? : '2';

        $encoded = @$_POST['data'] ? : '[]';
        $decoded = @$json->decode(htmlspecialchars_decode($encoded)) ? : array();

        // dump($type);
        // die();

        ksort($decoded);
        $decoded = array_reverse($decoded, true);

//         $decoded =array (
//           2 =>
//           array (
//             'i_code' => '2',
//             'i_position' => '1',
//             'ecmfkbook_id' => false,
//             'i_name' => 'WARTOŚĆ NETTO - STAWKA 22%',
//             'ecmfkvattable_id' => '4233f21a-89b7-195d-730c-51ee26ba3ef0',
//             'book_number' => false,
//             'i_acc_wn' => 'null',
//             'i_acc_wn_code' => '000',
//             'i_acc_wn_name' => 'Brak',
//             'i_acc_wn_type' => 0,
//             'i_account_acc_wn' => '0',
//             'i_acc_wn_kind' => false,
//             'i_acc_ma' => 'null',
//             'i_acc_ma_code' => '000',
//             'i_acc_ma_name' => 'Brak',
//             'i_acc_ma_type' => 0,
//             'i_account_acc_ma' => '0',
//             'i_acc_ma_kind' => false,
//             'i_amount' => 0,
//             'i_amount_wn' => 0,
//             'i_amount_ma' => 0,
//             'i_sp_zap' => false,
//             'i_il_dni' => false,
//             'i_symb_wa' => '',
//             'i_kurs_wal' => '',
//             'i_dat_zap' => false,
//             'i_description' => '',
//           ),
//         ) ;

//         echo var_export($decoded, true);
//         exit;

        /* EOF: Data preparation. */

        array_walk($decoded, function(&$value, $key) use ($db, &$data, &$licz, &$zal) {
                    if (false == array_key_exists($id = $value['ecmfkvattable_id'], $data)) {
                        $query = '
                            SELECT
                                #  id
                                #, position
                                #, name
                                #,
                                  licz
                                , zal
                            FROM
                                ecmfkvattables
                            WHERE
                                id = \'' . $id . '\'
                            LIMIT
                                0, 1
                            ;
                        ';

                        // dump($query);
                        // die();

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

                        $data[$id]['licz'] = $results['licz'];
                        $data[$id]['zal'] = $results['zal'];
                    }

                    $licz[$id] = trim($data[$id]['licz']);
                    $zal[$id] = trim($data[$id]['zal']);
                });

        // dump($decoded);

//         $licz = array_filter($licz, 'strlen');

        // dump($data);
//         dump($licz, $zal);
//         die();

        $new = array();

        foreach ($decoded as $dkey => &$dvalue) {
            /* LICZ */
            if (true == isset($licz[$key = $dvalue['ecmfkvattable_id']])) {
                $pattern = $licz[$key];

                $positions = getPositionsFromPattern($pattern);

                array_walk($positions, function(&$value, $key) {
                        $value = $value[0];
                    });

                    $decodedKeys = array_keys($decoded);
                    $positionsKeys = array_values($positions);

                    $newKeys = array_diff($positionsKeys, $decodedKeys);

                    // dump($newKeys);
                    // die();

                    foreach($newKeys as $kkey => $kvalue) {
                        $query = '
                            SELECT
                                  vt.id as ecmfkvatkind_id
                                #, vt.position as i_code
                                , vt.name as i_name
                                , vt.licz
                                , vt.zal
                                , vt.acc_wn
                                , vt.acc_ma
                                , vt.account_acc_wn
                                , vt.account_acc_ma
                                , wn.code as acc_wn_code
                                , ma.code as acc_ma_code
                                , wn.name as acc_wn_name
                                , ma.name as acc_ma_name
                                , wn.type as acc_wn_type
                                , ma.type as acc_ma_type
                                , wn.kind as i_acc_ma_kind
                                , ma.kind as i_acc_ma_kind
                            FROM
                                ecmfkvattables as vt

                            left join ecmbankaccounts as wn on wn.id = acc_wn
                            left join ecmbankaccounts as ma on ma.id = acc_ma

                            WHERE
                                vt.position = \'' . $kvalue . '\'
                            AND
                                vt.type = \'' . $type . '\'
                            LIMIT
                                0, 1
                            ;
                        ';
                        //        type = \'' . $fktypemap[$type] . '\'

                        // dump($query);
                        // exit;

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

                        $i_dat_zap = date('Y-m-d');

                        $new[$kvalue] = array(
                            'i_code' => $kvalue,
                            'i_name' => $results['i_name'],
                            'ecmfkvattable_id' => $results['ecmfkvatkind_id'],
                            'i_dat_zap' => $i_dat_zap,
                            // 'i_acc_wn' => false,
                            // 'i_acc_wn_code' => '000',
                            // 'i_acc_wn_name' => 'Brak',
                            // 'i_acc_ma' => false,
                            // 'i_acc_ma_code' => '000',
                            // 'i_acc_ma_name' => 'Brak',
                            'i_acc_wn' => $results['acc_wn'] ? : false,
                            'i_acc_wn_code' => $results['acc_wn_code'] ? : '000',
                            'i_acc_wn_name' => $results['acc_wn_name'] ? : 'Brak',
                            'i_acc_wn_type' => $results['acc_wn_type'] ? : '0',
                            'i_acc_wn_kind' => $results['i_acc_wn_kind'] ? : '0',
                            'i_account_acc_wn' => $results['account_acc_wn'] ? : '0',
                            'i_acc_ma' => $results['acc_ma'] ? : false,
                            'i_acc_ma_code' => $results['acc_ma_code'] ? : '000',
                            'i_acc_ma_name' => $results['acc_ma_name'] ? : 'Brak',
                            'i_acc_ma_type' => $results['acc_ma_type'] ? : '0',
                            'i_acc_ma_kind' => $results['i_acc_ma_kind'] ? : '0',
                            'i_account_acc_ma' => $results['account_acc_ma'] ? : '0',
                            // 'i_amount' => 0,
                            // 'i_sp_zap' => '',
                            // 'i_il_dni' => 0,
                            // 'i_symb_wa' => 'PLN',
                            // 'i_kurs_wal' => 1,
                        );

                        if (false == array_key_exists($id = $results['ecmfkvatkind_id'], $data)) {
                            $data[$id]['licz'] = $results['licz'];
                            $data[$id]['zal'] = $results['zal'];
                        }

                        $licz[$id] = trim($data[$id]['licz']);
                        $zal[$id] = trim($data[$id]['zal']);
                    }
            } else {

            }
        }

        foreach($new as $k => $v) {
            $decoded[$v['i_code']] = $v;
        }

        // $decoded = array_merge($decoded, $new);

        ksort($decoded);
        $decoded = array_reverse($decoded, true);

//         dump($decoded);
//         die();

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

//         dump($licz, $zal);
//         die();

        // Magic. contact mh.
        foreach ($decoded as $dkey => &$dvalue) {
            /* ZAL */
            if (true == isset($zal[$key = $dvalue['ecmfkvattable_id']])) {
                $pattern = $zal[$key];

                list($function, $arguments) = translatePattern($pattern);

                $fields = array_shift($arguments);

                array_walk($arguments, function(&$value, $key) {
                        $value = $value[0];
                    });

                $translatedFields = getPositionsFromPattern($fields[0]);
                $translatedConstants = getConstantsFromPattern($fields[0]);

                // dump($pattern);
                // dump($function);
                // dump($arguments);
                // die();

//                 dump($translatedFields);
//                 dump($translatedConstants);
//                 exit;

                $mergedFields = array();

                foreach($translatedFields as $tfk => $tfv) {
                    list($num, $position) = $tfv;

                    $signPosition = $position - 2 - (2 - strlen($num));
                    $sign = $signPosition > 0 ? substr($fields[0], $signPosition, 1) : '';

                    $tfv[0] = $decoded[$num]['i_amount'] ? : 0;
                    $tfv['sign'] = $sign;

                    $mergedFields[] = $tfv;
                }

                foreach($translatedConstants as $tck => $tcv) {
                    list($num, $position) = $tcv;

                    $signPosition = $position - 1;
                    $sign = $signPosition > 1 ? substr($fields[0], $signPosition, 1) : '';

                    $tcv['sign'] = $sign;

                    $mergedFields[] = $tcv;
                }

                usort($mergedFields, function($left, $right) {
                        return $left[1] > $right[1];
                    });

                $evalstring = 'return (double) (';

                $tmp = '';

                foreach($mergedFields as $mfk => $mfv) {
                    $tmp .= (($sign = $mfv['sign']) ? (' ' . $sign . ' ') : '') . $mfv[0];
                }

                $evalstring .= $tmp ? : '0';

                $evalstring .= ');';

//                 dump($evalstring);
//                 dump($function);
//                 die();

                $eval = eval($evalstring);

                switch($function) {
                    case 'round':
                        array_unshift($arguments, $eval);
                        $dvalue['i_amount'] = call_user_func_array('round', $arguments);
                        break;

                    default:
                        $dvalue['i_amount'] = $eval;
                        break;
                }


//                 dump($dkey, $dvalue);
//                 exit
            } else {

            }
        }

//         dump($decoded);
//         exit;

        $return = array_reverse($decoded, true);

//         dump(count($return));
//         die();

        //
        if (count($return) == 0) {
            $return[] = array();
        }

        $returnString = $json->encode(array_values($return));

        $returnString = str_replace('\'', '\\\'', $returnString);
        $returnString = str_replace('"', '\'', $returnString);

        echo $returnString;
        die();
    }

}

/* BOF: functions used in transformating zal/licz forms. */
function getPositionsFromPattern($string, array &$matches = null) {
    $pattern = '/& *(\d+)\./';
    $count = preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);

    list($groups, $positions) = $matches;
    return $positions;
}

function getConstantsFromPattern($string, array &$matches = null) {
    $pattern = '/(\d+)\.(\d+)/';
    $count = preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);

    list($groups, $i, $m) = $matches;
    return $groups;
}

function translatePattern($string, array &$matches = null) {
    $pattern = '/([\w]+)?(\(?)([^\),]+)(\)?)/';
    $count = preg_match_all($pattern, $string, $matches, PREG_OFFSET_CAPTURE);

    list($groups, $function, $openBracket, $arguments, $closeBracket) = $matches;

    $return = array(
        $function[0][0],
        $arguments,
    );

    return $return;
}
/* EOF: functions used in transformating zal/licz forms. */