<?php
if ($_SERVER['REMOTE_ADDR'] != '188.6.239.155') {
  die();
}
error_reporting(E_ALL);
die();

mb_internal_encoding("UTF-8");

include("config.php");

$time = time();
$nManagerID = 54;
$arrFiles = array("leads/leads_imported.csv");

foreach ($arrFiles as $file) {
  foreach (file($file) as $k => $sor) {
    $mezo = explode(";", $sor);

    if ($k == 0) continue;
    if (trim($mezo[3]) == '') continue;

    $emails = explode(",", strtolower(trim(utf8_decode(str_replace("'", "", $mezo[3])))));

    $user = array(
      "strInfo" => utf8_decode(trim($mezo[0]) . ', ' . trim($mezo[1])),
      "strName" => ucwords(trim(strtolower(utf8_decode($mezo[2])))),
      "strEMail" => $emails[0],
      "strTel" => trim(utf8_decode($mezo[4])),
      "nCtrID" => ((int)$mezo[5] > 0 ? (int)$mezo[5] : NULL),
      "strZip" => strtoupper(trim(utf8_decode($mezo[6]))),
      "strCity" => ucwords(trim(strtolower(utf8_decode($mezo[7])))),
      "strStreet" => trim(utf8_decode($mezo[8])),
      "strCompany" => ucwords(trim(strtolower(utf8_decode($mezo[9])))),
      "strWeb" => strtolower(trim(utf8_decode($mezo[10]))),
      "nManagerID" => $nManagerID,
      "nUserStatus" => 0,
      "nIsCommendatory" => 0,
      "nUserType" => 0,
      "nUserDebt" => 0,
      "nEsely" => 0,
      "dateInsert" => $time,
      "deleted" => 0,
      "old_db" => "clusers_eng",
    );

    //print_r($user); print "<br />";

    $nUserID = 0;
    $exist = FALSE;

    foreach ($emails as $email) {
      $res = array();
      $msh->query("SELECT * FROM " . CRMADATBAZIS . ".u_emails WHERE LOWER(email)='" . strtolower(trim($email)) . "' LIMIT 1;");
      $res = $msh->fetchAssoc();
      if (!empty($res)) {
        $exist = TRUE;
        break;
      }
    }

    if ($exist) {
      $nUserID = $res[0]['nUserID'];
      print "exist: {$nUserID}<br />\n";
    } else {
      $msh->insert(CRMADATBAZIS . ".`users`", $user);
      $nUserID = $msh->getInsertedId();

      foreach ($emails as $e => $email) {
        $msh->query("SELECT * FROM " . CRMADATBAZIS . ".u_emails WHERE LOWER(email)='" . strtolower(trim($email)) . "' LIMIT 1;");
        $res = $msh->fetchAssoc();
        if (empty($res)) {
          $msh->insert(CRMADATBAZIS . ".`u_emails`", array(
            'email' => strtolower(trim($email)),
            'nUserID' => $nUserID,
            'default' => ($e == 0 ? 1 : 0),
            'active' => 1,
            'deleted' => 0,
            'newsletter' => 1
          ));
        }
      }
    }

    $msh->insert(CRMADATBAZIS . ".`u_history`", array(
      'nUserID' => $nUserID,
      'nTopicID' => 339,
      'dateEvent' => date("Y-m-d", $time),
      'strPlace' => '',
      'strInfo' => 'Tóth Zoli (Partnering) adatbázis',
      'nManagerID' => $nManagerID,
      'insertDate' => date("Y-m-d H:i:s", $time),
    ));
  }
}
