<?php

/*******************************************************************************
 * Az workshop-okra jelentkezőket/lemondásokat viszi át a crm rendszerbe
 ******************************************************************************/
if (!isset($config)) {
  require_once('config.php');
  require_once($folder . '/maintenance/libraries/phpmailer/PHPMailerAutoload.php');
}

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

$nManagerID = 36;
$days_before = 45;
$topicid = array(
  'eloadonak_jelentkezik' => ($jmdb == 'jml' ? 288 : 0),
  'klub_varolista' => ($jmdb == 'jml' ? 4 : 0),
  'klubra_jelentkezett' => ($jmdb == 'jml' ? 5 : 298),
  'workshopra_hivni' => ($jmdb == 'jml' ? 122 : 225),
  'workshopra_jelentkezett' => ($jmdb == 'jml' ? 123 : 226),
);

// Workshop-on részt vett userek automatikus átsorolása 8-ra (2015-03-01 = user státusz mező bevezetése)
$msh->query("
  SELECT x.*,u.nUserStatus,h.changeDate FROM (SELECT nUserID,MAX(dateEvent) AS dateEvent FROM u_history WHERE nTopicID IN (120,223) AND dateEvent>='2015-03-01' GROUP BY nUserID) x
  LEFT OUTER JOIN users u ON u.nUserID=x.nUserID
  LEFT OUTER JOIN (SELECT nUserID,MAX(changeDate) AS changeDate FROM u_userstatus_history GROUP BY nUserID) h ON h.nUserID=x.nUserID
  WHERE x.dateEvent>=h.changeDate AND u.nUserStatus<8;");
$exist = $msh->fetchAssoc();
if (count($exist)) {
  foreach ($exist as $key => $row) {
    $msh->query("UPDATE " . CRMADATBAZIS . ".users SET nUserStatus=8 WHERE nUserID=" . $row['nUserID'] . " LIMIT 1;");
    $msh->insert(CRMADATBAZIS . ".`u_userstatus_history`", array(
      'nUserID' => $row['nUserID'],
      'val' => 8,
      'changeDate' => date('Y-m-d H:i:s'),
      'nManagerID' => $nManagerID,
    ));
  }
}

$msh2->query("SELECT a.`id`,a.`course_id`,a.`date`,a.`user_id`,a.`attendees`,a.`published`,a.`gepet_kerek`,a.`berletem_van`,c.`title`,c.`alias`,c.`start_date`,c.`finish_date`,u.`name`,u.`email`,u.nUserID
  FROM `alworkshops_application` a
  LEFT OUTER JOIN `alworkshops_courses` c ON a.course_id=c.id
  LEFT OUTER JOIN `jml_users` u ON a.user_id=u.id
  WHERE a.`date`>DATE_ADD(CURRENT_TIMESTAMP,interval-" . $days_before . " DAY);");
$res = $msh2->fetchAssoc();

foreach ($res as $key => $row) {
  $datumok = array();
  $jelentkezes = ($row['published'] == 'N' ? FALSE : TRUE);

  if ($row['start_date'] == $row['finish_date']) {
    $datumok[] = array('hely' => $row['title'], 'datum' => $row['start_date']);
  } else {
    $msh2->query("SELECT session_date,description FROM alworkshops_sessions WHERE courseid=" . $row['course_id'] . ";");
    foreach ($msh2->fetchAssoc() as $datum) {
      $datumok[] = array('hely' => $datum['description'], 'datum' => $datum['session_date']);
    }
  }

  if (empty($datumok) or (int)$row['nUserID'] == 0) {
    continue;
  }

  foreach ($datumok as $datum) {
    $nTopicID = (strpos($row['alias'], "archline-klub") === 0 || strpos($row['alias'], "archline-estek") === 0 || strpos($row['alias'], "archline-evenings") === 0 || strpos($row['alias'], "design-het") === 0) ?
      ($jelentkezes ? $topicid['klubra_jelentkezett'] : $topicid['klub_varolista']) : ($jelentkezes ? $topicid['workshopra_jelentkezett'] : $topicid['workshopra_hivni']);

    if ($row['alias'] == 'tanulocsoportok') {
      if ($jelentkezes) $nTopicID = 379;
      else $nTopicID = 381;
    }

    $sql = "SELECT * FROM " . CRMADATBAZIS . ".u_history WHERE nUserID=" . $row['nUserID'] . " AND dateEvent='" . $datum['datum'] . "' AND strPlace LIKE '%" . trim($datum['hely']) . "%'";
    $msh->query($sql);
    $exist = $msh->fetchAssoc();

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

      //    nUserStatus beallitas
      if (!empty($crm)) {
        if (in_array($crm[0]['nUserStatus'], array(-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 99))) {
          $msh->query("UPDATE " . CRMADATBAZIS . ".users SET nUserStatus=5 WHERE nUserID=" . $row['nUserID'] . " LIMIT 1;");
          $msh->insert(CRMADATBAZIS . ".`u_userstatus_history`", array(
            'nUserID' => $row['nUserID'],
            'val' => 5,
            'changeDate' => date('Y-m-d H:i:s'),
            'nManagerID' => 36,
          ));
        }
      }

      //    $strPlace beállitas
      if (strpos($row['alias'], "archline-klub") === 0 || strpos($row['alias'], "archline-estek") === 0 || strpos($row['alias'], "archline-evenings") === 0  || strpos($row['alias'], "design-het") === 0) {
        if (strpos($row['alias'], "archline-klub") === 0) $strPlace = "";
        if (strpos($row['alias'], "archline-estek") === 0) $strPlace = "ARCHLine Esték - ";
        if (strpos($row['alias'], "archline-evenings") === 0) $strPlace = "ARCHLine Evenings - ";
        if (strpos($row['alias'], "design-het") === 0) $strPlace = "Design Hét - ";
      } else {
        $strPlace = (count($datumok) == 1 ? "Workshop - " : "Tanfolyam - ");
      }

      $tomb = array(
        'nUserID' => $row['nUserID'],
        'nTopicID' => $nTopicID,
        'dateEvent' => $datum['datum'],
        'strPlace' => trim($strPlace . $datum['hely']),
        'strInfo' => trim(
          (trim($row['berletem_van']) == 'Y' ? ' <b>Bérlete van</b>,' : '') .
            (trim($row['gepet_kerek']) == 'Y' ? ' <b>Gépet kér</b>,' : '') .
            ($jelentkezes == TRUE ? '' : ' <b>Jelentkezés törölve</b>')
        ),
        'nManagerID' => '36',
        'insertDate' => $row['date'],
        'applicationID' => $row['id'],
      );
      $msh->insert(CRMADATBAZIS . ".`u_history`", $tomb);
    } else {
      if (((int)$exist[0]['nTopicID'] == 379 || (int)$exist[0]['nTopicID'] == $topicid['workshopra_jelentkezett'] || (int)$exist[0]['nTopicID'] == $topicid['klubra_jelentkezett']) && $jelentkezes == FALSE) {
        $nTopic = ((int)$exist[0]['nTopicID'] == $topicid['workshopra_jelentkezett'] ? $topicid['workshopra_hivni'] : $topicid['klub_varolista']);
        if ((int)$exist[0]['nTopicID'] == 379) $nTopic = 381;

        $msh->update(CRMADATBAZIS . '.u_history', array(
          'nTopicID' => ((int)$exist[0]['nTopicID'] == $topicid['workshopra_jelentkezett'] ? $topicid['workshopra_hivni'] : $topicid['klub_varolista']),
          'strInfo' => $exist[0]['strInfo'] . ' <b>Jelentkezés törölve</b>'
        ), array('nEventID' => $exist[0]['nEventID']));

        $msg = 'Helló adminisztrátor, <br />' . $row['name'] . ' nevű felhasználó jelentkezése a ' . $row['title'] . '-ról törölve lett.';

        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->Host = $mailconfig['Host'];
        $mail->SMTPAuth = true;
        $mail->CharSet = 'UTF-8';
        $mail->Username = $mailconfig['Username'];
        $mail->Password = $mailconfig['Password'];
        $mail->SMTPSecure = $mailconfig['SMTPSecure'];
        $mail->Port = $mailconfig['Port'];
        $mail->isHTML(TRUE);
        $mail->setFrom($mailconfig['from_hu']);
        $mail->addAddress($mailconfig['from_hu']);
        $mail->addBCC('webdeveloper@cadline.hu');
        $mail->Subject = 'Jelentkezés törlés: ' . $row['title'];
        $mail->msgHTML($msg);
        $mail->AltBody = strip_tags($msg);
        $mail->send();
        unset($mail);
      }
    }
  }
}
