<?php

/**
 * Listing Cache Handler Class
 * Listing Cache Handler class responsible for handling the listing cache.
 * @author Rihards Silins
 * @copyright MTC Media Ltd
 * @version 1 10/03/2016
 * @access public
 */
namespace Mtc\Cms\Handlers;

use Page;

class ListingCacheHandler
{
    /**
     * ListingCacheHandler::triggerAsyncRefresh
     * trigger relevant listing cache refresh
     * @param Page Object $page
     * @return bool $success
     */
    public static function triggerAsyncRefresh($page)
    {
        // Check if LISTING_CACHE is enabled
        if (! defined('LISTING_CACHE') || LISTING_CACHE === false) {
            return false;
        }
        if ($page->slug == '404') {
            \ContentManager::refreshPageCache(404);
        }

        $command_arguments = array();

        if ($page->listing_container) {
            if (($page->type == 'history' || $page->type == 'temp') && $page->draft_for_page_id != 0) {
                $command_arguments[] = $page->draft_for_page_id;
            } else {
                $command_arguments[] = $page->id;
            }
        }

        // Get parent page
        if ($page->sub_id != 0) {
            $parent_page = new Page($page->sub_id);
            if ($parent_page->listing_container) {
                $command_arguments[] = $parent_page->id;
            }
        }

        if (empty($command_arguments)) {
            return false;
        }

        $php_lib = '/usr/local/bin/php';
        if (defined('PHP_LIB')) {
            $php_lib = PHP_LIB;
        }

        $command = $php_lib.' '.CMS_ROOT_PATH.'/admin/scheduled/refresh_listing_cache.php';

        for ($i = 0; $i < count($command_arguments); $i++) {
            $command .= ' '.$command_arguments[$i];
        }

        $command .= ' > /dev/null &';

        exec($command, $exec_output, $exec_response);

        return true;
    }
}
