<?php
/**
 * 2007-2023 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 *  @author    PrestaShop SA <contact@prestashop.com>
 *  @copyright 2007-2023 PrestaShop SA
 *  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */

namespace PrestaShop\Module\AgileMultisellerPro\Helper;

use PrestaShop\Module\AgileMultisellerPro\Entity\Sellerinfo;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\DataConfiguration;

if (!defined('_PS_VERSION_')) {
    exit;
}

class AgileHelperSellerInfo
{
    public static function syncSellerManufacturerSupplier(Sellerinfo $sellerinfo)
    {
        if (\Configuration::get(DataConfiguration::AGILE_MS_IS_MANUFACTURER)) {
            $m = self::synchSellerManufacturer($sellerinfo);

            if ($sellerinfo->getIdManufacturer() == 0 && $m->id > 0) {
                $sellerinfo->setIdManufacturer($m->id);
            }
        }

        if (\Configuration::get(DataConfiguration::AGILE_MS_IS_SUPPLIER)) {
            $s = self::synchSellerSupplier($sellerinfo);

            if ($sellerinfo->getIdSupplier() == 0 && $s->id > 0) {
                $sellerinfo->setIdSupplier($s->id);
            }
        }

        if ($sellerinfo->getIdSellerInfo()) {
            self::syncSellerManufacturerSupplierLogo($sellerinfo);
        }
    }

    public static function synchSellerManufacturer($sellerinfo)
    {
        $id_deflang = (int) \Configuration::get('PS_LANG_DEFAULT');
        $address = self::getAddressData($sellerinfo);

        $languages = \Language::getLanguages(false);
        $manufacturer = new \Manufacturer($sellerinfo->getIdManufacturer());

        if (!\Validate::isLoadedObject($manufacturer)) {
            $sellerinfo->setIdManufacturer(0);
            $manufacturer->id = 0;
        }

        $manufacturer->name = $sellerinfo->getLangByLangId($id_deflang)->getCompany();
        $manufacturer->active = $sellerinfo->isActive();

        foreach ($languages as $lang) {
            $idLang = (int) $lang['id_lang'];
            $manufacturer->description[$idLang] = $sellerinfo->getLangByLangId($idLang)->getDescription();
            $manufacturer->short_description[$idLang] = '';
            $manufacturer->meta_description[$idLang] = '';
            $manufacturer->meta_keywords[$idLang] = '';
            $manufacturer->meta_title[$idLang] = '';
        }

        $manufacturer->save();

        $id_address = (int) \Db::getInstance()->getValue('SELECT id_address FROM ' . _DB_PREFIX_ .
            'address where id_manufacturer=' . (int) $manufacturer->id);

        if ($id_address == 0) {
            $sql = 'INSERT INTO ' . _DB_PREFIX_ . 'address (`id_country`, `id_state`, `id_customer`,
                `id_manufacturer`, `id_supplier`, `id_warehouse`, `alias`, `company`, `lastname`, `firstname`,
                `address1`, `address2`, `postcode`, `city`, `other`, `phone`, `phone_mobile`, `vat_number`,
                `dni`, `date_add`, `date_upd`, `active`, `deleted`)
					VALUES (' . (int) $address->id_country . ', ' . (int) $address->id_state . ', 0, ' .
                (int) $manufacturer->id . ', 0, 0, \'manufacturer\', \'' . $address->company .
                '\', \'manufacturer\', \'manufacturer\', \'' . $address->address1 . '\', \'' . $address->address2 .
                '\', \'' . $address->postcode . '\', \'' . $address->city . '\', \'\', \'' . $address->phone . '\', \'' .
                $address->phone_mobile . '\', \'\', \'\', \'' . date('Y-m-d H:i:s') .
                '\', \'' . date('Y-m-d H:i:s') . '\', 1, 0)';
        } else {
            $sql = 'UPDATE ' . _DB_PREFIX_ . 'address SET `id_country` = ' . (int) $address->id_country .
                ', `id_state` = ' . (int) $address->id_state . ', `id_manufacturer` = ' . (int) $manufacturer->id .
                ', `company` = \'' . $address->company . '\', `address1` = \'' . $address->address1 .
                '\', `address2` = \'' . $address->address2 . '\', `postcode` = \'' . $address->postcode .
                '\', `city` = \'' . $address->city . '\', `phone` = \'' . $address->phone . '\', `phone_mobile` = \'' .
                $address->phone_mobile . '\', `dni` = \'' . $address->dni . '\', `date_upd` = \'' .
                date('Y-m-d H:i:s') . '\' WHERE id_address = ' . (int) $id_address;
        }

        \Db::getInstance()->Execute($sql);

        return $manufacturer;
    }

    public static function synchSellerSupplier($sellerinfo)
    {
        $id_deflang = (int) \Configuration::get('PS_LANG_DEFAULT');
        $address = self::getAddressData($sellerinfo);
        $languages = \Language::getLanguages(false);
        $supplier = new \Supplier($sellerinfo->getIdSupplier());

        if (!\Validate::isLoadedObject($supplier)) {
            $sellerinfo->setIdSupplier(0);
            $supplier->id = 0;
        }

        $supplier->name = $sellerinfo->getLangByLangId($id_deflang)->getCompany();
        $supplier->active = $sellerinfo->isActive();

        foreach ($languages as $lang) {
            $idLang = (int) $lang['id_lang'];
            $supplier->description[$idLang] = $sellerinfo->getLangByLangId($idLang)->getDescription();
            $supplier->meta_description[$idLang] = '';
            $supplier->meta_keywords[$idLang] = '';
            $supplier->meta_title[$idLang] = '';
        }

        $supplier->save();

        $id_address = (int) \Db::getInstance()->getValue('SELECT id_address FROM ' . _DB_PREFIX_ .
            'address where id_supplier = ' . (int) $supplier->id);

        if ($id_address == 0) {
            $sql = 'INSERT INTO ' . _DB_PREFIX_ .
                'address (`id_country`, `id_state`, `id_customer`, `id_manufacturer`, `id_supplier`,
                `id_warehouse`, `alias`, `company`, `lastname`, `firstname`, `address1`, `address2`,
                `postcode`, `city`, `other`, `phone`, `phone_mobile`, `vat_number`, `dni`, `date_add`,
                `date_upd`, `active`, `deleted`)
					VALUES (' . (int) $address->id_country . ', ' . (int) $address->id_state . ', 0, 0, ' .
                (int) $supplier->id . ', 0, \'supplier\', \'' . $address->company . '\', \'supplier\' , \'supplier\', \'' .
                $address->address1 . '\', \'' . $address->address2 . '\', \'' . $address->postcode . '\', \'' .
                $address->city . '\', \'\', \'' . $address->phone . '\', \'' . $address->phone_mobile .
                '\', \'\', \'\', \'' . date('Y-m-d H:i:s') . '\', \'' . date('Y-m-d H:i:s') . '\', 1, 0)';
        } else {
            $sql = 'UPDATE ' . _DB_PREFIX_ . 'address SET `id_country` = ' . (int) $address->id_country .
                ', `id_state` = ' . (int) $address->id_state . ', `id_supplier` = ' . (int) $supplier->id .
                ', `company` = \'' . $address->company . '\', `address1` = \'' . $address->address1 .
                '\', `address2` = \'' . $address->address2 . '\', `postcode` = \'' . $address->postcode .
                '\', `city` = \'' . $address->city . '\', `phone` = \'' . $address->phone . '\', `phone_mobile` = \'' .
                $address->phone_mobile . '\', `dni` = \'' . $address->dni . '\', `date_upd` = \'' .
                date('Y-m-d H:i:s') . '\' WHERE id_address = ' . (int) $id_address;
        }

        \Db::getInstance()->Execute($sql);

        return $supplier;
    }

    public static function getAddressData($sellerinfo)
    {
        $customer = new \Customer($sellerinfo->getIdCustomer());
        $address = new \Address();

        $address->id_customer = 0;
        $address->id_manufacturer = 0;
        $address->id_supplier = 0;
        $address->id_warehouse = 0;
        $address->id_country = $sellerinfo->getIdCountry();
        $address->id_state = $sellerinfo->getIdState();
        $address->company = $sellerinfo->getCompany();
        $address->lastname = $customer ? $customer->lastname : '';
        $address->firstname = $customer ? $customer->firstname : '';
        $address->address1 = $sellerinfo->getAddress1();
        $address->address2 = $sellerinfo->getAddress2();
        $address->postcode = $sellerinfo->getPostcode();
        $address->city = $sellerinfo->getCity();
        $address->phone = $sellerinfo->getPhone();
        $address->phone_mobile = $sellerinfo->getPhone();
        $address->dni = $sellerinfo->getDni();
        $address->date_add = $sellerinfo->getDateAdd();
        $address->date_upd = $sellerinfo->getDateUpd();

        return $address;
    }

    public static function syncSellerManufacturerSupplierLogo($sellerinfo)
    {
        if (
            \Configuration::get(DataConfiguration::AGILE_MS_IS_MANUFACTURER)
            || \Configuration::get(DataConfiguration::AGILE_MS_IS_SUPPLIER)
        ) {
            $sellerlogo = AgileHelper::getImageDirectory($sellerinfo->getIdSellerInfo(), 'logo');

            if (!file_exists($sellerlogo)) {
                return false;
            }

            if (\Configuration::get(DataConfiguration::AGILE_MS_IS_MANUFACTURER)) {
                $manufacturerlogo = _PS_IMG_DIR_ . 'm' . DIRECTORY_SEPARATOR .
                    $sellerinfo->getIdManufacturer() . '.jpg';

                copy($sellerlogo, $manufacturerlogo);
                $images_types = \ImageType::getImagesTypes('manufacturers');

                foreach ($images_types as $image_type) {
                    $file = _PS_MANU_IMG_DIR_ . $sellerinfo->getIdManufacturer() . '.jpg';

                    \ImageManager::resize($file, _PS_MANU_IMG_DIR_ . $sellerinfo->getIdManufacturer() . '-' .
                        \Tools::stripslashes($image_type['name']) .
                        '.jpg', (int) $image_type['width'], (int) $image_type['height']);
                }
            }

            if (\Configuration::get(DataConfiguration::AGILE_MS_IS_SUPPLIER)) {
                $supplierlogo = _PS_IMG_DIR_ . 'su' . DIRECTORY_SEPARATOR . $sellerinfo->getIdSupplier() . '.jpg';

                copy($sellerlogo, $supplierlogo);
                $images_types = \ImageType::getImagesTypes('suppliers');

                foreach ($images_types as $image_type) {
                    $file = _PS_SUPP_IMG_DIR_ . $sellerinfo->getIdSupplier() . '.jpg';

                    \ImageManager::resize($file, _PS_SUPP_IMG_DIR_ . $sellerinfo->getIdSupplier() . '-' .
                        \Tools::stripslashes($image_type['name']) .
                        '.jpg', (int) $image_type['width'], (int) $image_type['height']);
                }
            }
        }
    }
}
