<?php

use Bitrix\Main\Loader;
use intec\core\helpers\ArrayHelper;

require_once($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_before.php');

if (!check_bitrix_sessid()) {
    http_response_code(403);

    die('Forbidden');
}

global $USER;

if (!$USER->IsAuthorized() || !$USER->CanDoOperation('cache_control')) {
    http_response_code(403);

    die('Forbidden');
}

if (!Loader::includeModule('intec.core')) {
    die('Module intec.core not found');
}

include_once('class.php');

$backUrl = (string)ArrayHelper::getValue($_REQUEST, 'BACK_URL');

if (
    $backUrl === ''
    || !str_starts_with($backUrl, '/')
    || str_starts_with($backUrl, '//')
    || str_contains($backUrl, '://')
) {
    $backUrl = '/';
}

$token = preg_replace(
    '/[^A-Za-z0-9_\-\.]/',
    '',
    (string)ArrayHelper::getValue($_REQUEST, 'ACCESS_TOKEN')
);
$cachePath = 'upload/intec.universe/instagram/cache/#SITE_DIR#';

$oUpdate = new IntecInstagramComponent();
$oUpdate->setToken($token);
$oUpdate->setFileCachePath($cachePath);
$oUpdate->clearResultCache();
$oUpdate->refreshToken();
$data = $oUpdate->getData();
$oUpdate->storeCache($data);

LocalRedirect($backUrl);
