<?php

/**
 * [BEGIN_COT_EXT]
 * Hooks=tools
 * [END_COT_EXT]
 */

defined('COT_CODE') or die('Wrong URL.');

require_once cot_incfile('rewards', 'plug');

$a = cot_import('a', 'G', 'TXT');

if($a == 'create')
{
 $rtitle = cot_import('rtitle', 'P', 'TXT');
 $rdesc = cot_import('rdesc', 'P', 'TXT');

 cot_check(empty($rtitle), 'Укажите название награды', 'rtitle');

 if(!cot_error_found())
 {
   $db->insert($db_rewards, array('r_title' => $rtitle, 'r_desc' => $rdesc));
   $rid = $db->lastInsertId();

   if ($rid > 0 && $_FILES)
   {
    require_once cot_incfile('uploads');

  	@clearstatcache();
  	$file = $_FILES['rfile'];
  	if (!empty($file['tmp_name']) && $file['size'] > 0 && is_uploaded_file($file['tmp_name']))
  	{
  		$var = explode(".", $file['name']);
  		$file_ext = strtolower(array_pop($var));
  		$fcheck = cot_file_check($file['tmp_name'], $file['name'], $file_ext);
  		if (in_array($file_ext, array('png', 'PNG')) && $fcheck == 1)
  		{
  			$file['name'] = cot_safename($file['name'], true);
  			$filename_full = $rid.'.png';
  			$filepath = $rewards_path . $filename_full;

  			if (file_exists($filepath)) unlink($filepath);

  			move_uploaded_file($file['tmp_name'], $filepath);
  			@chmod($filepath, $cfg['file_perms']);
  		}
    } else {
      cot_check(true, 'Изображение не удалось загрузить', '');
    }
   }
 }
 cot_redirect(cot_url('admin', 'm=other&p=rewards', '', true));
}
elseif($a == 'save')
{
 $rid = cot_import('id', 'G', 'INT');

 if($rid > 0)
 {
   $rtitle = cot_import('rtitle', 'P', 'TXT');
   $rdesc = cot_import('rdesc', 'P', 'TXT');

   $updata = array(
    'r_desc' => $rdesc
   );
   if(!empty($rtitle)) $updata['r_title'] = $rtitle;
   $db->update($db_rewards, $updata, 'r_id='.$rid);

   if ($_FILES)
   {
    require_once cot_incfile('uploads');

  	@clearstatcache();
  	$file = $_FILES['rfile'];
  	if (!empty($file['tmp_name']) && $file['size'] > 0 && is_uploaded_file($file['tmp_name']))
  	{
  		$var = explode(".", $file['name']);
  		$file_ext = strtolower(array_pop($var));
  		$fcheck = cot_file_check($file['tmp_name'], $file['name'], $file_ext);
  		if (in_array($file_ext, array('png', 'PNG')) && $fcheck == 1)
  		{
  			$file['name'] = cot_safename($file['name'], true);
  			$filename_full = $rid.'.png';
  			$filepath = $rewards_path . $filename_full;

  			if (file_exists($filepath)) unlink($filepath);

  			move_uploaded_file($file['tmp_name'], $filepath);
  			@chmod($filepath, $cfg['file_perms']);
  		}
    } else {
      cot_check(true, 'Изображение не удалось загрузить', '');
    }
   }
 }
 cot_redirect(cot_url('admin', 'm=other&p=rewards', '', true));
}
elseif($a == 'del')
{
 $id = cot_import('id', 'G', 'INT');

 $db->delete($db_rewards, 'r_id='.$id);
 $db->delete($db_rewards_owners, 'rid='.$id);
 if (file_exists($rewards_path . $id . '.png')) unlink($rewards_path . $id . '.png');

 cot_redirect(cot_url('admin', 'm=other&p=rewards', '', true));
}
elseif($a == 'delrewowner')
{
 $rid = cot_import('rid', 'G', 'INT');
 $uid = cot_import('uid', 'G', 'INT');

 if($rid > 0 && $uid > 0) $db->delete($db_rewards_owners, 'rid='.$rid.' AND uid='.$uid);

 cot_redirect(cot_url('admin', 'm=other&p=rewards', '', true));
}
elseif($a == 'newreward') {
 $rreward = cot_import('rreward', 'P', 'INT');
 $ruser = cot_import('ruser', 'P', 'INT');

 if($rreward > 0 && $ruser > 0) {
   $reward = $db->query("SELECT * FROM $db_rewards WHERE r_id=".$rreward.' LIMIT 1')->fetch();

   if($reward['r_id'] > 0) {
     $newrew = array(
      'rid' => $rreward,
      'uid' => $ruser,
      'odate' => $sys['now'],
      'oview' => 0
     );

     if($db->query("SELECT COUNT(*) FROM $db_rewards_owners WHERE rid=".$rreward.' AND uid='.$ruser)->fetchColumn() > 0) {
      cot_check(true, 'Данный пользователь уже получит эту награду', '');
     } else {
      $db->insert($db_rewards_owners, $newrew);

      /* === Hook === */
    	foreach (cot_getextplugins('reward.newreward.done') as $pl)
    	{
    		include $pl;
    	}
     	/* ===== */
     }
   }  else {
     cot_check(true, 'Произошла ошибка при добавлении награды', '');
   }
 } else {
   cot_check(true, 'Произошла ошибка при добавлении награды', '');
 }
 cot_redirect(cot_url('admin', 'm=other&p=rewards', '', true));
}

$t = new XTemplate(cot_tplfile('rewards.admin', 'plug', true));

$rewards = $db->query("SELECT * FROM $db_rewards")->fetchAll();

$rewsselect = array();

foreach($rewards as $pc)
{	
  $rewsselect[$pc['r_id']] = $pc['r_title'];
  $t->assign(array(
  	'PC_ROW_DEL_URL' => cot_url('admin', 'm=other&p=rewards&a=del&id='.$pc['r_id']),
  	'PC_ROW_ID' => $pc['r_id'],
  	'PC_ROW_TITLE' => $pc['r_title'],
  	'PC_ROW_DESC' => $pc['r_desc'],
  	'PC_ROW_IMG' => $rewards_path.(file_exists($rewards_path . $pc['r_id'] . '.png') ? $pc['r_id'] : '0').'.png',
  ));
	$t->parse('MAIN.PC_ROW');
}

$urrsselect = $db->query("SELECT user_id, user_name FROM $db_users ORDER BY user_name")->fetchAll(PDO::FETCH_KEY_PAIR);

$t->assign(array(
  'NEW_REWSELECT' => cot_selectbox('', 'rreward', array_keys($rewsselect), array_values($rewsselect), false, 'class="form-control"'),
  'NEW_URRSELECT' => cot_selectbox('', 'ruser', array_keys($urrsselect), array_values($urrsselect), false, 'class="form-control"'),
));


$rewards = $db->query("SELECT * FROM $db_rewards_owners as rewards_owners
  JOIN $db_rewards as rewards ON rewards.r_id=rewards_owners.rid
  JOIN $db_users as users ON users.user_id=rewards_owners.uid
  ORDER BY rewards_owners.odate DESC
  ")->fetchAll();

foreach($rewards as $pc)
{
  $t->assign(array(
  	'PC_ROW_DEL_URL' => cot_url('admin', 'm=other&p=rewards&a=delrewowner&rid='.$pc['rid'].'&uid='.$pc['uid']),
  	'PC_ROW_ID' => $pc['r_id'],
    'PC_ROW_DATE' => cot_date('d.m.Y H:i', $pc['odate']),
  	'PC_ROW_TITLE' => $pc['r_title'],
  	'PC_ROW_IMG' => $rewards_path.(file_exists($rewards_path . $pc['r_id'] . '.png') ? $pc['r_id'] : '0').'.png',
  ));
  $t->assign(cot_generate_usertags($pc['uid'], 'PC_ROW_USER_'));
	$t->parse('MAIN.REW_ROW');
}

cot_display_messages($t);

$t->parse('MAIN');
$adminmain = $t->text('MAIN');