<?php
/**
 * Script for changing the sub_id's of pages
 * @author Rihards Siliņš
 * @copyright MTC media Ltd
 */
$cms_root_path = "../../../";
require_once($cms_root_path."includes/compatibility_includer.php");

use \Mtc\Cms\Handlers\ListingCacheHandler;
use \Mtc\Cms\Models\Page as PageModel;

if (empty($_POST['current_page_id']) || !is_numeric($_POST['current_page_id'])) {
    header("HTTP/1.0 400 Bad Request");
    $error_message = "Valid current_page_id missing from move page request.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

if (empty($_POST['new_sub_id']) || !is_numeric($_POST['new_sub_id'])) {
    header("HTTP/1.0 400 Bad Request");
    $error_message = "Valid new_sub_id missing from move page request.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

if (empty($_POST['page_ids'])) {
    header("HTTP/1.0 400 Bad Request");
    $error_message = "page_ids missing from move page request.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

$target_page = new Page();
$target_page->get($_POST['new_sub_id']);

if (empty($target_page->id)) {
    header("HTTP/1.0 409 Conflict");
    $error_message = "The page you attempted to move the pages to was not found.";
    ContentManagerPanel::addMessage($error_message);
    die($error_message);
}

$current_page = new Page();
$current_page->get($_POST['current_page_id']);


foreach ($_POST['page_ids'] as $page_id) {
    if (empty($page_id) || !is_numeric($page_id)) {
        continue;
    }
    $pages = PageModel::where("id", $page_id)
        ->orWhere("draft_for_page_id", $page_id)
        ->get();
    foreach ($pages as $page) {
        $page->sub_id = $target_page->id;
        $page->save();
    }
}
// rebuild listing cache if relevant
ListingCacheHandler::triggerAsyncRefresh($current_page);
ListingCacheHandler::triggerAsyncRefresh($target_page);
