<?php
defined('COT_CODE') or die('Wrong URL');

$return_json = false;
$return = '';

$cid = cot_import('cid', 'G', 'INT');
$uid = cot_import('uid', 'G', 'INT');

if($uid > 0 || $cid > 0) {
  require_once cot_incfile('certificates', 'module');

  list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('certificates', 'any', 'RWA');
  if(!$usr['isadmin'] && $usr['maingrp'] == 6) $usr['isadmin'] = true;

  $fcidid = 0;

  if($cid > 0) {
    $fcid = $sqllist = $db->query("SELECT * FROM $db_certificates AS f
      WHERE item_id=".$cid.(!$usr['isadmin'] ? ' AND item_state=0' : ' AND (item_state=0 OR item_userid='.$usr['id'].')')." LIMIT 1")->fetch();
    if($fcid['item_id'] > 0) {
      $fcidid = $fcid['item_id'];
      $uid = $fcid['item_userid'];
    }
  }

  if($uid > 0) {
    $sqllist = $db->query("SELECT * FROM $db_certificates AS f
      WHERE item_userid=".$uid.((!$usr['isadmin'] && $uid != $usr['id']) ? ' AND item_state=0' : '')."
    	ORDER BY item_date DESC")->fetchAll();

    $t = new XTemplate(cot_tplfile(array('api', 'getCertificates'), 'plug'));

    /* === Hook === */
    $extp = cot_getextplugins('api.getCertificates.loop');
    /* ===== */

    $jj=0;
    $active_list = false;
    $items_list = array();
    foreach($sqllist as $item)
    {
      $jj++;
      $items_list[] = $item['item_id'];
      $active_list = (($fcidid == 0 && $jj == 1) || ($fcidid > 0 && $fcidid == $item['item_id']));

      $t->assign(cot_generate_certificatestags($item, 'ITEM_ROW_', 300, $usr['isadmin'], $cfg['homebreadcrumb']));
      $t->assign(array(
      	"ITEM_ROW_LIST_ISACTIVE_CLASS" => ($active_list ? ' active' : ''),
      ));
      if($active_list) {
        $t->assign(cot_generate_certificatestags($item, 'ITEM_ACTIVE_', 300, $usr['isadmin'], $cfg['homebreadcrumb']));
      }

    	/* === Hook === */
    	foreach ($extp as $pl)
    	{
    		include $pl;
    	}
    	/* ===== */
    	$t->parse("MAIN.ITEMS_ROWS");
    }

    $t->assign(cot_generate_usertags($uid, 'USER_TAGS_', '', true));

    $t->assign(array(
    	"ITEMS_LIST" => implode(',', $items_list),
      "ITEMS_LIST_CNT" => $jj
    ));

    foreach (cot_getextplugins('api.getCertificates.usertags') as $pl)
    {
    	include $pl;
    }
    /* ===== */

    $return = $t->text('MAIN');
  }
}

?>