<?php
/**
 *  Please read the terms of the CLUF license attached to this module(cf "licences" folder)
 *
 * @author    Línea Gráfica E.C.E. S.L.
 * @copyright Lineagrafica.es - Línea Gráfica E.C.E. S.L. all rights reserved.
 * @license   https://www.lineagrafica.es/licenses/license_en.pdf
 *            https://www.lineagrafica.es/licenses/license_es.pdf
 *            https://www.lineagrafica.es/licenses/license_fr.pdf
 */

require_once(
    _PS_MODULE_DIR_ .
    DIRECTORY_SEPARATOR .
    'lgcomments' .
    DIRECTORY_SEPARATOR .
    'classes' .
    DIRECTORY_SEPARATOR .
    'LGProductComment.php'
);
require_once(
    _PS_MODULE_DIR_ .
    DIRECTORY_SEPARATOR .
    'lgcomments' .
    DIRECTORY_SEPARATOR .
    'classes' .
    DIRECTORY_SEPARATOR .
    'LGStoreComment.php'
);

class LGCommentsCSV
{
    public static function importProductComments($module)
    {
        $html        = '';
        $separator1  = (int)Tools::getValue('separator1', 1);
        $sp          = self::getSeparator($separator1);
        $tokenPC     = Tools::getAdminTokenLite('AdminLGCommentsProducts');
//        $fileversion = (int)Tools::getValue('LGCOMMENTS_FILE_VERSION', 16);
        $encoding1 = (int)Tools::getValue('encoding1', 1);
        if (is_uploaded_file($_FILES['csv1']['tmp_name'])) {
            $type = explode(".", $_FILES['csv1']['name']);
            if (Tools::strtolower(end($type)) == 'csv') {
                if (move_uploaded_file(
                    $_FILES['csv1']['tmp_name'],
                    dirname(dirname(__FILE__)) . '/csv/' . $_FILES['csv1']['name']
                )) {
                    $archivo = $_FILES['csv1']['name'];
                    $fp      = fopen(dirname(dirname(__FILE__)) . '/csv/' . $archivo, 'r');
                    while (($datos = fgetcsv($fp, 1000, '' . $sp . '')) !== false) {
                        $datos[0]    = str_replace('/', '-', $datos[0]);
                        $date        = strtotime($datos[0]);

                        $date        = date('Y-m-d H:i:s', $date);
                        $csv_comment = $datos[4];
                        $csv_title   = $datos[8];
                        $csv_answer  = $datos[9];
                        $nick        = pSQL(((isset($datos[10]) && !empty($datos[10]))?$datos[10]:''));
                        if ($encoding1 == 2) {
                            $csv_comment = mb_convert_encoding($datos[4], 'UTF-8', 'auto');
                            $csv_title   = mb_convert_encoding($datos[8], 'UTF-8', 'auto');
                            $csv_answer  = mb_convert_encoding($datos[9], 'UTF-8', 'auto');
                            $nick        = (isset($datos[10])
                                && (!empty(pSQL(mb_convert_encoding($datos[10], 'UTF-8', 'auto')))))
                                ? mb_convert_encoding($datos[10], 'UTF-8', 'auto')
                                : '';
                        }

                        $data = array(
                            'date'        => $date,
                            'id_customer' => (int)$datos[1],
                            'id_product'  => (int)$datos[2],
                            'stars'       => (int)$datos[3],
                            'comment'     => pSQL($csv_comment),
                            'id_lang'     => (int)$datos[5],
                            'active'      => (int)$datos[6],
                            'position'    => (int)$datos[7],
                            'title'       => pSQL($csv_title),
                            'answer'      => pSQL($csv_answer),
                            'nick'        => pSQL($nick),
                        );

                        // If we don't have a value for nick, we will try to fill
                        // it using the selected option by customer.
                        if (empty(trim($nick)) || trim($nick) == '') {
                            if ((int)Tools::getValue('LGCOMMENTS_NICK_OPTIONS', 0) == 2) {
                                $nick2 = trim(pSQL(Tools::getValue('LGCOMMENTS_FORCED_NICK', '')));
                                if (!empty($nick2)) {
                                    $data['nick'] = pSQL($nick2);
                                }
                            } elseif ((int)Tools::getValue('LGCOMMENTS_NICK_OPTIONS', 0) == 1) {
                                $id_customer = ((isset($datos[1]))?(int)$datos[1]:0);
                                $customer    = new Customer($id_customer);
                                if (Validate::isLoadedObject($customer)) {
                                    $first_letter = Tools::substr($customer->firstname, 0, 1);
                                    $data['nick'] = pSQL($first_letter . '. ' . $customer->lastname);
                                }
                            }
                        }

                        Db::getInstance()->insert(LGProductComment::$definition['table'], $data, false, false);
                    }
                    fclose($fp);
                    $html .= $module->displayConfirmation(
                        $module->l('The comments have been successfully added') .
                        '&nbsp;'.
                        $module->getAnchor(
                            array(
                                'lgcomments_warning_link_href' => 'index.php?controller=AdminLGCommentsProducts&token='
                                    .$tokenPC,
                                'lgcomments_warning_link_target'  => '_blank',
                                'lgcomments_warning_link_message' => $module->l(
                                    'Click here to manage your product reviews'
                                ),
                            )
                        )
                    );
                }
            } else {
                $html .= $module->displayError(
                    $module->l('The format of the file is not valid, it must be saved in ".csv" format.')
                );
            }
        } else {
            $html .= $module->displayError($module->l('An error occurred while uploading the CSV file'));
        }

        return $html;
    }

    public static function exportProductComments($module)
    {
        $html         = '';
        $separator1   = (int)Tools::getValue('separator1', 1);
        $sp           = self::getSeparator($separator1);
        $ln           = "\n";
        $prodComments = LGProductComment::getAllProductComments();

        $fp           = fopen(_PS_ROOT_DIR_ . '/modules/' . $module->name . '/csv/save_products.csv', 'w');
        foreach ($prodComments as $prodComment) {
            fwrite(
                $fp,
                $prodComment['date'] . $sp . $prodComment['id_customer'] . $sp . $prodComment['id_product'] .
                $sp . $prodComment['stars'] . $sp . utf8_decode($prodComment['comment']) . '' .
                $sp . $prodComment['id_lang'] . $sp . $prodComment['active'] . $sp . $prodComment['position'] .
                $sp . utf8_decode($prodComment['title']) . $sp . utf8_decode($prodComment['answer']) . $ln
            );
        }
        fclose($fp);

        if ($prodComments != false) {
            $html .= $module->displayConfirmation(
                $module->l('The CSV file has been successfully generated,') . '&nbsp;'.
                $module->getAnchor(
                    array(
                        'lgcomments_warning_link_href'    => '../modules/' . $module->name . '/csv/save_products.csv',
                        'lgcomments_warning_link_message' => $module->l('click here to download it'),
                    )
                )
            );
        } else {
            $html .= $module->displayError($module->l('There are no product comments to export'));
        }

        return $html;
    }

    public static function importStorecomments($module)
    {
        $html       = '';
        $separator2 = (int)Tools::getValue('separator2', 1);
        $sp         = self::getSeparator($separator2);
        $tokenSC    = Tools::getAdminTokenLite('AdminLGCommentsStore');
        $encoding2  = (int)Tools::getValue('encoding2', 1);

        if (is_uploaded_file($_FILES['csv2']['tmp_name'])) {
            $type = explode(".", $_FILES['csv2']['name']);
            if (Tools::strtolower(end($type)) == 'csv') {
                if (move_uploaded_file(
                    $_FILES['csv2']['tmp_name'],
                    dirname(dirname(__FILE__)) . '/csv/' . $_FILES['csv2']['name']
                )) {
                    $archivo = $_FILES['csv2']['name'];
                    $fp = fopen(dirname(dirname(__FILE__)) . '/csv/' . $archivo, 'r');
                    while (($datos = fgetcsv($fp, 1000, '' . $sp . '')) !== false) {
                        $datos[0]    = str_replace('/', '-', $datos[0]);
                        $date        = strtotime($datos[0]);
                        $date        = date('Y-m-d H:i:s', $date);
                        $csv_comment = $datos[4];
                        $csv_title   = $datos[8];
                        $csv_answer  = $datos[9];
                        $nick        = pSQL(((isset($datos[10]) && !empty($datos[10]))?$datos[10]:''));
                        if ($encoding2 == 2) {
                            $csv_comment = mb_convert_encoding($datos[4], 'UTF-8', 'auto');
                            $csv_title   = mb_convert_encoding($datos[8], 'UTF-8', 'auto');
                            $csv_answer  = mb_convert_encoding($datos[9], 'UTF-8', 'auto');
                            $nick        = (isset($datos[10])
                                && (!empty(pSQL(mb_convert_encoding($datos[10], 'UTF-8', 'auto')))))
                                ? mb_convert_encoding($datos[10], 'UTF-8', 'auto')
                                : '';
                        }

                        $data = array(
                            'date'        => $date,
                            'id_customer' => (int)$datos[1],
                            'id_order'    => (int)$datos[2],
                            'stars'       => (int)$datos[3],
                            'comment'     => pSQL($csv_comment),
                            'id_lang'     => (int)$datos[5],
                            'active'      => (int)$datos[6],
                            'position'    => (int)$datos[7],
                            'title'       => pSQL($csv_title),
                            'answer'      => pSQL($csv_answer),
                            'nick'        => $nick,
                        );

                        // If we don't have a value for nick, we will try to fill
                        // it using the selected option by customer.
                        if (empty(trim($nick)) || trim($nick) == '') {
                            if ((int)Tools::getValue('LGCOMMENTS_NICK_OPTIONS_STORE', 0) == 2) {
                                $nick2 = trim(pSQL(Tools::getValue('LGCOMMENTS_FORCED_NICK_STORE', '')));
                                if (!empty($nick2)) {
                                    $data['nick'] = $nick2;
                                }
                            } elseif ((int)Tools::getValue('LGCOMMENTS_NICK_OPTIONS_STORE', 0) == 1) {
                                $id_customer = ((isset($datos[1]))?(int)$datos[1]:0);
                                $customer    = new Customer($id_customer);
                                if (Validate::isLoadedObject($customer)) {
                                    $first_letter = Tools::substr($customer->firstname, 0, 1);
                                    $data['nick'] = $first_letter . '. ' . $customer->lastname;
                                }
                            }
                        }

                        Db::getInstance()->insert(LGStoreComment::$definition['table'], $data, false, false);
                    }
                    fclose($fp);
                    $html .= $module->displayConfirmation(
                        $module->l('The comments have been successfully added') . '.&nbsp;'.
                        $module->getAnchor(
                            array(
                                'lgcomments_warning_link_href'    => 'index.php?controller=AdminLGCommentsStore&token='
                                    .$tokenSC,
                                'lgcomments_warning_link_target'  => '_blank',
                                'lgcomments_warning_link_message' => $module->l(
                                    'Click here to manage your store reviews'
                                ),
                            )
                        )
                    );
                }
            } else {
                $html .= $module->displayError(
                    $module->l('The format of the file is not valid, it must be saved in ".csv" format.')
                );
            }
        } else {
            $html .= $module->displayError($module->l('An error occurred while uploading the CSV file'));
        }

        return $html;
    }

    public static function exportStoreComments($module)
    {
        $html       = '';
        $separator2 = (int)Tools::getValue('separator2', 1);
        $sp         = self::getSeparator($separator2);

        $ln = "\n";
        $fp = fopen(_PS_ROOT_DIR_ . '/modules/' . $module->name . '/csv/save_store.csv', 'w');
        $storeComments = LGStoreComment::getAllStoreComments();
        foreach ($storeComments as $storeComment) {
            fwrite(
                $fp,
                $storeComment['date'] . $sp . $storeComment['id_customer'] . $sp . $storeComment['id_order'] .
                $sp . $storeComment['stars'] . $sp . utf8_decode($storeComment['comment']) . '' .
                $sp . $storeComment['id_lang'] . $sp . $storeComment['active'] . $sp . $storeComment['position'] .
                $sp . utf8_decode($storeComment['title']) . $sp . utf8_decode($storeComment['answer']) . $ln
            );
        }
        fclose($fp);
        if ($storeComments != false) {
            $html .= $module->displayConfirmation(
                $module->l('The CSV file has been successfully generated,') . '&nbsp;'
                .$module->getAnchor(
                    array(
                        'lgcomments_warning_link_href'    => '../modules/' . $module->name . '/csv/save_store.csv',
                        'lgcomments_warning_link_message' => $module->l('click here to download it'),
                    )
                )
            );
        } else {
            $html .= $module->displayError($module->l('There are no store comments to export'));
        }
        return $html;
    }

    public static function getSeparator($separator)
    {
        if ($separator == 2) {
            return ',';
        } else {
            return ';';
        }
    }
}
