<?php

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

$id = cot_import('id', 'G', 'INT');

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('certificates', 'any', 'RWA');
cot_block($usr['auth_write']);

/* === Hook === */
$extp = cot_getextplugins('certificates.add.first');
foreach ($extp as $pl)
{
	include $pl;
}
/* ===== */

if ($a == 'add')
{
	cot_shield_protect();

	$ritem = array();
	
	/* === Hook === */
	foreach (cot_getextplugins('certificates.add.add.first') as $pl)
	{
		include $pl;
	}
	/* ===== */

	$ritem = cot_certificates_import('POST', array(), $usr);
	
	/* === Hook === */
	foreach (cot_getextplugins('certificates.add.add.import') as $pl)
	{
		include $pl;
	}
	/* ===== */

  cot_check(empty($ritem['item_title']), 'Укажите название сертификата', 'title');

  require_once cot_incfile('uploads');

  $filefound = false;
  $file = $_FILES['certificate'];
  if (!empty($file['tmp_name']) && $file['size'] > 0 && is_uploaded_file($file['tmp_name']))
  {
  	$gd_supported = array('jpg', 'jpeg', 'png', 'gif');
  	$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, $gd_supported) && $fcheck == 1)
  	{
      $filefound = true;
  	}
  }

  cot_check(!$filefound, 'Загрузите сертификат в формате jpeg, gif или png', 'files');

  $result = array(
    'result' => 'error',
    'redirectUrl' => '',
    'errors' => array()
  );

	if (!cot_error_found())
	{
    $ritem['item_state'] = 2;
		$id = cot_certificates_add($ritem, $usr);

    $file = $_FILES['certificate'];
    $extradata = cot_import('certificate-size', 'P', 'TXT');
    $extradata = (!empty($extradata) ? json_decode($extradata,1) : array());

    if (!empty($file['tmp_name']) && $file['size'] > 0 && is_uploaded_file($file['tmp_name']))
    {
    	$gd_supported = array('jpg', 'jpeg', 'png', 'gif');
    	$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, $gd_supported) && $fcheck == 1)
    	{
    		$file['name'] = cot_safename($file['name'], true);

    		$filename_full = $id.'.'.$file_ext;
    		$filepath = 'datas/certificates/' . $filename_full;
        $filepath_crop = 'datas/certificates/crop_' . $filename_full;
        if(file_exists($filepath)) unlink($filepath);

    		move_uploaded_file($file['tmp_name'], $filepath);

    		cot_imageresize($filepath, $filepath, $cfg['certificates_sizes']['main']['w'], $cfg['certificates_sizes']['main']['h'], '', '', 100, true, $extradata);

    		@chmod($filepath, $cfg['file_perms']);

        $db->update($db_certificates, array('item_file' => $filename_full), 'item_id='.$id);
    	}
    }

		$result['result'] = 'success';
		$result['redirectUrl'] = cot_url('users', array('m' => 'details', 'id' => $usr['id'], 'u' => $usr['name'], 'tab' => 'certificates'), '', true);
	}
	else
	{
    $result['errors'] = array();
  	$errors = cot_get_messages('', 'error');
  	if (count($errors) > 0)
  	{
  		foreach ($errors as $msg)
  		{
  			$result['errors'][$msg['src']] = isset($L[$msg['text']]) ? $L[$msg['text']] : $msg['text'];
  		}
  	}
  	cot_clear_messages();
	}

  echo json_encode($result);
  exit;
}

$out['subtitle'] = 'Добавление сертификата';
$out['head'] .= $R['code_noindex'];

$mskin = cot_tplfile(array('certificates', 'add'));

/* === Hook === */
foreach (cot_getextplugins('certificates.add.main') as $pl)
{
	include $pl;
}
/* ===== */

$t = new XTemplate($mskin);

// Error and message handling
cot_display_messages($t);

$t->assign(array(
	"PRDADD_FORM_SEND" => cot_url('certificates', 'm=add&a=add'),
	"PRDADD_FORM_TITLE" => cot_inputbox('text', 'rtitle', $ritem['item_title'], 'size="56"'),
	"PRDADD_FORM_TEXT" => cot_textarea('rtext', $ritem['item_text'], 10, 60, 'id="formtext"', 'input_textarea_editor'),
));

/* === Hook === */
foreach (cot_getextplugins('certificates.add.tags') as $pl)
{
	include $pl;
}
/* ===== */

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