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

require('classes/class.simplemodelmodulebuilder.php'); // MODEL SETTINGS
require('includes/settings.php'); // MODEL SETTINGS

$model_class_name = MODEL_CLASS_NAME;
$page_meta['title'] = 'Manage ' . ucwords(MODEL_PRULAR);

$model_manage_limit = $model_manage_limit_rows_per_page[0];
if ( isset($_GET['limit']) && is_numeric($_GET['limit']) ) {
	$model_manage_limit = $_GET['limit'];
}

$form_messages = array(
    'success' => array(),
    'error' => array(),
    'alert' => array()
);

if ( defined('MODEL_TABLE_CREATION_MODE') && MODEL_TABLE_CREATION_MODE === true ) {
    $_SESSION['model_form']['error'][] = "MODEL_TABLE_CREATION_MODE is turned on!";
}

if(isset($_POST['limit']) && is_numeric($_POST['limit'])) {
	header("Location: ".SimpleModuleModelBuilder::generateNondestructiveUrl(array('limit'=>$_POST['limit']), array('page'))); exit();
}

/*
	Order
	Assumes order is `ORDER` DESC
*/
if(!empty($_REQUEST['action']) && $_REQUEST['action']=='order') {

	$model_object = $model_class_name::find($_REQUEST['item_id']);

	if ( $model_object === null ) {
		$_SESSION['model_form']['alert'][] =  "The ".ucwords(MODEL_SINGULAR)." doesn't exist!";
		//header("Location: manage.php"); exit();
		header("Location: ".SimpleModuleModelBuilder::generateNondestructiveUrl(array(),array('action','direction','item_id'))); exit();
	}

	if ($_REQUEST['direction']=='up') {

		$order_item_above = $model_class_name::orderBy('order','asc')
							->where('id', '!=', $model_object->id)
							->where('order', '>=', $model_object->order)
							->first();

        if ( $order_item_above !== null ) {

        	$switch_order = $order_item_above->order;
        	$order_item_above->order =$model_object->order;
            $model_object->order = $switch_order;
            $model_object->save();
            $order_item_above->save();

        }

	} else {

		$order_item_below = $model_class_name::orderBy('order','desc')
							->where('id', '!=', $model_object->id)
							->where('order', '<=', $model_object->order)
							->first();

        if ( $order_item_below !== null ) {

        	$switch_order = $order_item_below->order;
        	$order_item_below->order =$model_object->order;
            $model_object->order = $switch_order;
            $model_object->save();
            $order_item_below->save();

        }

	}

	$model_list = $model_class_name::orderBy('order','desc')->get();
	$order = count($model_list);
	foreach ($model_list as $model_item) {
		$model_item->order = $order;
		$model_item->savE();
		$order--;
	}
	header("Location: ".SimpleModuleModelBuilder::generateNondestructiveUrl(array(),array('action','direction','item_id'))); exit();
	//header("Location: manage.php"); exit();
}

/*
	Delete
*/
if(!empty($_REQUEST['action']) && $_REQUEST['action']=='delete' && is_numeric($_REQUEST['delete_id'])) {
	$model_object = $model_class_name::find($_REQUEST['delete_id']);

    if ( $model_object !== null ) {
    	$_SESSION['model_form']['success'][] =  ucwords(MODEL_SINGULAR)." deleted!";
    	$model_object->delete();
    	header("Location: ".SimpleModuleModelBuilder::generateNondestructiveUrl(array(),array('action','delete_id'))); exit();
    	//header("Location: manage.php"); exit();
    } else {
    	$_SESSION['model_form']['alert'][] =  "The ".ucwords(MODEL_SINGULAR)." you wanted to delete already doesn't exist!";
    	header("Location: ".SimpleModuleModelBuilder::generateNondestructiveUrl(array(),array('action','delete_id'))); exit();
    	//header("Location: manage.php"); exit();
    }
}

/*************************************************************************************************************************************
 * 														OUTPUT
*************************************************************************************************************************************/

include($core_root_path.'admin/templates/adminheader.html.php');

?>

<!-- MODULE JS FILES -->
<script type="text/javascript" src="js/script.js"></script>
<!-- end of MODULE JS FILES -->

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <?php /* ANY PARENT PAGES */ ?>
    <li class="end"><?= $page_meta['title'] ?></li>
</ul>

<h1><?= $page_meta['title'] ?></h1>

<ul class="tabnav el">
	<li class="selected"><a href="/cms/admin/<?=MODEL_FOLDER?>/manage.php">Manage</a></li>
	<?php
	if ( MODEL_ALLOW_NEW ) {
		?>
		<li><a href="/cms/admin/<?=MODEL_FOLDER?>/edit.php">Add</a></li>
		<?php
	}
	?>
</ul>

<?php

/* ALERTS */
if ( isset($_SESSION['model_form']['success']) && !empty($_SESSION['model_form']['success']) ) {
    $form_messages['success'] = array_merge($form_messages['success'], $_SESSION['model_form']['success']);
    unset($_SESSION['model_form']['success']);
}
if ( isset($_SESSION['model_form']['error']) && !empty($_SESSION['model_form']['error']) ) {
    $form_messages['error'] = array_merge($form_messages['error'], $_SESSION['model_form']['error']);
    unset($_SESSION['model_form']['error']);
}
if ( isset($_SESSION['model_form']['alert']) && !empty($_SESSION['model_form']['alert']) ) {
    $form_messages['alert'] = array_merge($form_messages['alert'], $_SESSION['model_form']['alert']);
    unset($_SESSION['model_form']['alert']);
}

foreach ($form_messages as $class => $messages) {
    if ( empty($messages) ) {
        continue;
    }
    echo '<div class="el msg '.$class.'">';
    foreach ($messages as $message) {
        echo "<p>".$message."</p>";
    }
    echo '</div>';
}

?>

<?php
/* FILTER */
?>
<form action="<?=SimpleModuleModelBuilder::generateNondestructiveUrl()?>" method="post" class="moduleBuilder">
   <fieldset class="show">
	<div class="row">
		<select name="limit" class="modelAutoSearchLimit" class="INPUT1" style="float:right" onchange="this.form.submit()">
			<?php
			foreach ($model_manage_limit_rows_per_page as $key => $value) {
				?>
				<option value="<?=$value?>" <?=($value==$model_manage_limit?'selected':'')?>>
					<?php
					if ( $value > 0 ) {
						?>Display <?=$value?> <?=MODEL_PRULAR?> per page<?php
					} else {
						?>Display all<?php
					}
					?>
				</option>
				<?php
			}
			?>
		</select>
	</div>
	</fieldset>
</form>
<?php
/* end of FILTER */
?>

<?php

/* LIST */

$model_list_page_no = 1;
if ( isset($_GET['page']) && !empty($_GET['page']) ) {
	$model_list_page_no = $_GET['page'];
}

if ( $model_manage_limit == 0 ) {
	$model_manage_limit = PHP_INT_MAX;
}

$model_list_offset = ($model_list_page_no - 1) * $model_manage_limit;
$model_list = $model_class_name::take($model_manage_limit)->skip($model_list_offset)->orderBy($model_list_order[0],$model_list_order[1])->get();
$model_list_count = $model_class_name::count();

//$model_list_order = "order";
/*
$model_list_columns = array(
	'name' => "Name"
);
$model_list_action_columns = array(
	"Edit",
	"Delete",
);*/

if(count($model_list)>0) {
	?>
	<form action="" method="post" class="moduleBuilder">
		<table class="manage-items">
			<tr>
				<?php

				if ( in_array("Order", $model_list_action_columns) && MODEL_ORDER_COLUMN ) {
					echo '<th>&nbsp;</th>';
				}

				foreach ($model_list_columns as $key => $value) {
					$label = $value;
					if ( is_array($value) ) {
						$label = $value['label'];
					}
					echo '<th class="fieldname">'.$label.'</th>';
				}

				foreach ($model_list_action_columns as $key => $value) {
					if ( !is_array($value) ) {
						echo '<th class="center">'.$value.'</th>';
					}
					// else
				}

				?>
			</tr>
            <tbody class="tabular listTBody">
			<?php
			foreach ($model_list as $key => $model_list_item) {
				?>
				<tr id="rorder-<?=$model_list_item->id?>" style="height:45px;">
					<?php

					if ( in_array("Order", $model_list_action_columns) && MODEL_ORDER_COLUMN ) {
						echo '<td>&nbsp;<i class="fa fa-ellipsis-v"></i></td>';
					}

					foreach ($model_list_columns as $key => $model_list_column) {

						if ( is_array($model_list_column) ) {
							if ( !empty($model_list_column['type']) && $model_list_column['type'] == 'options' ||  !empty($model_list_column['type']) && $model_list_column['type'] == 'checkbox' ) {

								if ( $model_list_column['type'] == 'checkbox' && !isset($model_list_column['options']) ) {
									$model_list_column['options'] = array(0=>'No',1=>'Yes');
								}

								if ( is_array($model_list_column['options']) ) {
									$value = $model_list_column['options'][$model_list_item->{$key}];
								} else {
									// tries to fetch name
									$value = $model_list_column['options']::find($model_list_item->{$key})->name;
									// if name is null
									if ( $value === null ) {
										// fetches title
										$value = $model_list_column['options']::find($model_list_item->{$key})->title;
									}
								}
							} elseif ( !empty($model_list_column['type']) && $model_list_column['type'] == 'image' ) {
								$value = "";
								if ( !empty($model_list_item->{$key}) ) {

									$image_path = "/".$image_folders['cms_images']['small']['path']."/";
									if ( isset($model_list_column['path']) ) {
										$image_path = $model_list_column['path'];
									}

									$value = "<img
										src ='".$image_path.$model_list_item->{$key}."'
										alt=''
									/>
									";

								}
							} elseif ( !empty($model_list_column['type']) && $model_list_column['type'] == 'datetime' ) {
								$value = "";
								if ( !empty($model_list_item->{$key}) ) {
				                    $datetime = date_create_from_format('Y-m-d H:i:s', $model_list_item->{$key});
				                    $value = $datetime->format('d/m/Y H:i:s');
				                }
							} else {
								$value = $model_list_item->{$key};
							}
						} else {
							$value = $model_list_item->{$key};
						}

						echo '<td>';
							if ( is_array($model_list_column) && isset($model_list_column['link']) ) {
								$link = $model_list_column['link'];
								$link = str_replace("{id}", $model_list_item->id, $link);
								$link = str_replace("{value}", $value, $link);
								echo '<a href="'.$link.'" title="">';
							}
							echo $value;
							if ( is_array($model_list_column) && isset($model_list_column['link']) ) {
								echo '</a>';
							}
						echo '</td>';
					}
					foreach ($model_list_action_columns as $value) {
						$action = $value;
						if ( is_array($value) ) {}
						if ( $action == "Edit" ) {
							?>
							<td class="center">
								<a href="edit.php?id=<?=$model_list_item->id?>" class="edit picto" title="Edit <?=ucwords(MODEL_SINGULAR)?>">
									<i class="fa fa-pencil"></i>
								</a>
							</td>
							<?php
						} elseif ( $action == "Delete" ) {
							?>
							<td class="center">
								<a href="<?=SimpleModuleModelBuilder::generateNondestructiveUrl(array('action'=>'delete','delete_id'=>$model_list_item->id))?>" class="alert error" title="Are you sure you want to delete this?">
									<i class="fa fa-times-circle"></i>
								</a>
							</td>
							<?php
						} elseif ( $action == "Order" && MODEL_ORDER_COLUMN ) {
							?>
							<td class="center">
								<a href="<?=SimpleModuleModelBuilder::generateNondestructiveUrl(array('action'=>'order','direction'=>'up','item_id'=>$model_list_item->id))?>" class="" title="Move up.">
									<i class="fa fa-arrow-up"></i>
								</a>
								<a href="<?=SimpleModuleModelBuilder::generateNondestructiveUrl(array('action'=>'order','direction'=>'down','item_id'=>$model_list_item->id))?>" class="" title="Move down.">
									<i class="fa fa-arrow-down"></i>
								</a>
							</td>
							<?php
						}
					}
					?>
				</tr>
				<?php
			}
			?>
            </tbody>
		</table>
	</form>
	<?php
}
else {
	?>
	<p>No results to display.</p>
	<?php
}

/** PAGINATION **/

$startdots = $enddots = '<li class="dots">&hellip;</li>';
$maxPage = ceil($model_list_count/$model_manage_limit);
if ($maxPage > 1) {
    $self = $_SERVER['PHP_SELF'];
	$nav  = '';
    if ($model_list_page_no == '') {
        $model_list_page_no = 1;
    }
    if (empty($pagestoshow)) {
        $pagestoshow = 10;
    }
    $startpage = $model_list_page_no - floor($pagestoshow/2);
    if ($startpage <= 1) {
        $startpage = 1;
        $startdots = '';
    }
    $endpage = $startpage + $pagestoshow - 1;
    if ($endpage >= $maxPage) {
        $endpage = $maxPage;
        $enddots = '';
    }

	for($page = $startpage; $page <= $endpage; $page++)
	{
	   if ($page == $model_list_page_no)
	   {
		  $nav .= "<li class=\"active\"><a>".$page."</a></li>"; // no need to create a link to current page
	   }
	   else
	   {
		  //$nav .= "<li><a href=\"".$self."?page=".$page.$append."\">".$page."</a></li>";
		  $nav .= "<li><a href=\"".SimpleModuleModelBuilder::generateNondestructiveUrl(array('page'=>$page))."\">".$page."</a></li>";
	   }
	}

	// creating previous and next link
	// plus the link to go straight to
	// the first and last page

	if ($model_list_page_no > 1)
	{
	   $page  = $model_list_page_no - 1;
	  // $prev  = "<li class=\"prev\"><a href=\"".$self."?page=".$page.$append."\" rel=\"prev\">Prev</a></li>";
	   $prev  = "<li class=\"prev\"><a href=\"".SimpleModuleModelBuilder::generateNondestructiveUrl(array('page'=>$page))."\" rel=\"prev\">Prev</a></li>";

	   //$first = "<li class=\"first\"><a href=\"".$self."?page=1".$append."\">First Page</a></li>";
	   $first = "<li class=\"first\"><a href=\"".SimpleModuleModelBuilder::generateNondestructiveUrl(array('page'=>1))."\">First Page</a></li>";
	}
	else
	{
	   $prev  = ''; // we're on page one, don't print previous link
	   $first = ''; // nor the first page link
	}

	if ($model_list_page_no < $maxPage)
	{
	   $page = $model_list_page_no + 1;
	   //$next = "<li class=\"next\"><a href=\"".$self."?page=".$page.$append."\" rel=\"next\">Next</a></li>";
	   $next = "<li class=\"next\"><a href=\"".SimpleModuleModelBuilder::generateNondestructiveUrl(array('page'=>$page))."\" rel=\"next\">Next</a></li>";

	   //$last = "<li class=\"last\"><a href=\"".$self."?page=".$maxPage.$append."\">Last Page</a></li>";
	   $last = "<li class=\"last\"><a href=\"".SimpleModuleModelBuilder::generateNondestructiveUrl(array('page'=>$maxPage))."\">Last Page</a></li>";
	}
	else
	{
	   $next = ''; // we're on the last page, don't print next link
	   $last = ''; // nor the last page link
	}

	?>
	<ul class="pagination">
		<?php echo $first,$prev,$startdots,$nav,$enddots,$next,$last; ?>
	</ul>
	<?php
}

include($core_root_path.'admin/templates/adminfooter.html.php');
