<?php

use CkPhpUtil\Log;

/**
 * Preloader script for ajax calls.
 *
 * This sets the starting path inside the catalog directory, allowing the rest of OSC to load natively.
 */

if (isset($_POST['page'])) {
    $page = $_POST['page'];
} elseif (isset($_GET['page'])) {
    $page = $_GET['page'];
} else {
    $page = false;
}

/**
 * This switch statement will contain a define for cacheable.
 *
 * The define should contain the content type to be returned to the browser upon a successful find.
 * The swtich allows for more logic then just a simple array, as it was before.
 *
 * If you have an ajax page that can be cached to save some time, add it in here.
 * Obviously, you do not want to cache anything that will change frequently, such
 *   as pricing or design information.  Product/Category images are usually up for game however.
 *
 * Also, do not cache anything that requires authentication to view the object, as
 *   all auth. checking is disabled, due to the fact that app_top is never called,
 *   but instead the file is opened directly and immediately.
 *
 */
require_once('includes/application_top.php');

if (ENABLE_GLOBAL_CACHEABLE) {
    switch ($page) {
        //  Any standard text/html results.
        case 'avp_pantone_search':
            define('AJAX_CACHEABLE', 'text/html');
            break;
        //  Any standard image/jpeg results.
        case 'avp_get_design_template':
        case 'get_product_image':
            if (empty($_GET['ccid'])) {
                define('AJAX_CACHEABLE', false);
            } else {
                define('AJAX_CACHEABLE', 'image/png');
            }
            break;
        // Any standard image/png results.
        case 'show_color_image':
        case 'get_category_image':
            define('AJAX_CACHEABLE', 'image/png');
            break;
        //Special exceptions, require a bit more attention.
        case 'get_clipart':
            if (in_array($_GET['mode'] ?? '', ['get_full', 'get_preview'])) {
                define('AJAX_CACHEABLE', 'image/png');
            } else {
                define('AJAX_CACHEABLE', 'text/xml');
            }
            break;
        // Default case, disable caching completely.
        default:
            define('AJAX_CACHEABLE', false);
    }
} else {
    define('AJAX_CACHEABLE', false);
}

// Page requested is cacheable!  start the fun, whee...
if (ENABLE_GLOBAL_CACHEABLE && AJAX_CACHEABLE) {
    $_AJAXcachedPage = CACHE_DIR . CACHE_PREFIX . md5($_SERVER['REMOTE_ADDR'] . implode(',', $_GET) . implode(',', $_POST)) . '.ajax.cache';

    if (file_exists($_AJAXcachedPage) && ($fh = fopen($_AJAXcachedPage, 'r')) && filemtime($_AJAXcachedPage) > (time() - 7200)) {
        header('Content-Type: ' . AJAX_CACHEABLE);

        while (!feof($fh)) {
            echo fread($fh, 1024);
        }

        fclose($fh);
        die();
    }
}

if (!$page) {
    Log::write('Ajax file requested, but page data left blank:', 'error.log', Log::CRITICAL);
    Log::write('Request vars:' . print_r($_REQUEST, true), 'error.log', Log::CRITICAL);
    Log::write('Server vars:' . print_r($_SERVER, true), 'error.log', Log::CRITICAL);
    die("No Page Defined.");
}

// This script expects just the basename of the file.
// The .php/.inc/.inc.php is not needed when requesting the page via the GET/POST data.
$extensions = ['php', 'inc', 'inc.php'];
$found_file = false;

// Valid scripts may include more then just a php file.  Run through each possibility.
foreach ($extensions as $ext) {
    if (is_readable(DIR_FS_CATALOG . "ajax/{$page}.{$ext}")) {
        $found_file = DIR_FS_CATALOG . "ajax/{$page}.{$ext}";
        break;
    } elseif (is_readable(DIR_FS_CATALOG . 'templates/' . CLIENT_CODE . "/ajax/{$page}.{$ext}")) {
        $found_file = DIR_FS_CATALOG . 'templates/' . CLIENT_CODE . "/ajax/{$page}.{$ext}";
        break;
    }
}

if (!$found_file) {
    // Enable logging to the PHP error log to assist in debugging.
    Log::write('Ajax file does not exist: ' . DIR_FS_CATALOG . 'ajax/' . $page, 'error.log', Log::CRITICAL);
    die("Page Requested Not Found");
}

$allowIndexing = in_array(
    $page,
    [
        'get_product_image',
        'avp_get_design_template',
        'get_flexslider_home',
        'recommended_products'
    ]
);

if (
    PRIVATE_SITE
    || !$allowIndexing
) {
    header("X-Robots-Tag: noindex");
}

// Start the output buffer so I can save that to a cache file.
if (AJAX_CACHEABLE !== false && $_AJAXcachedPage) {
    ob_start();

    function _AJAXcachePage()
    {
        global $_AJAXcachedPage;
        $fh = fopen($_AJAXcachedPage, 'w');
        fwrite($fh, ob_get_contents());
        fclose($fh);
        ob_end_flush();
    }

    register_shutdown_function('_AJAXcachePage');
}


include($found_file);

