<?php

/*************************************************************************************************************************************
 *                                                      INITIALISE
*************************************************************************************************************************************/

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

use Mtc\Cms\Models\PageList as PageList;

/*************************************************************************************************************************************
 *                                                      PROCESS
*************************************************************************************************************************************/

if ( merge_cms_pagedata($_POST) ) {

    Pagedata::orderFix($_POST['page_id']);

    echo "true"; exit();

}

echo "false"; exit();

function merge_cms_pagedata($data) {

    // first list merges into second

    if (!empty($data['page_id']) && is_numeric($data['page_id']) &&
        !empty($data['first_list_id']) && is_numeric($data['first_list_id']) &&
        !empty($data['second_list_id']) && is_numeric($data['second_list_id']) &&
        !empty($data['list_name'])) {

        $list_id        = $data['second_list_id'];
        $list_name      = $data['list_name'];
        $page_id        = $data['page_id'];


        // now get to the (to be deleted) first list item datas

        $to_be_deleted_list = new Pagedata();

        if ($to_be_deleted_list->get(0, $data['first_list_id'], 0, 0, true, true) === false) {
            return false;
        }

        $to_be_deleted_list_items_datas = $to_be_deleted_list->pagedata[0]['items'][0]['data'];

        // now get to the second (the one who stays) list items

        $list = new Pagedata();

        if ( $list->Get(0,$list_id) === false ) {
            return false;
        }

        // if listname is provided - rename list
        if ( $list_name != "false" && !empty($list_name) ) {

            $list->pagedata[0]['name'] = $list_name;

        }


        // loop through lists items
        for ($i=0; $i<count($list->pagedata[0]['items']); $i++) {

            // add the old items data

            for ($j=0; $j<count($to_be_deleted_list_items_datas); $j++) {

                $to_be_deleted_list_items_datas[$j]['order'] = count($list->pagedata[0]['items'][$i]['data']);
                $list->pagedata[0]['items'][$i]['data'][] = $to_be_deleted_list_items_datas[$j];

            }

        }


        if ( $list->Save() ) {

            // Delete the old list
            PageList::destroy($data['first_list_id']);
            Pagedata::orderFix($data['page_id']);
            return true;

        }

        return false;

    }

    return false;

}
