<?php
//error_reporting(E_ALL);

defined('_JEXEC') or die;

jimport('joomla.user.helper');

class ModAlusersHelper
{

  public static function getUserFromCRM($nUserID = 0)
  {
    if ((int)$nUserID == 0) return (FALSE);
    $db = JFactory::getDbo();
    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`users` WHERE `nUserID`='" . (int)$nUserID . "';");
    $result = $db->loadObjectList();
    return (count($result) ? $result[0] : FALSE);
  }

  public static function isFloating($password = 0)
  {
    $hlNum = substr($password, 0, 6);

    $db = JFactory::getDbo();
    $db->setQuery("SELECT isFloating FROM `" . CRMADATBAZIS . "`.`hardlock` WHERE `hlNum`='" . $hlNum . "';");
    $hardlock = $db->loadObject();

    $db->setQuery("SELECT prID, prLogFilter, prVerID FROM `" . CRMADATBAZIS . "`.`h_programs` WHERE `prPass`='" . $password . "';");
    $program = $db->loadObject();

    return $hardlock->isFloating == 1 && $program->prVerID >= 23;
  }

  public static function getEmails($email = '')
  {
    if ($email == '') return (FALSE);
    $db = JFactory::getDbo();
    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE `email`='" . $email . "';");
    $result = $db->loadObjectList();
    return (count($result) ? $result : FALSE);
  }

  public function getNewsletterEmails($nUserID = 0)
  {
    if ((int)$nUserID == 0) return (FALSE);
    $db = JFactory::getDbo();
    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE nUserID=" . $nUserID . ";");
    $result = $db->loadObjectList();
    return (count($result) ? $result : FALSE);
  }

  public function getIdFromEmail($email = '')
  {
    if ($email == '') return (FALSE);
    $db = JFactory::getDbo();
    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE email='" . $email . "' ORDER BY u_emails_id LIMIT 1;");
    $result = $db->loadObjectList();
    return (count($result) ? $result[0]->nUserID : FALSE);
  }

  public static function getKeys($ids = array())
  {
    if (empty($ids)) return (FALSE);
    $db = JFactory::getDbo();
    $db->setQuery("SELECT hlNum kulcs_kod FROM `" . CRMADATBAZIS . "`.`hardlock` WHERE `hlUser` IN (" . implode(',', $ids) . ") AND hlStat!=2;");
    $result = $db->loadObjectList();
    return (count($result) ? $result : FALSE);
  }

  public static function getPrograms($key = '')
  {
    if ($key == '') return (FALSE);
    $db = JFactory::getDbo();
    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`h_programs` p 
      LEFT JOIN `" . CRMADATBAZIS . "`.`p_versions` v ON v.verID=p.prVerID 
      LEFT JOIN `" . CRMADATBAZIS . "`.`p_types` t ON t.typeCode=p.prTypeID 
      WHERE prHlNum = '" . $key . "' 
      ORDER BY prID DESC");
    $result = $db->loadObjectList();
    return (count($result) ? $result : FALSE);
  }

  public static function getModules($prid = '')
  {
    if ((int)$prid == 0) return (FALSE);
    $db = JFactory::getDbo();
    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`p_modules` m 
      LEFT JOIN `" . CRMADATBAZIS . "`.`p_mtypes` mt ON m.mdID=mt.ID 
      WHERE m.mdPrID=" . $prid);
    $result = $db->loadObjectList();
    return (count($result) ? $result : FALSE);
  }

  public static function getAllKeyData($ids = array())
  {
    if (empty($ids)) return (FALSE);

    $kulcsok = self::getKeys($ids);

    if (is_array($kulcsok) && count($kulcsok)) {
      foreach ($kulcsok as $key => $kulcs) {
        $programs = self::getPrograms($kulcs->kulcs_kod);

        if (count($programs) && is_array($programs)) {
          foreach ($programs as $key_program => $program) {
            $programs[$key_program]->modulok = ModAlusersHelper::getModules($program->prID);
          }
        }
        $kulcsok[$key]->programok = $programs;
      }
    }

    return (count($kulcsok) ? $kulcsok : FALSE);
  }

  public function savePersonalSettings($nUserID = 0, $tomb = array())
  {
    if ((int)$nUserID == 0 || !is_array($tomb) || empty($tomb)) return (FALSE);

    $set = '';
    $new = array();
    $mezok = array('strName' => JText::_('MOD_ARCHLINE_NAME'), 'nCtrID' => JText::_('MOD_ARCHLINE_COUNTRY'), 'strZip' => JText::_('MOD_ARCHLINE_ZIP'), 'strCity' => JText::_('MOD_ARCHLINE_CITY'), 'strStreet' => JText::_('MOD_ARCHLINE_ADDRESS'), 'strTel' => JText::_('MOD_ARCHLINE_PHONE'), 'nUserProf' => JText::_('MOD_ARCHLINE_PROFESSION'));

    foreach ($tomb as $k => $v) {
      if (in_array($k, array_keys($mezok))) {
        $new[$k] = $v;
        $set .= ($set == '' ? '' : ', ') . "`" . $k . "`='" . $v . "'";
      }
    }

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);

    $db->setQuery("SELECT * FROM `" . JMLADATBAZIS . "`.`dtch_users` WHERE nUserID=" . $nUserID . " LIMIT 1;");
    $jml = $db->loadObjectList();
    $jml = $jml[0];

    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID=" . $nUserID);
    $old = $db->loadObjectList();
    $old = $old[0];

    $strValt = '';
    $valt = array();
    foreach ($mezok as $mezo => $str) {
      if (!$old->$mezo || !$new[$mezo] || $old->$mezo != $new[$mezo]) {
        $valt[] = $mezo;
        $strValt .= $str . " " . JText::_('MOD_ARCHLINE_ORIG') . ": " . $old->$mezo . " " . JText::_('MOD_ARCHLINE_NEW') . ": " . $new[$mezo] . "<br />";
      }
    }

    //  crm user history-ba elmenti a változásokat
    if (count($valt)) self::insertUserHistory($nUserID, $strValt);

    //foreach (self::getCountries() as $k=>$v) { if ($new['nCtrID']==$k) { $country=$v;break;} } 
    //foreach (self::getProfessions() as $k=>$v) { if ($new['nUserProf']==$k) { $profession=$v;break;} } 

    //  crm rekord felülírása
    $db->setQuery("UPDATE `" . CRMADATBAZIS . "`.`users` SET " . $set . " WHERE nUserID=" . (int)$nUserID . " LIMIT 1;");
    $db->execute();

    $db->setQuery("UPDATE " . CRMADATBAZIS . ".users
        SET strTel = REPLACE(strTel, '/', ''), strTel = REPLACE(strTel, '.', ''), strTel = REPLACE(strTel, ' ', ''), strTel = REPLACE(strTel, '-', ''), 
        strTel = REPLACE(strTel, '+', ''), strTel = REPLACE(strTel, ',', ';'), strTel = REPLACE(strTel, '(', ''), strTel = REPLACE(strTel, ')', ''),
        strTel = REPLACE(strTel, '[', ''), strTel = REPLACE(strTel, ']', '')
        WHERE nUserID = " . (int)$nUserID . " LIMIT 1;");
    $db->execute();

    //  jml rekord felülírása
    $db->setQuery("UPDATE `" . JMLADATBAZIS . "`.`dtch_users` SET `name`='" . $new['strName'] . "' WHERE nUserID=" . (int)$nUserID . " LIMIT 1;");
    $db->execute();

    //  jml profile rekordok felülírása
    $db->setQuery("UPDATE `" . JMLADATBAZIS . "`.`dtch_jsn_users` SET `country`='" . $new['nCtrID'] . "' WHERE id=" . (int)$jml->id . " LIMIT 1;");
    $db->execute();
    /*$db->setQuery("UPDATE `".JMLADATBAZIS."`.`dtch_jsn_users` SET `profile_value`='".$new['strZip']."' WHERE user_id=".(int)$jml->id." AND `profile_key`='profile.postal_code' LIMIT 1;");
    $db->execute();
    $db->setQuery("UPDATE `".JMLADATBAZIS."`.`dtch_jsn_users` SET `profile_value`='".$new['strCity']."' WHERE user_id=".(int)$jml->id." AND `profile_key`='profile.city' LIMIT 1;");
    $db->execute();
    $db->setQuery("UPDATE `".JMLADATBAZIS."`.`dtch_jsn_users` SET `profile_value`='".$new['strStreet']."' WHERE user_id=".(int)$jml->id." AND `profile_key`='profile.address1' LIMIT 1;");
    $db->execute();*/
    $db->setQuery("UPDATE `" . JMLADATBAZIS . "`.`dtch_jsn_users` SET `phone`='" . $new['strTel'] . "' WHERE id=" . (int)$jml->id . " LIMIT 1;");
    $db->execute();
    $db->setQuery("UPDATE `" . JMLADATBAZIS . "`.`dtch_jsn_users` SET `profession`='" . $new['nUserProf'] . "' WHERE id=" . (int)$jml->id . " LIMIT 1;");
    $db->execute();
  }

  public function getCountries()
  {
    $db = JFactory::getDbo();
    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`countries` WHERE ctrID != 37 AND ctrID != 95 AND ctrID != 99 AND ctrID != 94 AND ctrID != 96 AND ctrID != 92 AND ctrID != 91 ;");
    $result = $db->loadObjectList();
    return (count($result) ? $result : FALSE);
  }

  public function getProfessions()
  {
    $db = JFactory::getDbo();
    $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`u_profs`;");
    $result = $db->loadObjectList();
    return (count($result) ? $result : FALSE);
  }

  public function savePassword($id, $pass)
  {
    if ((int)$id > 0) {
      $db = JFactory::getDbo();
      $db->setQuery("UPDATE `dtch_users` SET `password`='" . JUserHelper::hashPassword($pass) . "' WHERE id=" . (int)$id . " LIMIT 1;");
      $db->execute();
    }
  }

  public function newEmail($nUserID, $email)
  {
    if ((int)$nUserID > 0 && filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $db = JFactory::getDbo();
      $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE `email`='" . $email . "' LIMIT 1;");
      $exist = $db->loadObjectList();
      if (empty($exist)) {
        $db->setQuery("INSERT INTO `" . CRMADATBAZIS . "`.`u_emails` (`email`,`nUserID`,`default`,`active`,`deleted`,`newsletter`) VALUES ('" . $email . "','" . $nUserID . "','0','1','0','1');");
        $db->execute();
        $db->setQuery("UPDATE `www_archline_hu`.`dtch_users` SET `email`='" . $email . "' WHERE nUserID=" . $nUserID . " LIMIT 1;");
        $db->execute();
        $db->setQuery("UPDATE `" . CRMADATBAZIS . "`.`users` SET `strEMail`='" . $email . "' WHERE nUserID=" . $nUserID . " LIMIT 1;");
        $db->execute();
        self::insertUserHistory($nUserID, JText::_('MOD_ARCHLINE_NEW_EMAIL') . ': ' . $email);
      }
    }
  }

  public function delEmail($nUserID, $u_emails_id)
  {
    if ((int)$nUserID > 0 && (int)$u_emails_id > 0) {
      $db = JFactory::getDbo();
      $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE `nUserID`='" . $nUserID . "' AND `u_emails_id`='" . (int)$u_emails_id . "' LIMIT 1;");
      $exist = $db->loadObjectList();
      if (!empty($exist)) {
        $db->setQuery("DELETE FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE `nUserID`='" . $nUserID . "' AND `u_emails_id`='" . (int)$u_emails_id . "' LIMIT 1;");
        $db->execute();
        self::insertUserHistory($nUserID, JText::_('MOD_ARCHLINE_DEL_EMAIL') . ': ' . $exist[0]->email);
      }
    }
  }

  public function saveNewsletters($nUserID = 0, $ids = array())
  {
    if ((int)$nUserID > 0) {
      $db = JFactory::getDbo();

      $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`users` WHERE nUserID=" . (int)$nUserID . " LIMIT 1;");
      $crmUser = $db->loadObjectList();
      $crmUser = $crmUser[0];

      /*      
      if ($crmUser->bNewsletter=='Y' && !isset($_POST['bNewsletter'])) // letiltas
      {
        $db->setQuery("UPDATE `".CRMADATBAZIS."`.`users` SET `bNewsletter`='N' WHERE nUserID=".(int)$nUserID." LIMIT 1;");
        $db->execute();
        self::insertUserHistory($nUserID,JText::_('MOD_ARCHLINE_NEWSLETTER_DISABLED'),array('nTopicID'=>(JFactory::getLanguage()->getTag()=='hu-HU'?54:166)));
      }
      
      if ( (is_null($crmUser->bNewsletter) || $crmUser->bNewsletter=='N') && isset($_POST['bNewsletter'])) // engedélyezés
      {
        $db->setQuery("UPDATE `".CRMADATBAZIS."`.`users` SET `bNewsletter`='Y' WHERE nUserID=".(int)$nUserID." LIMIT 1;");
        $db->execute();
        self::insertUserHistory($nUserID,JText::_('MOD_ARCHLINE_NEWSLETTER_ENABLED'),array('nTopicID'=>(JFactory::getLanguage()->getTag()=='hu-HU'?38:150)));
      }
*/

      $db->setQuery("SELECT * FROM `" . CRMADATBAZIS . "`.`u_emails` WHERE nUserID=" . (int)$nUserID . ";");
      $exist = $db->loadObjectList();
      if (is_array($exist) && count($exist)) {
        foreach ($exist as $row) {
          if (is_null($ids) || (is_array($ids) && empty($ids))) {
            $db->setQuery("UPDATE `" . CRMADATBAZIS . "`.`u_emails` SET `newsletter`=0 WHERE u_emails_id=" . $row->u_emails_id . " AND nUserID=" . (int)$nUserID . " LIMIT 1;");
            $db->execute();
            self::insertUserHistory($nUserID, JText::_('MOD_ARCHLINE_UNSUBSCRIBE_NEWSLETTER') . ': ' . $row->email);
          } else {
            if ($row->newsletter == 0 && in_array($row->u_emails_id, $ids)) /* elötte nem volt és utána be lett pipálva => FELIRATKOZOTT */ {
              $db->setQuery("UPDATE `" . CRMADATBAZIS . "`.`u_emails` SET `newsletter`=1 WHERE u_emails_id=" . $row->u_emails_id . " AND nUserID=" . (int)$nUserID . " LIMIT 1;");
              $db->execute();
              self::insertUserHistory($nUserID, JText::_('MOD_ARCHLINE_SUBSCRIBE_NEWSLETTER') . ': ' . $row->email);
            }
            if ($row->newsletter == 1 && !in_array($row->u_emails_id, $ids)) /* elötte be volt és utána nem volt bepipálva => LEIRATKOZOTT */ {
              $db->setQuery("UPDATE `" . CRMADATBAZIS . "`.`u_emails` SET `newsletter`=0 WHERE u_emails_id=" . $row->u_emails_id . " AND nUserID=" . (int)$nUserID . " LIMIT 1;");
              $db->execute();
              self::insertUserHistory($nUserID, JText::_('MOD_ARCHLINE_UNSUBSCRIBE_NEWSLETTER') . ': ' . $row->email);
            }
          }
        }
      }
    }
  }

  public function insertUserHistory($nUserID = 0, $strInfo = "", $tomb = array())
  {
    if ((int)$nUserID > 0 && $strInfo > '') {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $item = array(
        'nUserID' => $nUserID,
        'nTopicID' => (isset($tomb['nTopicID']) && (int)$tomb['nTopicID'] > 0 ? (int)$tomb['nTopicID'] : (JFactory::getLanguage()->getTag() == 'hu-HU' ? 364 : 365)),
        'dateEvent' => (isset($tomb['dateEvent']) && $tomb['dateEvent'] > '' ? $tomb['dateEvent'] : date('Y-m-d', time())),
        'strPlace' => (isset($tomb['strPlace']) && $tomb['strPlace'] > '' ? $tomb['strPlace'] : 'web'),
        'strInfo' => $strInfo,
        'nManagerID' => (isset($tomb['nManagerID']) && (int)$tomb['nManagerID'] > 0 ? $tomb['nManagerID'] : 36),
        'insertDate' => (isset($tomb['insertDate']) && $tomb['insertDate'] > '' ? $tomb['insertDate'] : date('Y-m-d H:i:s', time())),
      );

      foreach ($item as $v) $values[] = $db->quote($v);
      $query->insert("`" . CRMADATBAZIS . "`.`u_history`")->columns($db->quoteName(array_keys($item)))->values(implode(',', $values));
      $db->setQuery($query);
      $db->execute();
    }
  }
} // end of class