<?php

/*******************************************************************************
 * A file download-ok     
 ******************************************************************************/
if (!isset($config)) {
  require_once('config.php');
}

if (!isset($jmdb)) {
  $jmdb = ((isset($_GET['jmdb']) && in_array($_GET['jmdb'], array('jml', 'eng'))) ? $_GET['jmdb'] : 'jml');
}

$days_before = 7;
$nTopicID = ($jmdb == 'jml' ? 117 : 167);
$nManagerID = 36;
$strPlace = 'web';

// A 21-es kategória a Letöltési központ!
$msh2->query("
  SELECT s.id,s.fileid,s.userid,u.email,u.nUserID,s.count,s.`date`,f.filename
  FROM " . $jmdb . "_phocadownload_user_stat s
  LEFT OUTER JOIN " . $jmdb . "_phocadownload f ON s.fileid=f.id
  LEFT OUTER JOIN jml_users u ON s.userid=u.id
  WHERE s.fileid IN (SELECT id AS fileid FROM " . $jmdb . "_phocadownload WHERE catid IN (SELECT id FROM " . $jmdb . "_phocadownload_categories WHERE id IN (21) OR parent_id IN (21))) 
  AND s.userid>0 AND u.nUserID>0 AND s.`date`>DATE_ADD(CURRENT_TIMESTAMP,interval-" . $days_before . " DAY)    
  ORDER BY s.`date`;");
$res = $msh2->fetchAssoc();

foreach ($res as $key => $row) {
  $msh->query("SELECT * FROM " . CRMADATBAZIS . ".u_history WHERE nUserID=" . $row['nUserID'] . " AND nTopicID=" . $nTopicID . " AND strInfo LIKE '%" . trim($row['filename']) . "%'");
  $exist = $msh->fetchAssoc();

  if (empty($exist)) {
    $msh->query("SELECT * FROM " . CRMADATBAZIS . ".users WHERE nUserID=" . $row['nUserID'] . " LIMIT 1;");
    $exist = $msh->fetchAssoc();

    if (!empty($exist)) {
      //    nUserStatus �ll�t�sa
      if (in_array($exist[0]['nUserStatus'], array(0, 1, 99))) {
        $msh->query("UPDATE " . CRMADATBAZIS . ".users SET nUserStatus=2 WHERE nUserID=" . $row['nUserID'] . " LIMIT 1");
        $msh->insert(CRMADATBAZIS . ".`u_userstatus_history`", array(
          'nUserID' => $row['nUserID'],
          'val' => 2,
          'changeDate' => $row['date'],
          'nManagerID' => $nManagerID,
        ));
      }

      //    esely �ll�t�sa
      /*
      if ((int)$exist[0]['nEsely']<3)
      {
        $msh->query("SELECT * FROM ".CRMADATBAZIS.".hardlock WHERE hlUser=".$row['nUserID']." AND hlStat=1;");
        $user=$msh->fetchAssoc();
        if (empty($user))
        {
          $msh->query("UPDATE ".CRMADATBAZIS.".users SET nEsely=3 WHERE nUserID=".$row['nUserID']." LIMIT 1");
        }
      }
*/
      $tomb = array(
        'nUserID' => $row['nUserID'],
        'nTopicID' => $nTopicID,
        'dateEvent' => substr($row['date'], 0, 10),
        'strPlace' => $strPlace,
        'strInfo' => "Letöltés: " . trim($row['filename']),
        'nManagerID' => $nManagerID,
        'insertDate' => $row['date'],
      );
      $msh->insert(CRMADATBAZIS . ".`u_history`", $tomb);
    }
  }
}
