<?php

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

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

// Requirements
require_once cot_incfile('forms');

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

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

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

	static $extp_first = null, $extp_main = null;

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

	/* === Hook === */
	foreach ($extp_first as $pl)
	{
		include $pl;
	}
	/* ===== */
	if (!is_array($item_data))
	{
		$sql = $db->query("SELECT * FROM $db_portfolio 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('portfolio', '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/portfolio/' . $item_data['item_file'];
      $image_crop = 'datas/portfolio/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/portfolio/', 'datas/portfolio/crop_', $image);
          cot_imageresize($image, $filepath_crop, $cfg['portfolio_sizes']['crop']['w'], $cfg['portfolio_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('portfolio', 'm=edit&id=' . $item_data['item_id']), $L['Edit']);
			$temp_array['ADMIN_EDIT_URL'] = cot_url('portfolio', '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_portfolio_import($source = 'POST', $ritem = array(), $auth = array())
{
	global $cfg, $db_portfolio, $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_portfolio_add(&$ritem, $auth = array())
{
	global $cache, $cfg, $db, $db_portfolio, $L;
	if (cot_error_found())
	{
		return false;
	}

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

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

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

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

	return $id;
}

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

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

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

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

	return true;
}

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

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

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