<?php

/*******************************************************************************
 * Az eseményekre jelentkezések alapján a fizetéseket kikeresi az
 * Instant Payment Terminal adatbázisából, és beírja a crm rendszerbe
 ******************************************************************************/

$message = "Sync Fizetés teszt";

mail('mate.nagy@cadline.hu', 'Cron', $message);

if (!isset($config)) {
  require_once('config.php');
  require_once('libraries/phpmailer/PHPMailerAutoload.php');
}

if (!class_exists('crm_users')) require_once("common_cadline_libraries/crm_users.class.php");
include('config.course.php');

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

$msh->query("SELECT *
  FROM `" . JMLADATBAZIS . "`.`alworkshops_application`
  WHERE `published`='Y' AND `price_total`>0 AND (`pay_id` IS NULL OR `pay_id`=0) AND DATE(`date`)>='" . date('Y-m-d', time() - 86400 * _DAYS_) . "'
  ORDER BY id DESC;");
$res = $msh->fetchAssoc();

if (count($res)) {
  foreach ($res as $application) {
    $msh->query("SELECT * FROM `pay_archline_hu`.`pos_transactions` WHERE `order_id`='" . $application['transaction_id'] . "' AND `remote_status`='Succeeded' AND `remote_message`='Succeeded' AND `payment_status`='completed' AND `transaction_status`='completed' LIMIT 1;");
    $pay = $msh->fetchAssoc();

    if (count($pay) && (int)$pay[0]['transaction_id'] > 0) {
      $pay = $pay[0];

      $msh->query("SELECT * FROM `" . JMLADATBAZIS . "`.`jml_users` WHERE id=" . (int)$application['user_id'] . " LIMIT 1;");
      $user = $msh->fetchAssoc();
      $user = $user[0];

      $msh->query("SELECT * FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID=" . (int)$user['nUserID'] . " LIMIT 1;");
      $crmUser = $msh->fetchAssoc();
      $crmUser = $crmUser[0];

      $msh->query("SELECT * FROM `" . JMLADATBAZIS . "`.`alworkshops_courses` WHERE id=" . (int)$application['course_id'] . " LIMIT 1;");
      $course = $msh->fetchAssoc();
      $course = $course[0];

      $msh->query("SELECT * FROM `" . JMLADATBAZIS . "`.`alworkshops_switch` WHERE `alias`='" . $course['alias'] . "' LIMIT 1;");
      $switch = $msh->fetchAssoc();
      $switch = $switch[0];

      $msh->query("SELECT * FROM `" . JMLADATBAZIS . "`.`jml_content` WHERE id=" . (int)$course['email_template'] . " LIMIT 1;");
      $tmpl = $msh->fetchAssoc();

      $msh->query("SELECT * FROM `" . CRMADATBAZIS . "`.`u_history` WHERE `nUserID`=" . (int)$user['nUserID'] . " AND `strAccno`='" . $application['transaction_id'] . "' LIMIT 1;");
      $exist = $msh->fetchAssoc();

      $nTopicID = 0;
      if ($switch['workshop'] == 'Y') {
        $nTopicID = _WORKSHOP_PRICE_;
      }
      if ($switch['kurzus'] == 'Y' && (int)$switch['level'] == 1) {
        $nTopicID = _COURSE_PRICE_PRELIMINARY_;
      }
      if ($switch['kurzus'] == 'Y' && (int)$switch['level'] == 2) {
        $nTopicID = _COURSE_PRICE_INTERMEDIATE_;
      }
      if ($switch['vizsga'] == 'Y' && (int)$switch['level'] == 1) {
        $nTopicID = _COURSE_EXAM_PRICE_PRELIMINARY_;
      }
      if ($switch['vizsga'] == 'Y' && (int)$switch['level'] == 2) {
        $nTopicID = _COURSE_EXAM_PRICE_INTERMEDIATE_;
      }
      if ($switch['vizsga'] == 'Y' && (int)$switch['level'] == 3) {
        $nTopicID = _TUTOR_EXAM_PRICE_;
      }
      if ($switch['vizsga'] == 'Y' && (int)$switch['level'] == 4) {
        $nTopicID = _TUTOR_EXAM_PRICE_;
      }

      if ($nTopicID > 0 && count($tmpl) && empty($exist)) {
        $mit = array('{NAME}', '{TITLE}', '{START_DATE}', '{START_TIME}', '{FINISH_DATE}', '{FINISH_TIME}', '{LOCATION}', '{ATTENDEES}', '{PRICE}', '{PRICE_TOTAL}', '{VAT}');
        $mire = array(
          $user['name'], $course['title'],
          ($switch['kurzus'] === 'Y' && (int)$switch['level'] == 2 ? date("Y-m-d", _TIME_) : $course['start_date']),
          ($switch['kurzus'] === 'Y' && (int)$switch['level'] == 2 ? "" : $course['start_time']),
          ($switch['kurzus'] === 'Y' && (int)$switch['level'] == 2 ? date("Y-m-d", _TIME_ + (_LEASE_VALID_DAYS_ * 86400)) : $course['finish_date']),
          ($switch['kurzus'] === 'Y' && (int)$switch['level'] == 2 ? "" : $course['finish_time']),
          $course['location'], $application['attendees'], $course['price'], $application['price_total'], $course['vat']
        );

        $msg = str_replace($mit, $mire, $tmpl[0]['introtext'] . $tmpl[0]['fulltext']);

        $mail = new PHPMailer;
        $mail->CharSet = 'UTF-8';
        $mail->isSMTP();
        $mail->Host = $mailconfig['Host'];
        $mail->SMTPAuth = true;
        $mail->Username = $mailconfig['Username'];
        $mail->Password = $mailconfig['Password'];
        $mail->SMTPSecure = $mailconfig['SMTPSecure'];
        $mail->Port = $mailconfig['Port'];
        $mail->isHTML(TRUE);
        $mail->setFrom('info@cadline.hu');
        $mail->addAddress($user['email']);
        $mail->addBCC('webdeveloper@cadline.hu');
        $mail->addBCC('marketing@cadline.hu');
        $mail->Subject = $tmpl[0]['title'];
        $mail->msgHTML($msg);
        $mail->AltBody = strip_tags($msg);
        $mail->send();
        unset($mail);

        crm_users::AddUserHistory(array(
          'nUserID' => $user['nUserID'],
          'nTopicID' => $nTopicID,
          'dateEvent' => ($switch['kurzus'] === 'Y' && (int)$switch['level'] == 2 ? date('Y-m-d', _TIME_) : $course['start_date']),
          'strInfo' => 'Barionon keresztül fizetett: ' . $pay['amount'] . ' ' . $pay['currency_code'],
          'strPlace' => $switch['title'],
          'datePaydate' => date('Y-m-d', _TIME_),
          'strAccno' => $application['transaction_id'],
          'applicationID' => (int)$application['id'],
        ));

        $arrUpdate = array('pay_id' => (int)$pay['transaction_id']);
        if ($application['berletem_van'] == 'N' && $switch['kurzus'] == 'Y' && in_array($switch['level'], array(1, 2))) $arrUpdate['berletem_van'] = 'Y';
        $msh->update("`" . JMLADATBAZIS . "`.`alworkshops_application`", $arrUpdate, array('id' => (int)$application['id']));

        crm_users::SetUserStatus($user['nUserID'], 8);
      }
    }
  }
}

// lejárt jelentkezések unpublish-re állítása
$msh->query("SELECT s.`level`,s.`kurzus`,s.`workshop`,s.`vizsga`,s.`esemeny`,s.`webinair`,a.*,u.nUserID,c.`start_date`,s.`tanfsor`
  FROM `" . JMLADATBAZIS . "`.`alworkshops_application` a
  LEFT OUTER JOIN `" . JMLADATBAZIS . "`.`jml_users` u ON a.user_id=u.id
  LEFT OUTER JOIN `" . JMLADATBAZIS . "`.`alworkshops_courses` c ON a.course_id=c.id
  LEFT OUTER JOIN `" . JMLADATBAZIS . "`.`alworkshops_switch` s ON c.alias=s.alias
  WHERE (a.pay_id IS NULL OR a.pay_id='') AND
    a.`published`='Y' AND
    a.`price_total`>0 AND
    c.start_date>CURRENT_DATE AND
    a.`date`<'" . date('Y-m-d H:i:s', _TIME_ - (_EXPIRE_TIME_MINUTES_ * 60)) . "';");
$res = $msh->fetchAssoc();
if (count($res)) {
  foreach ($res as $row) {
    //  !!! Ha a fizetős workshop jelentkezés a utoljára vásárolt bérlet időszakába beleesik, akkor nem törli!!!
    $currentLease = crm_users::GetValidLease((int)$row['nUserID'], (int)$row['level']);
    if ($currentLease && $row['vizsga'] == 'N' && $row['start_date'] >= $currentLease['validFrom'] && $row['start_date'] <= $currentLease['validThrough'] && (int)$row['tanfsor'] > 0) {
      continue;
    }

    $msh->update("`" . JMLADATBAZIS . "`.`alworkshops_application`", array('published' => 'N'), array('id' => (int)$row['id']));
  }
}
