<?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');
if(!$usr['isadmin'] && $usr['maingrp'] == 6) $usr['isadmin'] = true;

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

cot_block($usr['auth_read']);

if (!$id || $id < 0)
{
	cot_die_message(404);
}

$sql = $db->query("SELECT * FROM $db_certificates WHERE item_id='$id' LIMIT 1");
cot_die($sql->rowCount() == 0);
$item = $sql->fetch();

cot_block($usr['isadmin'] || $usr['auth_write'] && $usr['id'] == $item['item_userid']);

$sys['parser'] = $item['item_parser'];
$parser_list = cot_get_parsers();

if ($a == 'update')
{
	/* === Hook === */
	foreach (cot_getextplugins('certificates.edit.update.first') as $pl)
	{
		include $pl;
	}
	/* ===== */
	
	cot_block($usr['isadmin'] || $usr['auth_write'] && $usr['id'] == $item['item_userid']);

	$ritem = cot_certificates_import('POST', $item, $usr);
	$ritem['item_update_real'] = $sys['now'];

  if ($_SERVER['REQUEST_METHOD'] == 'POST')
	{
		$rdelete = cot_import('rdelete', 'P', 'BOL');
	}
	else
	{
		$rdelete = cot_import('delete', 'G', 'BOL');
		cot_check_xg();
	}

	if ($rdelete)
	{
		cot_certificates_delete($id, $item);

    $r_url = cot_url('users', array('m' => 'details', 'id' => $usr['id'], 'u' => $usr['name'], 'tab' => 'certificates'), '', true);
    if(COT_AJAX) {
      $result = array(
        'result' => 'success',
        'redirectUrl' => $r_url,
        'errors' => array()
      );

      echo json_encode($result);
      exit;
    } else {
      cot_redirect($r_url);
    }
	}
	
	/* === Hook === */
	foreach (cot_getextplugins('certificates.edit.update.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;
  	}
  }

	/* === Hook === */
	foreach (cot_getextplugins('certificates.edit.update.error') as $pl)
	{
		include $pl;
	}
	/* ===== */

  if(!$filefound && !empty($item['item_file'])) {
    $oldimage = 'datas/certificates/' . $item['item_file'];
    if(file_exists($oldimage)) $filefound = true;
  }

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

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

	if (!cot_error_found())
	{
    $ritem['item_state'] = 2;
    if($usr['isadmin'] && cot_import('rmoder', 'P', 'INT') == 1) {
      $ritem['item_state'] = 0;
    }
		cot_certificates_update($id, $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);
        if(file_exists($filepath_crop)) unlink($filepath_crop);
        if(!empty($item['item_file'])) {
          $oldimage = 'datas/certificates/' . $item['item_file'];
          $oldimage_crop = 'datas/certificates/crop_' . $item['item_file'];
          if(file_exists($oldimage)) unlink($oldimage);
          if(file_exists($oldimage_crop)) unlink($oldimage_crop);
        }

    		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'] = ($usr['isadmin'] ? cot_url('moderation', 'm=certificates&state=2', '', true) : cot_url('users', array('m' => 'details', 'id' => $usr['id'], 'u' => $usr['name']), '', 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', 'edit'));

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

$t = new XTemplate($mskin);

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

$t->assign(array(
	"PRDEDIT_FORM_SEND" => cot_url('certificates', "m=edit&a=update&id=" . $item['item_id']),
	"PRDEDIT_FORM_ID" => $item['item_id'],
	"PRDEDIT_FORM_TITLE" => cot_inputbox('text', 'rtitle', $item['item_title'], 'size="56"'),
	"PRDEDIT_FORM_TEXT" => cot_textarea('rtext', $item['item_text'], 10, 60, 'id="formtext"', 'input_textarea_editor'),
	"PRDEDIT_FORM_DELETE" => cot_radiobox(0, 'rdelete', array(1,0), array($L['Yes'], $L['No']))
)); 

$t->assign(cot_generate_certificatestags($item, 'PRD_EDIT_', 0, $usr['isadmin'], $cfg['homebreadcrumb']));

/* === Hook === */
foreach (cot_getextplugins('certificates.edit.tags') as $pl)
{
	include $pl;
}
/* ===== */
$t->parse('MAIN');
$module_body = $t->text('MAIN');