<?php

$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.");
}

$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'];
}

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

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

$filter = array();
if ( $listing_quick_search !== false ) {
    $filter[] = " `title` LIKE '%".CmsPdo::cleanDB($listing_quick_search)."%' ";
}

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();
    $i=0;
    foreach ( $lister->list as $listing_item ) {
        ?>
        <tr id="rorder-<?=$listing_item->id;?>" class="listedPage" 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" ) {
                            if ( $listing_item->published == 0 ) {
                                echo "(Draft) ";
                            }
                        }
                        if ( 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);
