<?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
 */

use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelper;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelperMembership;

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

class AgileMultiSellerProAgileCronModuleFrontController extends ModuleFrontController
{
    public function init()
    {
        parent::init();

        try {
            if (!$this->module->active) {
                throw new Exception('Module is disabled');
            }

            $shopToken = hash('sha256', 'agilecron.' . _COOKIE_IV_);
            if ($shopToken != AgileHelper::getBearerToken()) {
                // throw new \Exception('Unauthorized ' . $shopToken, 401);
                throw new Exception('Unauthorized', 401);
            }

            $cronType = 'action' . ucfirst(strtolower(Tools::getValue('action')));
            if (!method_exists($this, $cronType)) {
                throw new Exception(sprintf('Method "%s" not exists', $cronType), 400);
            }

            $this->$cronType();
        } catch (Exception $e) {
            return $this->response([
                'success' => false,
                'error' => [
                    'code' => $e->getCode(),
                    'message' => $e->getMessage(),
                ],
            ]);
        }

        return $this->response([
            'success' => true,
        ]);
    }

    private function actionSendmembershipexiprationreminder()
    {
        AgileHelperMembership::sendMembershipExiprationReminder();
    }

    private function actionHideproducts()
    {
        AgileHelperMembership::hideProducts(Tools::getValue('date'));
    }

    private function response($data)
    {
        if (!headers_sent()) {
            header('Content-Type: application/json');
        }

        echo json_encode($data);
        exit;
    }
}
