<?php

use Illuminate\Support\Facades\DB;

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

$p = new Page();
if ( isset($_GET['page_id']) && is_numeric($_GET['page_id']) ) {
    $p->Get($_GET['page_id']);
} else {
    die("Page not found.");
}

if (!function_exists('cms_flatten_listing_page_tree')) {
    /**
     * Recursively flatten a page tree for listing output.
     *
     * @param Page $page
     * @return Page[]
     */
    function cms_flatten_listing_page_tree(Page $page)
    {
        $items = [$page];
        $children = $page->get_subs(PHP_INT_MAX, "order", "ASC", false, true);
        foreach ($children as $child) {
            $items = array_merge($items, cms_flatten_listing_page_tree($child));
        }
        return $items;
    }
}

if (!function_exists('cms_collect_listing_matches')) {
    /**
     * Collect pages that match a search term, including their ancestor path.
     *
     * @param Page $page
     * @param callable $matcher
     * @param array $seen
     * @return Page[]
     */
    function cms_collect_listing_matches(Page $page, callable $matcher, array &$seen)
    {
        $children = $page->get_subs(PHP_INT_MAX, "order", "ASC", false, true);

        $child_results = [];
        foreach ($children as $child) {
        $child_results = array_merge($child_results, cms_collect_listing_matches($child, $matcher, $seen));
    }

    $result = [];
    if ($matcher($page) && !isset($seen[$page->id])) {
        $result[] = $page;
        $seen[$page->id] = true;
    }

    return array_merge($result, $child_results);
}
}

$listing_page_logic = json_decode($p->logic, true);

// LIMIT
$limits = array(20,50,0);
if ( isset($listing_page_logic['limits']) && !empty($listing_page_logic['limits']) ) {
    $decoded = json_decode($listing_page_logic['limits']);
    if ( $decoded !== false ) {
        $limits = $decoded;
    }
}
$limit = $limits[0];
if ( isset($_GET['limit']) ) {
    $limit = $_GET['limit'];
}

// ORDER
$default_admin_listing_order = array("`order`");
if ( isset($listing_page_logic['default_admin_listing_order']) && !empty($listing_page_logic['default_admin_listing_order']) ) {
    $decoded = json_decode($listing_page_logic['default_admin_listing_order']);
    if ( $decoded !== false ) {
        $default_admin_listing_order = $decoded;
    }
}
$order = $default_admin_listing_order;
if ( isset($_GET['order']) ) {
    $order = $_GET['order'];
}

// COLUMNS
$columns = array("`title`","`updated`");
if ( isset($listing_page_logic['columns']) && !empty($listing_page_logic['columns']) ) {
    $decoded = json_decode($listing_page_logic['columns']);
    if ( $decoded !== false ) {
        $columns = $decoded;
    }
}

$date_value = array();
if ( isset($listing_page_logic['date_value']) && !empty($listing_page_logic['date_value']) ) {
    $decoded = json_decode($listing_page_logic['date_value']);
    if ( $decoded !== false ) {
        $date_value = $decoded;
    }
}

$adv_filter = [];
if (!empty($_GET['adv_filter'])) {
    $adv_filter = $_GET['adv_filter'];
}

// LISTING PAGE
$listing_page = 1;
if ( !empty($_GET['listing_page']) ) {
    $listing_page = $_GET['listing_page'];
}

// Listing Quick Search
$listing_quick_search = false;
if ( !empty($_GET['listing_quick_search']) ) {
    $listing_quick_search = $_GET['listing_quick_search'];
}

if ($listing_quick_search !== false) {
    $limit = 0;
}

$lister = Listing::newInstance($p->id)
    ->disableCache()
    ->setDebug(1)
    ;

if (defined('CMS_ROOT_PAGE_ID') && (int)$p->id === (int)CMS_ROOT_PAGE_ID) {
    $lister->includeRootOrphans();
}

if ( $limit != 0 ) {
    $lister = $lister->setLimit($limit); // set number of articles (pages) per one pagination page
}

$filter = array();

if ( !empty($date_value) && !empty($_GET['filter_from']) && !empty($_GET['filter_to']) && preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $_GET['filter_from']) && preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $_GET['filter_to']) ) {
    if ( is_array($date_value) ) {
        $filter[] = array($date_value[0],array($_GET['filter_from'], $_GET['filter_to']), "BETWEEN", "datetime");
    } else {
        $filter[] = " ".$date_value." BETWEEN ".$_GET['filter_from']." AND ".$_GET['filter_to']." ";
    }
}

foreach ($adv_filter as $pagedata_name => $pagedata) {
    if (empty($pagedata['value'])) {
        continue;
    }
    if ($pagedata['type'] === "checkbox") {
        $filter[] = array($pagedata_name, $pagedata['value'], "=", "tinyint");
    } elseif ($pagedata['type'] === "text") {
        $filter[] = array($pagedata_name, "%" . $pagedata['value'] . "%", "LIKE", "varchar");
    } elseif ($pagedata['type'] === "select") {
        $filter[] = array($pagedata_name, $pagedata['value'], "=", "varchar");
    }
}

if ( !empty($filter) ) {
    $lister = $lister->setFilter($filter);
}

$lister = $lister->setCurrentPage($listing_page)         // pass page number (its safe to pass unset vars)
    ->setGetParams(array("pagination"=>"listing_page"))
    ->onlyPublished( false )
    ;

if ( !empty($order) ) {
    $lister->setOrder($order);                      // order by date descending which is to be treated as type datetime
}

if ( !empty($select) ) {
    $lister->setSelect($select);
}

$drag_and_drop_order = true;
if ( !empty($filter) || $order != array("`order`") ) {
    $drag_and_drop_order = false;
}

$lister->run();                                     // before getting anything - one needs to "run()" this whole setup

?>

<table class="manage-items">
    <tr>
        <th class="center"></th>
        <th class="">ID</th>
        <?php
        if ( $drag_and_drop_order === true ) {
            ?>
            <th class=""></th>
            <?php
        }
        if ( !empty($columns) ) {

            for ($i=0; $i < count($columns); $i++) {
                if ( !is_array($columns[$i]) ) {
                    $data_name = $columns[$i];
                } elseif (isset($columns[$i][0]) && is_array($columns[$i][0])) {
                    $data_name = $columns[$i][0][2];
                } else {
                    $data_name = $columns[$i][0];
                }
                echo "<th>".ucwords(str_replace("`", "", $data_name))."</th>";
            }
        }
        ?>
        <th class="">URL</th>
        <th class="">Function</th>
        <th class="center">Edit</th>
        <th class="center">Delete</th>
    </tr>
    <tbody class="tabular  <?=( $drag_and_drop_order === true ? 'dragAndDropOrder' : '' )?>">
    <?php

$lister->getListing();

$render_list = [];

$has_additional_filters = !empty($filter);

if ($listing_quick_search !== false) {
    $search_term = mb_strtolower($listing_quick_search);
    $matcher = function(Page $page) use ($search_term) {
        $title = mb_strtolower((string)$page->title);
        $slug = mb_strtolower((string)$page->slug);
        return (
            $search_term === '' ||
            strpos($title, $search_term) !== false ||
            strpos($slug, $search_term) !== false
        );
    };

    $seen = [];
    foreach ($lister->list as $parent) {
        $matches = cms_collect_listing_matches($parent, $matcher, $seen);
        if (!empty($matches)) {
            $render_list = array_merge($render_list, $matches);
        }
    }
} elseif ($has_additional_filters) {
    $render_list = $lister->list;
} else {
    foreach ($lister->list as $parent) {
        $render_list = array_merge($render_list, cms_flatten_listing_page_tree($parent));
    }
}

    $i=0;
    foreach ( $render_list as $listing_item ) {
        $item_path_segments = array_filter(explode('/', trim($listing_item->path, '/')));
        $container_path_segments = array_filter(explode('/', trim($p->path, '/')));
        $indent_level = max(0, count($item_path_segments) - count($container_path_segments) - 1);
        $indent_padding = $indent_level * 20;
        ?>
        <tr id="rorder-<?=$listing_item->id;?>" class="listedPage<?= $indent_level > 0 ? ' listedPage--child listedPage--depth-' . $indent_level : '' ?>" data-page-id="<?= $listing_item->id ?>">
            <td class="center">
                <input type="checkbox" name="bulk_selection_page_ids[]" value="<?= $listing_item->id ?>" />
            </td>
            <td class="">
                <?= $listing_item->id ?>
            </td>
            <?php
            if ( $drag_and_drop_order === true ) {
                ?>
                <td class="" style="padding-top: 11px">
                    <span class="orderHandle">
                        <i class="fa fa-ellipsis-v"></i>
                    </span>
                </td>
                <?php
            }

            if ( !empty($columns) ) {
                for ($i=0; $i < count($columns); $i++) {

                    $offset = 0;

                    // if its not an array. just append it and continue
                    if ( !is_array($columns[$i]) ) {

                        $attr = str_replace("`", "", $columns[$i]);
                        echo "<td>";
                        if ( $attr === "title" ) {
                            echo '<span class="listingPageTitle" data-indent-level="'.$indent_level.'" style="display:inline-block;padding-left:'.$indent_padding.'px;">';
                            if ($indent_level > 0) {
                                echo '<i class="fa fa-level-up fa-rotate-90 listingPageTitle__connector"></i> ';
                            }
                            if ( $listing_item->published == 0 ) {
                                echo "(Draft) ";
                            }
                            if ( isset($listing_item->{$attr}) ) {
                                echo clean_page($listing_item->{$attr});
                            }
                            echo '</span>';
                        } elseif ( isset($listing_item->{$attr}) ) {
                            echo clean_page($listing_item->{$attr});
                        }
                        echo "</td>";
                    } elseif (isset($columns[$i][0]) && is_array($columns[$i][0])) {
                        echo "<td>";
                        if (isset($listing_item->pagedata[$columns[$i][0][0]][$columns[$i][0][1]][$columns[$i][0][2]]['value'])) {
                            echo $listing_item->pagedata[$columns[$i][0][0]][$columns[$i][0][1]][$columns[$i][0][2]]['value'];
                        }
                        echo "</td>";
                    } else {
                        echo "<td>";
                        if (isset($listing_item->pagedata[$columns[$i][0]][0]['value'])) {
                            echo clean_page($listing_item->pagedata[$columns[$i][0]][0]['value']);
                        }
                        echo "</td>";

                    }
                }
            }
            ?>
            <td class=""><?= $listing_item->path ?></td>
            <td class="">
                <?php if ($listing_item->listing_container): ?>
                    <a
                        href="?page=<?=$listing_item->id?>#tab=2"
                        class="edit picto" data-page-id="<?=$listing_item->id?>"
                    >
                        <i class="fa fa-list"></i>
                    </a>
                <?php endif ?>
                <?= ($listing_item->frontpage ? '<i class="fa fa-home"></i>' : '') ?>
                <?= ($listing_item->contact_page ? '<i class="fa fa-map-marker"></i>' : '') ?>
            </td>
            <td class="center">
                <a
                    href="?page=<?=$listing_item->id?>#tab=1"
                    class="edit picto" data-page-id="<?=$listing_item->id?>"
                >
                    <i class="fa fa-pencil"></i>
                </a>
            </td>
            <td class="center">
                <a
                    href="?delete=true&page=<?=$listing_item->id?>"
                    class=" picto error delete" data-page-id="<?=$listing_item->id?>"
                    data-page-title="<?=$listing_item->title?>"
                    title="Delete '<?=addslashes($listing_item->title)?>'?"
                >
                    <i class="fa fa-times-circle"></i>
                </a>
            </td>
        </tr>
        <?php
        $i++;
    }

    if (empty($lister->list)) {
        ?>
        <tr>
            <td class="center" colspan="100">Nothing to display.</td>
        </tr>
        <?php
    }
    ?>
    </tbody>
</table>

<?php

$lister->getPagination($twig);

$options = array(
    'container_class' => 'pagination',
    'active_page_id' => $listing_page
);

echo CMSNav::generateMenu($lister->generatePaginationTree(), $options);
