<?php

/*******************************************************************************
 * Marketing-es email-ket küld ki a trial-t letöltő usereknek, kivéve az alábbi
 * országok: 30,39,41,42,43,49,421,1257,1403,1414
 * (Ausztria,Németország,Svájc,Csehország,Szlovákia,Görögország,Olaszország)
 ******************************************************************************/
if (!isset($config)) {
  require_once('config.php');
  require_once('libraries/phpmailer/PHPMailerAutoload.php');
}

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

$strPlace = 'web';
$nManagerID = 36;
$nTopicID = ($jmdb == 'jml' ? 305 : 306);
$time = time();
$days = array();

if (date('H', $time) == '13') {
  $msh2->query("SELECT alias FROM " . $jmdb . "_content WHERE state=1 AND alias LIKE 'nonprofit-mail-%'");
  foreach ($msh2->fetchAssoc() as $row) {
    $days[] = end(explode('-', $row['alias']));
  }

  sort($days);

  foreach ($days as $idx => $day) {
    $msh->query("
      SELECT u.nUserID,u.strName,u.strEmail,u.old_db,DATE(FROM_UNIXTIME(u.dateInsert)) AS signupDate,d.letoltDate,d.strInfo
      FROM users u
      LEFT OUTER JOIN
      (
      	SELECT nUserId, MIN(dateEvent) AS letoltDate,strInfo
      	FROM u_history h
      	WHERE h.nManagerID=36 AND h.nTopicID IN (117,167) AND dateEvent>=ADDDATE(CURRENT_DATE, INTERVAL -60 DAY)
      	GROUP BY nUserID
      	ORDER BY nUserID DESC
      ) d ON u.nUserID=d.nUserID
      WHERE
        u.strEmail>'' AND
        u.nCtrID NOT IN (30,39,41,42,43,49,421,1257,1403,1414) AND
        u.dateInsert IS NOT NULL AND
        d.letoltDate IS NOT NULL AND
        u.old_db='" . ($jmdb == 'jml' ? 'clusers' : 'clusers_eng') . "' AND
        DATE(FROM_UNIXTIME(u.dateInsert))=ADDDATE(CURRENT_DATE, INTERVAL -" . $day . " DAY)
      ORDER BY dateInsert DESC;");
    $users = $msh->fetchAssoc();

    if (!empty($users)) {
      //    get email template from joomla content
      $msh2->query("SELECT * FROM " . $jmdb . "_content WHERE alias='nonprofit-mail-" . $day . "' LIMIT 1;");
      $content = $msh2->fetchAssoc();

      foreach ($users as $key => $row) {
        //      get user from joomla
        $msh2->query("SELECT * FROM " . JMLADATBAZIS . ".jml_users WHERE nUserID=" . $row['nUserID'] . " LIMIT 1;");
        $user = $msh2->fetchAssoc();

        if (!empty($content) && !empty($user)) {
          if ($jmdb == 'jml') {
            $firstname = trim(substr($user[0]['name'], strpos($user[0]['name'], ' ')));
            $lastname = trim(substr($user[0]['name'], 0, strpos($user[0]['name'], ' ')));
          } else {
            $firstname = trim(substr($user[0]['name'], 0, strpos($user[0]['name'], ' ')));
            $lastname = trim(substr($user[0]['name'], strpos($user[0]['name'], ' ')));
          }

          $subject = str_replace(array('#name#', '#firstname#', '#lastname#'), array(ucwords($user[0]['name']), ucwords($firstname), ucwords($lastname)), $content[0]['title']);
          $msg = str_replace(array('#name#', '#firstname#', '#lastname#'), array(ucwords($user[0]['name']), ucwords($firstname), ucwords($lastname)), $content[0]['introtext']);

          $msh->query("SELECT * FROM " . CRMADATBAZIS . ".u_history WHERE nUserID=" . $row['nUserID'] . " AND nTopicID=" . $nTopicID . " AND dateEvent='" . date('Y-m-d', $time) . "' AND strPlace='" . $strPlace . "' AND strInfo='" . $subject . "' AND nManagerID=" . $nManagerID . ";");
          $exist = $msh->fetchAssoc();

          $msh->query("SELECT * FROM " . CRMADATBAZIS . ".u_emails WHERE email='" . $user[0]['email'] . "' AND newsletter=1 LIMIT 1;");
          $newsletter = $msh->fetchAssoc();

          if (empty($exist) && !empty($newsletter) && $newsletter[0]['newsletter'] == 1) {
            $mail = new PHPMailer;
            $mail->CharSet = 'UTF-8';
            //          $mail->isSendmail();
            $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($jmdb == 'jml' ? 'info@cadline.hu' : 'info@archlinexp.com');
            $mail->addAddress($user[0]['email']);
            //            $mail->addAddress('mcleod78@gmail.com');
            $mail->addBCC('webdeveloper@cadline.hu');
            $mail->Subject = $subject;
            $mail->msgHTML($msg);
            $mail->AltBody = strip_tags($msg);
            $mail->send();

            unset($mail);

            $msh->insert(CRMADATBAZIS . ".`u_history`", array(
              'nUserID' => $row['nUserID'],
              'nTopicID' => $nTopicID,
              'dateEvent' => date('Y-m-d', $time),
              'strPlace' => $strPlace,
              'strInfo' => $subject,
              'nManagerID' => $nManagerID,
              'insertDate' => date('Y-m-d H:i:s', $time),
            ));

            /* edited by: F.Zs. 2017.01.17 - H. Erika kérésére többé nem kell ezt a bejegyzést beírni
            if ($idx==count($days)-1)
            {
              $msh->insert("`".CRMADATBAZIS."`.`u_messages`",array(
                'nUserID'=>$row['nUserID'],
                'nManagerID'=>($jmdb=='jml' ? 51 : 42),
                'nManSender'=>36,
                'dateSend'=>date('Y-m-d',$time+86400),
                'strTopic'=>'Auto levél',
                'strMsg'=>'Email kiküldve: '.$day.' napon.',
                'bFlag'=>0
              ));
            }
*/
          }
        }
      }
    }
  }
}
