<?php

$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

use \Mtc\Cms\Handlers\ListingCacheHandler;

$page = new Page();

if (isset($_POST['page_id']) && is_numeric($_POST['page_id'])) {
    $page->get($_POST['page_id']);
    if (!empty($page->id)) {
        // checks so that non-mtcadmin user can't delete page he/she isn't allowed to delete
        if ($page->allow_delete == 0 && $page->type == "default") {
            die("not allowed to delete pages");
        }
        if ($page->type == "history" && empty($_SESSION['content_manager']['is_publisher']) && empty($_SESSION['content_manager']['is_mtcadmin'])) {
            die("page type is 'history'");
        }

        $sub_id = $page->sub_id;

        $page->delete($page->id, true);
        // rebuild listing cache if relevant
        ListingCacheHandler::triggerAsyncRefresh($page);
        die($sub_id);
    } else {
        die("page not found");
    }
} elseif (isset($_POST['page_ids'])) {
    $i = 0;
    foreach ($_POST['page_ids'] as $page_id) {
        if (empty($page_id) || !is_numeric($page_id)) {
            continue;
        }
        if ($i == 0) {
            $page->get($page_id);
            $sub_id = $page->sub_id;
            // rebuild listing cache if relevant
            ListingCacheHandler::triggerAsyncRefresh($page);
        }
        // checks so that non-mtcadmin user can't delete page he/she isn't allowed to delete
        if ($_SESSION['content_manager']['is_mtcadmin'] == false && $page->allow_delete == 0 && $page->type == "default") {
            continue;
        }
        if ($page->type == "history" && empty($_SESSION['content_manager']['is_publisher']) && empty($_SESSION['content_manager']['is_mtcadmin'])) {
            continue;
        }
        $page->delete($page_id, true);
        ++$i;
    }
    die($sub_id);
} else {
    die("page_id not provided");
}
