<?php
use System\Check;

// View Class Instance
$view = new System\View('manage');

// include common
include('common.php');

$search = '';

if(Check::post('search') || $params['type'] == 'search'){
    $search = escapeText($_POST['search']);
    if(!$search) System\Response::redirect('/manage/links');
}


if(!$usero->isAdmin()){

$paramsArray = [
    'links' =>  
        "SELECT 
            id, 
            uid as name, 
            views, 
            status, 
            created
            FROM links
         WHERE user_id = {$usero->data()->id}", 

    'search' => 
        "SELECT 
            id, 
            uid as name, 
            views, 
            status, 
            created
            FROM links
        WHERE user_id = {$usero->data()->id} 
        AND content LIKE '%{$search}%'"
];

}else{

$paramsArray = [
'links' =>  
    "SELECT links.id, 
       links.uid as name,
       links.views,
       links.status,
       users.username as username,
       links.created
 FROM links
 LEFT JOIN users
 ON links.user_id = users.id", 

 'users' =>
    "SELECT id,
            email,
            status,
            username,
            joined as created
    FROM users",

 'payment_history' =>  
    "SELECT payment_history.id,
       payment_history.amount,
       users.username,
       payment_history.status as paid,
       payment_history.user_id,
       payment_history.created
FROM payment_history
JOIN users
ON payment_history.user_id = users.id",    

'search' => 
    "SELECT links.id, 
           links.uid as name,
           links.views,
           links.status,
           users.username as username,
           links.created
     FROM links
     LEFT JOIN users
     ON links.user_id = users.id"
];
   
}

if(!isset($paramsArray[$params['type']])) System\Response::error(404);

// settting variables
$paramType = $params['type'];
$paramQuery = $paramsArray[$paramType];

// page no
$pageNo = isset($params['page'])? str_replace('p:', '', $params['page']) : 1;
$perPage = isset($params['perpage'])? str_replace('pp:', '', $params['perpage']) : 10;

// finding next number
$nextNumber = 0; // it will be 0 by default
if($pageNo == 1 || $pageNo == 0) $nextNumber = 0;
else $nextNumber = $pageNo*$perPage-$perPage;


if($paramType == 'search'){
   $paramType = 'links';
   
   $record_type = escapeText($_POST['record_type']);
   
   if($record_type == 'links') {
	if(strpos($paramQuery, 'WHERE') !== false)
	  $paramQuery .= " OR links.uid LIKE '%{$search}%'";
	else
   	  $paramQuery .= " WHERE links.uid LIKE '%{$search}%'";
   }else{
   
   $paramType  = 'users';
   	
   	$paramQuery = "SELECT id,
            email,
            status,
            username,
            joined as created
    FROM users
    WHERE username LIKE '%{$search}%'";
   
   }
  
}

//sorting
if(isset($params['sort'])){
    $sortArray = explode(':', $params['sort']);
    $sortField = $sortArray[1];
    $sortOrder = $sortArray[2];
    $paramQuery .= ' ORDER BY '.$paramType.'.'.$sortField.' '.$sortOrder;

}else{

    $sortOrder = 'DESC';
    $sortField = 'id';

    $paramQuery .= ' ORDER BY '.$paramType.'.id DESC';
}

// adding LIMIT
$paramQuery .= ' LIMIT '.$nextNumber.', '.$perPage;

// setting parameters
$view->records = $dbo->query($paramQuery)->results(); // query results
$view->type = $paramType; // param type

// check for fields
if($firstRecord = current($view->records))
    $view->fields = array_keys(get_object_vars($firstRecord));
else $view->fields = [];

$view->sortField = $sortField;
$view->sortOrder = $sortOrder;
$view->perPage = $perPage;
$view->recordType = $paramType;
$view->currentPage = $pageNo;

if(!$usero->isAdmin())
    $view->totalFieldsCount = $dbo->getCount($paramType, $usero->data()->id);
else 
    $view->totalFieldsCount = $dbo->getCount($paramType);


$view->recordCount = count($view->records);
$view->totalPages = (int)ceil($view->totalFieldsCount/$perPage);
$view->fieldCount = count($view->fields);
$view->searchTerm = $search;

$view->showedCount = (int)$view->currentPage * (int)$view->perPage;

if($view->showedCount > $view->totalFieldsCount) $view->showedCount = $view->totalFieldsCount;


$view->title = System\Config::meta('manage')['title'];
$view->meta_desc = System\Config::meta('manage')['desc'];
$view->canonicalUrl = System\Uri::full('/manage/'.$paramType);
$view->noIndex = true;

$view->pageType = 'manage';
$data = $view->render();

echo $data;



