<?php 

class sorting extends Exception {
	
	public $total_pages;
	public $sorted = false;

	public function __construct()
	{
		
	}

	public function asort_by_meta_value($array, $sort_by = 'title', $order = SORT_ASC) {
		$sort_config = array();
		if(_count($sort_by)) {
			foreach ($sort_by as $key => $_sort_by) {
				$column = array_column($array, $_sort_by);
				array_push($sort_config, $column);
				if(_count($order)) {
					if(isset($order[$key])) {
						array_push($sort_config, $order[$key]);
					} else {
						array_push($sort_config, $order[0]);
					}
				} else {
					array_push($sort_config, $order);
				}
			}
		} else {
			$column = array_column($array, $sort_by);
			array_push($sort_config, $column);
			if(_count($order)) {
				array_push($sort_config, $order[0]);
			} else array_push($sort_config, $order);
		}
		array_push($sort_config, $array);
		array_multisort(...$sort_config);
		$this->sorted = $array;
		return $this->sorted;
	}

	public function sort_by_meta_value($array, $sort_by = 'title', $order = 'asc') {
		$temp_memory = array();
		$sorted = array();
		if(empty($array))
			return $sorted;
		foreach ($array as $key => $value) {
			if(is_array($value) && isset($value[$sort_by])) {
				$temp_memory[$key] = strtolower($value[$sort_by]);
			} else {
				if(strtolower($order) == 'asc') :
					asort($array);
				endif;
				if(strtolower($order) == 'desc') :
					arsort($array);
				endif;
				return $array;
			}
		}
		if(strtolower($order) == 'asc') :
			asort($temp_memory);
		endif;
		if(strtolower($order) == 'desc') :
			arsort($temp_memory);
		endif;
		foreach ($temp_memory as $key => $value) {
			$sorted[$key] = $array[$key];
		}
		$sorted = array_values($sorted);
		return $sorted; 
	}

	public function paginate($array, $limit = 5, $page = 1) {
		$paginated = array_chunk($array, $limit);
		if($page > _count($paginated)) {
			$page = _count($paginated);
		}
		$this->total_pages = _count($paginated);
		return $paginated[$page-1];
	}

	public function reset_index($array) {
		$result = array();
		if(_count($array) > 0) {
			foreach ($array as $key => $value) {
				$result[] = $value;
			}
		}
		return $result;
	}
}