<?php

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

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

// Requirements
require_once cot_incfile('forms');

// Global variables
global $cot_extrafields, $db_certificates, $db_x, $cfg;
$db_certificates = (isset($db_certificates)) ? $db_certificates : $db_x . 'certificates';

$cfg['certificates_sizes'] = array(
  'preview' => array(
    'h' => 90,
    'w' => 130
  ),
  'main' => array(
    'h' => 450,
    'w' => 650
  ),
  'crop' => array(
    'h' => 230,
    'w' => 230
  )
);

function cot_generate_certificatestags($item_data, $tag_prefix = '', $textlength = 0, $admin_rights = null,
									 $pagepath_home = false, $emptytitle = '')
{
	global $db, $cfg, $L, $Ls, $R, $db_certificates, $usr, $sys, $cot_yesno;

	static $extp_first = null, $extp_main = null;

	if (is_null($extp_first))
	{
		$extp_first = cot_getextplugins('certificatestags.first');
		$extp_main = cot_getextplugins('certificatestags.main');
	}

	/* === Hook === */
	foreach ($extp_first as $pl)
	{
		include $pl;
	}
	/* ===== */
	if (!is_array($item_data))
	{
		$sql = $db->query("SELECT * FROM $db_certificates WHERE item_id = '" . (int)$item_data . "' LIMIT 1");
		$item_data = $sql->fetch();
	}

	if ($item_data['item_id'] > 0)
	{
		if (is_null($admin_rights))
		{
			$admin_rights = cot_auth('certificates', 'any', 'A');
      if($usr['maingrp'] == 6) $admin_rights = true;
		}

		$text = cot_parse($item_data['item_text'], '', 'none');
		$text_cut = ((int)$textlength > 0) ? cot_string_truncate($text, $textlength) : $text;

		$temp_array = array(
			'ID' => $item_data['item_id'],
      'USER_ID' => $item_data['item_userid'],
			'STATE' => $item_data['item_state'],
			'SHORTTITLE' => $item_data['item_title'],
      'TEXT_NOTPARSE' => $item_data['item_text'],
			'TEXT' => $text,
			'SHORTTEXT' => $text_cut,
			'DATE' => cot_date('datetime_medium', $item_data['item_date']),
			'DATE_STAMP' => $item_data['item_date'],
			'USER_IS_ADMIN' => ($admin_rights || $usr['id'] == $item_data['item_userid']),
      'IMAGE' => '',
      'IMAGE_CROP' => ''
		);

    if(!empty($item_data['item_file'])) {
      $image = 'datas/certificates/' . $item_data['item_file'];
      $image_crop = 'datas/certificates/crop_' . $item_data['item_file'];
      if(file_exists($image)) {
        $temp_array['IMAGE'] = $image;
        $temp_array['IMAGE_CROP'] = $image;
        if(file_exists($image_crop)) {
          $temp_array['IMAGE_CROP'] = $image_crop;
        } else {
          require_once cot_incfile('uploads');
          $filepath_crop = str_replace('datas/certificates/', 'datas/certificates/crop_', $image);
          cot_imageresize($image, $filepath_crop, $cfg['certificates_sizes']['crop']['w'], $cfg['certificates_sizes']['crop']['h'], 'fit', '', 100, true);
          @chmod($filepath_crop, $cfg['file_perms']);

          $temp_array['IMAGE_CROP'] = $filepath_crop;
        }
      }
    }

		if ($admin_rights || $usr['id'] == $item_data['item_userid'])
		{
			$temp_array['ADMIN_EDIT'] = cot_rc_link(cot_url('certificates', 'm=edit&id=' . $item_data['item_id']), $L['Edit']);
			$temp_array['ADMIN_EDIT_URL'] = cot_url('certificates', 'm=edit&id=' . $item_data['item_id']);
		}

		/* === Hook === */
		foreach ($extp_main as $pl)
		{
			include $pl;
		}
		/* ===== */
	}
	else
	{
		$temp_array = array(
			'TITLE' => (!empty($emptytitle)) ? $emptytitle : $L['Deleted'],
			'SHORTTITLE' => (!empty($emptytitle)) ? $emptytitle : $L['Deleted'],
		);
	}

	$return_array = array();
	foreach ($temp_array as $key => $val)
	{
		$return_array[$tag_prefix . $key] = $val;
	}

	return $return_array;
}

function cot_certificates_import($source = 'POST', $ritem = array(), $auth = array())
{
	global $cfg, $db_certificates, $usr, $sys;

	if ($source == 'D' || $source == 'DIRECT')
	{
		// A trick so we don't have to affect every line below
		global $_PATCH;
		$_PATCH = $ritem;
		$source = 'PATCH';
	}

	$ritem['item_title'] = cot_import('title', $source, 'TXT');
	$ritem['item_text'] = cot_import('description', $source, 'HTM');

	if(empty($ritem['item_date']))
	{
		$ritem['item_date'] = (int)$sys['now'];
	}
	else
	{
		$ritem['item_update'] = (int)$sys['now'];
	}
	
	if ($auth['isadmin'] && isset($ritem['item_userid']))
	{
		$ritem['item_userid']   = $ritem['item_userid'];
	}
	else
	{
		$ritem['item_userid'] = $usr['id'];
	}
	
	return $ritem;
}

function cot_certificates_add(&$ritem, $auth = array())
{
	global $cache, $cfg, $db, $db_certificates, $L;
	if (cot_error_found())
	{
		return false;
	}

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

	if ($db->insert($db_certificates, $ritem))
	{
		$id = $db->lastInsertId();
	}
	else
	{
		$id = false;
	}

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

	cot_shield_update(30, "r certificates");
	cot_log("Add certificates #".$id, 'adm');

	return $id;
}

function cot_certificates_delete($id, $ritem = array())
{
	global $db, $db_certificates, $cache, $cfg, $L;
	if (!is_numeric($id) || $id <= 0)
	{
		return false;
	}
	$id = (int)$id;
	if (count($ritem) == 0)
	{
		$ritem = $db->query("SELECT * FROM $db_certificates WHERE item_id = ?", $id)->fetch();
		if (!$ritem)
		{
			return false;
		}
	}

	$db->delete($db_certificates, "item_id = ?", $id);
	cot_log("Deleted certificates #" . $id, 'adm');

  if(!empty($ritem['item_file'])) {
    $image = 'datas/certificates/' . $ritem['item_file'];
    $image_crop = 'datas/certificates/crop_' . $ritem['item_file'];
    if(file_exists($image)) unlink($image);
    if(file_exists($image_crop)) unlink($image_crop);
  }

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

	return true;
}

function cot_certificates_update($id, &$ritem, $auth = array())
{
	global $cache, $cfg, $db, $db_certificates, $L;
	if (cot_error_found())
	{
		return false;
	}

	$item = $db->query("SELECT * FROM $db_certificates WHERE item_id = ?", $id)->fetch();
	
	if (!$db->update($db_certificates, $ritem, 'item_id = ?', $id))
	{
		return false;
	}

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