<?php
  /**
   * Helper
   *
   * @package Wojo Framework
   * @author wojoscripts.com
   * @copyright 2017
   * @version $Id: helper.php, v1.00 2017-08-05 10:12:05 gewa Exp $
   */
  define("_WOJO", true);
  require_once("../../init.php");
	  
  if (!App::Auth()->is_Admin())
      exit;

  /* == Post Actions== */
  if (isset($_POST['processItem'])):
	  switch ($_POST['page']) :
		  /* == Update Role Description == */
		  case "editRole":
			  App::Users()->updateRoleDescription();
		  break;  
		  /* == Rename File == */
		  case "renameFile":
			  App::Product()->renameFile();
		  break;
      endswitch;
  endif;
  
    
  /* == Get Actions== */
  if (isset($_GET['action'])):
      switch ($_GET['page']):
          /* == Edit Role == */
          case "editRole":
			  $tpl = App::View(BASEPATH . 'view/admin/snippets/'); 
			  $tpl->data = Db::run()->first(Users::rTable, null, array('id' => Filter::$id));
			  $tpl->template = 'editRole.tpl.php'; 
			  echo $tpl->render(); 
          break;
          /* == Load Language Section == */
          case "loadLanguageSection":
			  $xmlel = simplexml_load_file(BASEPATH . Lang::langdir . Core::$language . ".lang.xml");
			  $section = $xmlel->xpath('/language/phrase[@section="' . Validator::sanitize($_GET['section']) . '"]');
			  $tpl = App::View(BASEPATH . 'view/admin/snippets/'); 
			  $tpl->xmlel = $xmlel;
			  $tpl->section = $section;
			  $tpl->template = 'loadLanguageSection.tpl.php'; 
			  $json['html'] = $tpl->render(); 
			  print json_encode($json);
          break;
              /* == Get Content Type == */
          case "contenttype":
              $type = Validator::sanitize($_GET['type'], "alpha");
              $html = '';
              if ($type == "page"):
                  $data = Db::run()->select(Content::pTable, array("id", "title"), array("active" => 1), "ORDER BY title ASC")->results();
                  if ($data):
                      foreach ($data as $row):
                          $html .= "<option value=\"" . $row->id . "\">" . $row->title . "</option>\n";
                      endforeach;
                      $json['type'] = 'page';
                  endif;

              else:
                  $json['type'] = 'web';
              endif;
                  $json['message'] = $html;
                  print json_encode($json);
          break;
		  /* == Item Chart == */
		  case "itemChart":
			  $data = Stats::itemChart(Filter::$id);
			  print json_encode($data);
		  break;
          /* == Rename File == */
          case "renameFile":
			  $tpl = App::View(BASEPATH . 'view/admin/snippets/'); 
			  $tpl->template = 'renameFile.tpl.php'; 
			  $tpl->data = Db::run()->first(Product::fTable, array("alias"), array('id' => Filter::$id));
			  echo $tpl->render(); 
          break;
		  /* == Site Sales Chart == */
		  case "salesChart":
			  $data = Stats::getAllSalesStats();
			  print json_encode($data);
		  break;
      endswitch;
  endif;


  /* == Quick Actions == */
  if (isset($_POST['qAction'])):
      switch ($_POST['page']) :
          /* == Sort Menus == */
          case "sortMenus":
              $jsonstring = $_POST['sorting'];
			  $jsonDecoded = json_decode($jsonstring, true, 12);
			  $result = Utility::parseJsonArray($jsonDecoded);
			  
			  $i = 0;
			  $query = "UPDATE `" . Content::mTable . "` SET `sorting` = CASE ";
			  $idlist = '';
			  foreach ($result as $item):
				  $i++;
				  $query .= " WHEN id = " . $item['id'] . " THEN " . $i . " ";
				  $idlist .= $item['id'] . ',';
			  endforeach;
			  $idlist = substr($idlist, 0, -1);
			  $query .= "
					  END
					  WHERE id IN (" . $idlist . ")";
			  Db::run()->pdoQuery($query);
          break;
          /* == Sort Categories == */
          case "sortCategories":
			  $jsonstring = $_POST['sortlist'];
			  $jsonDecoded = json_decode($jsonstring, true, 12);
			  $result = Utility::parseJsonArray($jsonDecoded);
			  $i = 0;
			  foreach ($result as $item):
				  if (is_array($item)):
					  $i++;
					  $data = array('sorting' => $i, 'parent_id' => $item['parent_id']);
					  Db::run()->update(Content::cTable, $data, array('id' => $item['id']));
				  endif;
			  endforeach; 
          break;
          /* == Sort Custom Fields == */
          case "sortFields":
			  $i = 0;
			  $query = "UPDATE `" . Content::cfTable . "` SET `sorting` = CASE ";
			  $idlist = '';
			  foreach ($_POST['sortlist'] as $item):
				  $i++;
				  $query .= " WHEN id = " . $item . " THEN " . $i . " ";
				  $idlist .= $item . ',';
			  endforeach;
			  $idlist = substr($idlist, 0, -1);
			  $query .= "
					  END
					  WHERE id IN (" . $idlist . ")";
			  Db::run()->pdoQuery($query);
          break;
          /* == Sort FAQ == */
          case "sortFaq":
			  $i = 0;
			  $query = "UPDATE `" . Content::fTable . "` SET `sorting` = CASE ";
			  $idlist = '';
			  foreach ($_POST['sortlist'] as $item):
				  $i++;
				  $query .= " WHEN id = " . $item . " THEN " . $i . " ";
				  $idlist .= $item . ',';
			  endforeach;
			  $idlist = substr($idlist, 0, -1);
			  $query .= "
					  END
					  WHERE id IN (" . $idlist . ")";
			  Db::run()->pdoQuery($query);
          break;

		  /* == Comment Approve == */
		  case "commentApprove":
			  if(Db::run()->update(Comments::mTable, array("active" => 1), array("id" => Filter::$id))):
				  $json['type'] = "success";
				  print json_encode($json);
			  endif;
		  break; 
		  
          /* == Process Images == */
		  case "processImages":
			  $num_files = count($_FILES['images']['tmp_name']);
			  $filedir = UPLOADS . Product::DATA . Filter::$id;
			  File::makeDirectory($filedir . '/thumbs');
			  
			  for ($x = 0; $x < $num_files; $x++):
				  $image = $_FILES['images']['name'][$x];
				  $newName = "IMG_" . Utility::randomString(12);
				  $ext = substr($image, strrpos($image, '.') + 1);
				  $name = $newName . "." . strtolower($ext);
				  $fullname = $filedir . '/' . $name;
				  
				  if (!move_uploaded_file($_FILES['images']['tmp_name'][$x], $fullname)) {
					  die(Message::msgSingleError(Lang::$word->FU_ERROR13, false));
				  }
	
				  try {
					  $img = new Image($filedir . '/' . $name);
					  $img->bestFit(App::Core()->thumb_w, App::Core()->thumb_h)->save($filedir . '/thumbs/' . $name);
				  } catch(Exception $e) {
					  echo 'Error: ' . $e->getMessage();
				  }
				  
				  $last_id = Db::run()->insert(Product::iTable, array("parent_id" => Filter::$id, "name" => $name))->getLastInsertId();

				  print '
				  <div class="column" id="item_' . $last_id . '" data-id="' . $last_id . '">
					<div class="wojo basic attached segment"><img src="' . Product::hasThumb($name, Filter::$id) . '" alt="" class="wojo boxed image"><a data-set=\'{"option":[{"delete":"deleteImage", "id":' . $last_id . '}], "url":"/controller.php", "parent":"#item_' . $last_id . '", "complete":"remove"}\' class="wojo top right small basic icon attached label qAction"><i class="icon trash negative"></i></a>
					</div>
				  </div>';
			  endfor;
		  break;
              /* == File Upload == */
          case "fileUpload":
			  if (!empty($_FILES['file']['name'])):
				  $upl = Upload::instance(Product::FS, Product::FE);
				  $upl->process("file", App::Core()->file_dir, 'File_');
				  if (empty(Message::$msgs)):
					  $data = array(
						  'alias' => $upl->fileInfo['name'],
						  'name' => $upl->fileInfo['fname'],
						  'filesize' => $upl->fileInfo['size'],
						  'extension' => $upl->fileInfo['ext'],
						  'type' => $upl->fileInfo['type_short'],
						  'token' => Utility::randomString(32),
						  );
						  
					  $last_id = Db::run()->insert(Product::fTable, $data)->getLastInsertId(); 
					  $tpl = App::View(BASEPATH . 'view/admin/snippets/');
					  $tpl->row = Db::run()->first(Product::fTable, null, array('id' => $last_id)); 
					  $tpl->template = 'loadFile.tpl.php'; 
			  
					  $json['type'] = "success";
					  $json['filecolor'] = Product::fileStyle($upl->fileInfo['ext']);
					  $json['filetype'] = Product::fileIcon($upl->fileInfo['ext'], "");
					  $json['id'] = $last_id;
					  $json['html'] = $tpl->render();
				  else:
					  $json['type'] = "error";
					  $json['message'] = Message::$msgs['name'];
				  endif;
				  print json_encode($json);
			  endif;
          break;
		  /* == Database Backup == */
          case "databaseBackup":
              dbTools::doBackup();
          break;
		  /* == Restore Menu == */
		  case "restoreMenu":
			  if($result = Db::run()->first(Core::txTable, array('dataset'), array("id" => filter::$id))):
				  $array = Utility::jSonToArray($result->dataset);
				  Core::restoreFromTrash($array, Content::mTable);
				  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  endif;
		  break;
		  /* == Delete Menu == */
		  case "deleteMenu":
			  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  $json['type'] = "success";
			  print json_encode($json);
		  break; 
		  /* == Restore Page == */
		  case "restorePage":
			  if($result = Db::run()->first(Core::txTable, array('dataset'), array("id" => filter::$id))):
				  $array = Utility::jSonToArray($result->dataset);
				  Core::restoreFromTrash($array, Content::pTable);
				  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  endif;
		  break;
		  /* == Delete Page == */
		  case "deletePage":
			  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  $json['type'] = "success";
			  print json_encode($json);
		  break; 
		  /* == Restore News == */
		  case "restoreNews":
			  if($result = Db::run()->first(Core::txTable, array('dataset'), array("id" => filter::$id))):
				  $array = Utility::jSonToArray($result->dataset);
				  Core::restoreFromTrash($array, Content::nTable);
				  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  endif;
		  break;
		  /* == Delete News == */
		  case "deleteNews":
			  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  $json['type'] = "success";
			  print json_encode($json);
		  break; 
		  /* == Restore Faq == */
		  case "restoreFaq":
			  if($result = Db::run()->first(Core::txTable, array('dataset'), array("id" => filter::$id))):
				  $array = Utility::jSonToArray($result->dataset);
				  Core::restoreFromTrash($array, Content::fTable);
				  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  endif;
		  break;
		  /* == Delete Faq == */
		  case "deleteFaq":
			  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  $json['type'] = "success";
			  print json_encode($json);
		  break; 
		  /* == Restore Coupon == */
		  case "restoreCoupon":
			  if($result = Db::run()->first(Core::txTable, array('dataset'), array("id" => filter::$id))):
				  $array = Utility::jSonToArray($result->dataset);
				  Core::restoreFromTrash($array, Content::dcTable);
				  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  endif;
		  break;
		  /* == Delete Coupon == */
		  case "deleteCoupon":
			  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  $json['type'] = "success";
			  print json_encode($json);
		  break; 
		  /* == Restore Membership == */
		  case "restoreMembership":
			  if($result = Db::run()->first(Core::txTable, array('dataset'), array("id" => filter::$id))):
				  $array = Utility::jSonToArray($result->dataset);
				  Core::restoreFromTrash($array, Content::mxTable);
				  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  endif;
		  break;
		  /* == Delete Membership == */
		  case "deleteMembership":
			  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  $json['type'] = "success";
			  print json_encode($json);
		  break; 
		  /* == Restore User == */
		  case "restoreUser":
			  if($result = Db::run()->first(Core::txTable, array('dataset'), array("id" => filter::$id))):
				  $array = Utility::jSonToArray($result->dataset);
				  Core::restoreFromTrash($array, Users::mTable);
				  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  endif;
		  break;
		  /* == Delete User == */
		  case "deleteUser":
			  Db::run()->delete(Core::txTable, array("id" => filter::$id));
			  $json['type'] = "success";
			  print json_encode($json);
		  break; 
      endswitch;
  endif;

  /* == Quick Edit == */
  if (isset($_POST['quickedit'])):
      $title = Validator::cleanOut($_POST['title']);
      $title = Validator::sanitize($title);
      switch ($_POST['type']) :
          /* == Update Language Phrase == */
          case "phrase":
			  if (file_exists(BASEPATH . Lang::langdir . Core::$language . ".lang.xml")):
				  $xmlel = simplexml_load_file(BASEPATH . Lang::langdir . Core::$language . ".lang.xml");
				  $node = $xmlel->xpath("/language/phrase[@data = '" . $_POST['key'] . "']");
				  $node[0][0] = $title;
				  $xmlel->asXML(BASEPATH . Lang::langdir . Core::$language . ".lang.xml");
			  endif;
              break;  
          /* == Update Country Vat == */
          case "tax":
              if (empty($_POST['title'])):
                  print '0.00';
                  exit;
              endif;
              if ($vat = Validator::sanitize($title, "float")):
				  Db::run()->update(Content::cnTable, array("vat" => $vat), array('id' => Filter::$id));
              endif;
          break;
      endswitch;
	  $json['title'] = $title;
	  print json_encode($json);
  endif;
  
  /* == Quick Status == */
  if (Validator::post('quickStatus')):
      switch ($_POST['action']) :
          /* == Roles == */
          case "role":
		      if(Auth::checkAcl("owner")):
			      Db::run()->update(Users::rpTable, array("active" => intval($_POST['active'])), array("id" => Filter::$id));
			  endif;
          break;
          /* == Gateway == */
          case "gateway":
		      Db::run()->update(Admin::gTable, array("active" => intval($_POST['active'])), array("id" => Filter::$id));
          break;
          /* == Coupons == */
          case "coupon":
		      Db::run()->update(Content::dcTable, array("active" => intval($_POST['active'])), array("id" => Filter::$id));
          break;
      endswitch;
  endif;

  /* == Export Item Payments == */
  if (isset($_GET['itemPayments'])):
	  header("Pragma: no-cache");
	  header('Content-Type: text/csv; charset=utf-8');
	  header('Content-Disposition: attachment; filename=ItemPayments.csv');
	  
	  $data = fopen('php://output', 'w');
	  fputcsv($data, array('TXN ID', 'User', 'Amount', 'TAX/VAT', 'Coupon', 'Total Amount', 'Currency', 'Processor', 'Created'));
	  
	  $result = Stats::itemPayments(Filter::$id);
	  if($result):
		  foreach ($result as $row) :
			  fputcsv($data, $row);
		  endforeach;
		  fclose($data);
	  endif;
  endif;
  
  /* == Export User Payments == */
  if (isset($_GET['exportUserProductPayments'])):
      header("Pragma: no-cache");
	  header('Content-Type: text/csv; charset=utf-8');
	  header('Content-Disposition: attachment; filename=UserPayments.csv');
	  
	  $data = fopen('php://output', 'w');
	  fputcsv($data, array('TXN ID', 'User', 'Item', 'Coupon', 'TAX/VAT', 'Amount', 'Processor', 'Currency', 'IP', 'Status', 'Created'));
	  
	  $result = Stats::exportProductPayments(Filter::$id);
	  if($result):
		  foreach ($result as $row) :
			  fputcsv($data, $row);
		  endforeach;
	  endif;
  endif;
  
  /* == User Payments Chart == */
  if (isset($_GET['getUserProductPaymentsChart'])):
      $data = Stats::getUserProductPaymentsChart(Filter::$id);
	  print json_encode($data);
  endif;
  
  /* == Export Users == */
  if (isset($_GET['exportUsers'])):
      header("Pragma: no-cache");
	  header('Content-Type: text/csv; charset=utf-8');
	  header('Content-Disposition: attachment; filename=UserList.csv');
	  
	  $data = fopen('php://output', 'w');
	  fputcsv($data, array('Name', 'Membership', 'Expire', 'Email', 'Newsletter', 'Created'));
	  
	  $result = Stats::exportUsers();
	  if($result):
		  foreach ($result as $row) :
			  fputcsv($data, $row);
		  endforeach;
	  endif;
  endif;

   /* == Membership Payments Chart == */
  if (isset($_GET['getMembershipPaymentsChart'])):
      $data = Stats::getMembershipPaymentsChart(Filter::$id);
	  print json_encode($data);
  endif;

   /* == Index Payments Chart == */
  if (isset($_GET['getIndexStats'])):
      $data = Stats::indexSalesStats();
	  print json_encode($data);
  endif;

  /* == Main Membership Chart == */
  if (isset($_GET['getMainMembershipStats'])):
      $data = Stats::getMainMembershipStats();
	  print json_encode($data);
  endif;
   /* == Export Membership Payments == */
  if (isset($_GET['exportMembershipPayments'])):
      header("Pragma: no-cache");
	  header('Content-Type: text/csv; charset=utf-8');
	  header('Content-Disposition: attachment; filename=MembershipPayments.csv');
	  
	  $data = fopen('php://output', 'w');
	  fputcsv($data, array('TXN ID', 'User', 'Amount', 'TAX/VAT', 'Coupon', 'Total Amount', 'Currency', 'Processor', 'Created'));
	  
	  $result = Stats::exportMembershipPayments(Filter::$id);
	  if($result):
		  foreach ($result as $row) :
			  fputcsv($data, $row);
		  endforeach;
	  endif;
  endif;
  
  /* == Export All Payments == */
  if (isset($_GET['exportAllTransactions'])):
      header("Pragma: no-cache");
	  header('Content-Type: text/csv; charset=utf-8');
	  header('Content-Disposition: attachment; filename=AllPayments.csv');
	  
	  $data = fopen('php://output', 'w');
	  fputcsv($data, array('TXN ID', 'Item', 'User', 'Amount', 'TAX/VAT', 'Coupon', 'Total Amount', 'Currency', 'Processor', 'Created'));
	  
	  $result = Stats::exportAllTransactions();
	  if($result):
		  foreach ($result as $row) :
			  fputcsv($data, $row);
		  endforeach;
	  endif;
  endif;

  /* == Search == */
  if (isset($_GET['liveSearch'])):
      $string = Validator::sanitize($_GET['value'], 'string', 15);
	  switch ($_GET['type']) :
		  /* == Pages == */
		  case "pages":
			  $sql = "
				SELECT 
				  id,
				  title
				FROM
				  `" . Content::pTable . "`
				WHERE title LIKE '%" . $string . "%'
				OR body LIKE '%" . $string . "%'
				ORDER BY title 
				LIMIT 10;";

			  $html = '';
			  if ($result = Db::run()->pdoQuery($sql)->results()):
				  $html .= '<table class="wojo basic dashed table">';
				  foreach ($result as $row):
					  $link = Url::url("/admin/pages/edit", $row->id);
					  $html .= '<tr>';
					  $html .= '<td>';
					  $html .= '<span class="wojo basic disabled label">' . $row->id . '</span>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= '<a href="' . $link . '" class="white">' . $row->title . '</a>';
					  $html .= '</td>';
					  $html .= '</tr>';
				  endforeach;
				  $html .= '</table>';
				  $json['html'] = $html;
				  $json['status'] = 'success';
			  else:
				  $json['status'] = 'error';
			  endif;
			  print json_encode($json);
		  break;  
		  /* == User == */
          case "users":
			  $sql = "
				SELECT 
				  id,
				  email,
				  CONCAT(fname, ' ', lname) AS name
				FROM
				  `" . Users::mTable . "`
				WHERE MATCH (fname) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
				OR MATCH (lname) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
				OR MATCH (email) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
				ORDER BY fname
				LIMIT 10 ";

			  $html = '';
			  if ($result = Db::run()->pdoQuery($sql)->results()):
				  $html .= '<table class="wojo basic dashed table">';
				  foreach ($result as $row):
					  $link = Url::url("/admin/users/edit", $row->id);
					  $history = Url::url("/admin/users/history", $row->id);
					  $email = Url::url("/admin/mailer", "?email=" . urlencode($row->email));
					  $html .= '<tr>';
					  $html .= '<td>';
					  $html .= '<span class="wojo basic disabled label">' . $row->id . '</span>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= '<a href="' . $link . '" class="white">' . $row->name . '</a>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= '<a href="' . $email . '" class="white">' . $row->email . '</a>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= '<a href="' . $history . '" class="white"><i class="icon large money bag"></i></a>';
					  $html .= '</td>';
					  $html .= '</tr>';
				  endforeach;
				  $html .= '</table>';
				  $json['html'] = $html;
				  $json['status'] = 'success';
			  else:
				  $json['status'] = 'error';
			  endif;
			  print json_encode($json);
          break;
		  /* == Products == */
          case "products":
			  $sql = "
				SELECT 
				  id,
				  title
				FROM
				  `" . Product::mTable . "`
				WHERE MATCH (title) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
				ORDER BY title
				LIMIT 10;";

			  $html = '';
			  if ($result = Db::run()->pdoQuery($sql)->results()):
				  $html .= '<table class="wojo basic dashed table">';
				  foreach ($result as $row):
					  $link = Url::url("/admin/products/edit", $row->id);
					  $history = Url::url("/admin/products/history", $row->id);
					  $html .= '<tr>';
					  $html .= '<td>';
					  $html .= '<span class="wojo basic disabled label">' . $row->id . '</span>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= '<a href="' . $link . '" class="white">' . $row->title . '</a>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= '<a href="' . $history . '" class="white"><i class="icon large money bag"></i></a>';
					  $html .= '</td>';
					  $html .= '</tr>';
				  endforeach;
				  $html .= '</table>';
				  $json['html'] = $html;
				  $json['status'] = 'success';
			  else:
				  $json['status'] = 'error';
			  endif;
			  print json_encode($json);
          break;
		  /* == Transactions == */
          case "transactions":
			  $sql = "
			  SELECT 
				p.id,
				p.created,
				m.title,
				CONCAT(u.fname,' ',u.lname) as name
			  FROM `" . Product::xTable . "` as p 
				LEFT JOIN " . Users::mTable . " AS u 
				  ON p.user_id = u.id
				LEFT JOIN " . Product::mTable . " AS m 
				  ON p.product_id = m.id
				WHERE MATCH (u.fname) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
				OR MATCH (u.lname) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
				OR MATCH (m.title) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
			  ORDER BY p.created DESC LIMIT 10";

			  $html = '';
			  if ($result = Db::run()->pdoQuery($sql)->results()):
				  $html .= '<table class="wojo basic dashed table">';
				  foreach ($result as $row):
					  $html .= '<tr>';
					  $html .= '<td>';
					  $html .= '<span class="wojo basic disabled label">' . $row->id . '</span>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= $row->title;
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= $row->name;
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= Date::doDate("short_date", $row->created);
					  $html .= '</td>';
					  $html .= '</tr>';
				  endforeach;
				  $html .= '</table>';
				  $json['html'] = $html;
				  $json['status'] = 'success';
			  else:
				  $json['status'] = 'error';
			  endif;
			  print json_encode($json);
          break;
		  /* == Files == */
          case "files":
			  $sql = "
				SELECT 
				  id,
				  alias,
				  name,
				  type,
				  filesize
				FROM
				  `" . Product::fTable . "`
				WHERE MATCH (alias) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
				OR MATCH (name) AGAINST ('" . $string . "*' IN BOOLEAN MODE)
				ORDER BY alias
				LIMIT 10 ";

			  $html = '';
			  if ($result = Db::run()->pdoQuery($sql)->results()):
				  $html .= '<table class="wojo basic dashed table">';
				  foreach ($result as $row):
					  $link = Url::url("/admin/products/new", "?file=" . $row->id);
					  $html .= '<tr>';
					  $html .= '<td>';
					  $html .= '<span class="wojo basic disabled label">' . $row->id . '</span>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= '<a href="' . $link . '" class="white">' . $row->alias . '</a>';
					  $html .= '</td>';
					  $html .= '<td class="wojo large text">';
					  $html .= $row->name;
					  $html .= '</td>';
					  $html .= '<td>';
					  $html .= Product::fileIcon($row->type, "large");
					  $html .= '</td>';
					  $html .= '</tr>';
				  endforeach;
				  $html .= '</table>';
				  $json['html'] = $html;
				  $json['status'] = 'success';
			  else:
				  $json['status'] = 'error';
			  endif;
			  print json_encode($json);
          break;
      endswitch;
  endif;
  
  /* == Clear Session Temp Queries == */
  if (isset($_GET['ClearSessionQueries'])):
      App::Session()->remove('debug-queries');
	  App::Session()->remove('debug-warnings');
	  App::Session()->remove('debug-errors');
	  print 1;
  endif;