Thursday, November 22, 2012

create a bash script to run php files

I have create this shell script to migrate  customer, address and orders. 


1st must migrate customer
2nd migrate addresses
3rd migrate order

this 3 tasks i can do by running 1 script when i create bash file.

order_create_shellScript.sh


#!/bin/sh

# Author Sanjeewani
# Date 2012-11-06

# Shell script to migrate Proporta customer,customer address, orders to magento via php scripts


# /team/project_mojo/sourcecode/migration_script_v01/deploy_notes/customer_create_deploy_note.txt
# /team/project_mojo/sourcecode/migration_script_v01/deploy_notes/order_create_deploy_note.txt

path=`pwd`
logfile=$path/../log/order_create_shellScript.log

cd $path
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Starting to migrate orders" | tee -a $logfile

# 1- Script for migrate all customers with all direct attributes
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Migrating all customers with all direct attributes" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php customer_create.php -nor 5000" | tee -a $logfile
php customer_create.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished migrate all customers with all direct attributes" | tee -a $logfile

# 2- Script for update customers(fix to first name and last name)
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> updating migrated customers" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php customer_update.php -nor 5000" | tee -a $logfile
php customer_update.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished update customers" | tee -a $logfile

# 3- Script for migrate customer addresses
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Migrating  customer addresses  " | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php customer_create_address.php -nor 700000" | tee -a $logfile
php customer_create_address.php -nor 700000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished migrate all addresses" | tee -a $logfile

# 4-Script for Migrate missing addresses(for old migrated customer's latest addresses)
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Migrating missing addresses" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php customer_create_missing_address.php -nor 5000" | tee -a $logfile
php customer_create_missing_address.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished migrate missing addresses" | tee -a $logfile

# 5- Script for update customer addresses
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> updating customer addresses" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php customer_address_update.php -nor 5000" | tee -a $logfile
php customer_address_update.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished update customer addresses" | tee -a $logfile

# 6- Script for reassign store view to customers
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> updating customer store view" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php customer_reassign_storeview.php -nor 5000" | tee -a $logfile
php customer_reassign_storeview.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished update customer store view" | tee -a $logfile

# 7- Script for migrate orders
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Migrating orders" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php order_create.php -nor 5000" | tee -a $logfile
php order_create.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished migrate orders" | tee -a $logfile

# 8- Script for migrate missing orders
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Migrating Missing orders" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php order_create_missing.php -nor 5000" | tee -a $logfile
php order_create_missing.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished migrate missing orders" | tee -a $logfile

# 9- Script for update currency rate for orders
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> updating currency rate for orders" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php order_update_currency_rate.php -nor 5000" | tee -a $logfile
php order_update_currency_rate.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished migrate all customers with all direct attributes" | tee -a $logfile

# 10- Script for migrate order notes for migrated orders
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Migrating order notes" | tee -a $logfile
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  -->\t running php order_note_create.php -nor 5000" | tee -a $logfile
php order_note_create.php -nor 5000
echo "`date +"%Y-%m-%d %H:%M:%S"` - INFO  --> Finished migrate order notes" | tee -a $logfile


echo "--------------------------------------------------------" | tee -a $logfile






Wednesday, November 21, 2012

Create a cron schedule for php run


I wanted to insert a record to database every minute. this is the my php script.

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$user="ppuser";
$password="ppuserbb";
$database="test";
$host="192.168.1.22";

$names=array('test1','test2','test3','test4');

$id=array_rand($names);
$name=$names[$id];



mysql_connect($host,$user,$password);
@mysql_select_db($database) or die( "Unable to select database");

$sql="INSERT INTO `crontest` (
        `name` ,
        `insert_time`
        )
        VALUES ('".$name."', NOW());";
 mysql_query($sql);
 mysql_close();

?>


then open the crontab in linux.

run  crontab -e on terminal. then add below line to crontab.

*/1 * * * * php /opt/lampp/htdocs/test2/sanjicron.php

  • 1st *: Minute (0-59)
  • 2nd *: Hours (0-23)
  • 3rd *: Day (0-31)
  • 4th *: Month (0-12 [12 == December])
  • 5th *: Day of the week(0-7 [7 or 0 == sunday])


Monday, November 19, 2012

File uploading

I have got more experience with file uploading using php.Finaly i created a correct code definition for file uploading using php .This is the fileupload.html file.

Untitled Document



enctype="multipart/form-data">





this is the PHP file for the server side.upload_file.php,


Untitled Document
if ($_FILES["file"]["error"] > 0)
{
echo 'sanji went';
echo "Error: " . $_FILES["file"]["error"] . "
";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "
";
echo "Type: " . $_FILES["file"]["type"] . "
";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>

when we upload a file it save in tmp folder in our localhost server. After that we can change the location using move funtion.

Access wamp www directory and phpmyadmin from another machine


Question:
I have installed wamp on machine A. When I am on the local server that I installed it on I can access PHPMyAdmin from http://127.0.0.1/phpmyadmin or http://localhost/phpmyadmin
But I want to be able to access it from my computer and when I type in IP address of the Server I can see the pages I have put in but when I type http://192.168.1.116/phpmyadmin, PHPMyAdmin comes up saying
Forbidden
You don’t have permission to access /mysql/ on this server.
Solution:
Go to C:\wamp\alias. Open the file phpmyadmin.conf and add

Options Indexes FollowSymLinks MultiViews
Allow Override all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from MACHINE_IP

Create a custom module for change encryption mechanism inside magento

This is my first experience with mageto custom module creation.

first you should create below folder structure in you magento installation.My module name is ShaModule and my custom module creating package is Sanji.If i create another custom module  then i can put that module also inside the Sanji package.

mageto/app/code/local/Sanji/ShaModule
mageto/app/code/local/Sanji/ShaModule/Block
mageto/app/code/local/Sanji/ShaModule/controllers
mageto/app/code/local/Sanji/ShaModule/etc
mageto/app/code/local/Sanji/ShaModule/Helper
mageto/app/code/local/Sanji/ShaModule/Model
mageto/app/code/local/Sanji/ShaModule/sql

Then you create module files.

mageto/app/code/local/Sanji/ShaModule/ShaModule.php
in this module its an empty file.
####################################################################

mageto/app/code/local/Sanji/ShaModule/etc/config.xml

this is the content of config.xml file.



<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : config.xml
    Created on : July 26, 2012, 1:12 PM
    Author     : sanjeewani
    Description:
        Purpose of the document follows.
-->

<config>
    <modules>
        <Sanji_ShaModule>
            <version>0.1.0</version>
            <depends>
             <Mage_Core />
            </depends>
        </Sanji_ShaModule>
    </modules>

    <global>
        <models>
            <core>
                <rewrite>
                 <encryption>Sanji_ShaModule_Model_Encryption</encryption>
                </rewrite>
            </core>
        </models>
        <helpers>
            <core>
             <encryption_model>Sanji_ShaModule_Model_Encryption</encryption_model>
            </core>
        </helpers>
    </global>

    <frontend>
        <routers>
            <sanji_shamodule>
             <use>standard</use>
                <args>
                    <module>Sanji_ShaModule</module>
                    <frontName>shamodule</frontName>
                </args>
            </sanji_shamodule>
        </routers>
    </frontend>
</config>


########################################################################
mageto/app/code/local/Sanji/ShaModule/Model/Encryption.php
you should override the parent encryption function inside your module. so extend  parent class to your model class.


<?php
class Sanji_ShaModule_Model_Encryption extends Mage_Core_Model_Encryption
{

   public function getHash($password, $salt = false)
    {
        return $this->hash($password);
    }
   public function hash($data){
       //die('came');

        return sha1($data); //magento through create customer and other
    }

    public function validateHash($password, $hash) {
        return $this->hash($password) === $hash;

        }
}
?>


####################################################################
put this file to below path Sanji_ShaModule.xml.this is the your module installation file to magento.
magento/app/etc/modules/

content of Sanji_ShaModule.xml file is below.


<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : Sanji_ShaModule.xml
    Created on : July 26, 2012, 1:17 PM
    Author     : sanjeewani
    Description:
        Purpose of the document follows.
-->


<config>

    <modules>

        <Sanji_ShaModule>

            <active>true</active>

            <codePool>local</codePool>

        </Sanji_ShaModule>

    </modules>

</config>




****
Make sure clear session data and cache data  from magento.
session data path -magento/var/session/
cache data path   -magento/var/cache/
****


After that go to admin login page  and  go with your admin username and password. I think  can't log with previous account password. then you go to database and change password (sha1('password')) with sha1 value. then you can log and change every thing with sha1 encryption.

Sunday, November 18, 2012

Customer migrate from programmacally

we can migrate customer using direct accessing with model class. its so faster than using soap api.(*4 faster)


<?php
date_default_timezone_set(date_default_timezone_get());
$timezone=date_default_timezone_get();
require_once('../config/script_config.php');
require_once('../class/error_log_class.php');
require_once('../class/db_class.php');
require_once('../class/common_functions.php');


 $time_now = date("Y-m-d G:i:s");
 echo '# --start time'.$time_now;

print("\n# Starting Script (customer Create)\n");
print("# Memory Usage : ".round((memory_get_usage()/1048576),2) ."MB \n");

$com_func = new CommonFunctions();
$com_func->setCustomParameters( array("-nor") );
$cmd_args = $com_func->getArgs($argv);

$mage_num_rec   = $cmd_args['-nor'];

$log = new Logger(LOG_PATH.'customer_create_log.txt', LOG_LEVEL);

$setUTF="SET character_set_results =  'utf8',
             character_set_client =  'utf8',
             character_set_connection = 'utf8',
             character_set_database =  'utf8',
             character_set_server =  'utf8';";

$db = new Database();
$db->connect();

try{



$query_max_id="SELECT  IFNULL(MAX(pp_cus_id),0) AS pp_cus_id FROM ".TBL_MIGRATION_CUSTOMER_CREATE."
                where email_duplicate=0;";
$db->queryExecute($query_max_id);
$rows = $db->getResult();


$query_dup_max_id="SELECT  IFNULL(MAX(pp_cus_id),0) AS pp_dup_cus_id FROM ".TBL_MIGRATION_CUSTOMER_CREATE."
               ;";
$db->queryExecute($query_dup_max_id);
$dup_rows = $db->getResult();


$last_cus_id =@$rows[0]['pp_cus_id'];
$last_dup_cus_id =@$dup_rows[0]['pp_dup_cus_id'];


if($last_cus_id==0 && $last_dup_cus_id ==0 ){

echo "Migrating customers with duplicate email addresses \n";
$exquery = " SELECT COUNT( cs.cus_id ) ,
                                    cs.cus_id,
                                    cs.cus_vatnumber,
                                    cs.cus_created,
                                    cs.cus_enabled,
                                    cs.date_of_birth,
                                    cs.cus_f_name,
                                    cs.cus_l_name,
                                    cs.cus_email,
                                    cs.password,
                                    cs.lang_id,
                                    cs.curr_id
                                FROM  (select * from `tbl_customer` ORDER BY cus_id DESC) AS cs
                                WHERE cs.cus_id >0 and cs.`cus_email`<>''
                                GROUP BY cs.`cus_email`
                                HAVING COUNT( cs.`cus_id` ) >1
                                ORDER BY cs.`cus_id` ASC ;";

}else{


$exquery = " SELECT  COUNT( cs.`cus_id` ),
                    cs.cus_id,
                    cs.cus_vatnumber,
                    cs.cus_created,
                    cs.cus_enabled,
                    cs.date_of_birth,
                    cs.cus_f_name,
                    cs.cus_l_name,
                    cs.cus_email,
                    cs.password,
                    cs.lang_id,
                    cs.curr_id
                    FROM  `tbl_customer` cs
                    WHERE cs.cus_id >$last_cus_id
                    AND cs.`cus_email` <>  ''
                    GROUP BY cs.`cus_email`
                    HAVING COUNT( cs.`cus_id` ) =1
                    ORDER BY cs.`cus_id` ASC
                    LIMIT $mage_num_rec ;";

 }


$db->executeNonReturn($setUTF);
$db->queryExecute($exquery);
$res = $db->getResult();
//print_r($res);
$res_count = count($res);

if($res_count==0){
    $log->LogInfo("No Customers For Migrate in given limit $time_now ");
      die("No Customers For Migrate in given limit");

}


print("# $res_count Customers For Migrate \n");
$log->LogInfo("succesefully connect to mysql and found $res_count Customers For Migrate  ");

}  catch (Exception $e){
$log->LogError(" Login Faild for mysql " .$time_now."..\n");
die("Login Faild for mysql....\n");

}


$num =0;

// try {
//
//        // If some stuff requires api authentification,
//        $client = new SoapClient(WSDL_URL);
//        // then get a session token
//        $session = $client->login(API_USER, API_PWD);
//
//
//        print("# Succsefully Connect To SOAP Server And Logged Succsesfully \n");
//         $log->LogInfo("# Succsefully Connect To SOAP Server And Logged Succsesfully $time_now ");
//
//    } catch (Exception $exc) {
//        print("# There Was an Error , When Try to Connect SOAP server \n");
//        $log->LogError(" Login Faild for " . API_USER);
//        die("SOAP Connection Error. Data -" . $time_now."..\n");
//    }

// path to mage.php
ini_set('include_path', ini_get('include_path') .
PATH_SEPARATOR . INCLUDE_PATH .
PATH_SEPARATOR . dirname(__FILE__));

// include mage.php
include INCLUDE_FILE;

Mage::init();
date_default_timezone_set($timezone);

foreach ($res as $value) {
    //for local Dev Tesing
    $num++;
    $result = null;
    $pp_customer_id=$value['cus_id'];

    $date1=$value['cus_created'];

    // define groups
        $sqlGruop="SELECT t.order_id,IFNULL(teo.ex_seller_id,0) as cus_group_id
            FROM tbl_order t
            join tbl_external_order teo
            on t.order_id=teo.order_id
            left join tbl_external_seller tes
            on tes.ex_id=teo.ex_seller_id
            where t.cus_id=$pp_customer_id
            order by t.order_id DESC";
            $db->executeNonReturn($setUTF);
            $db->queryExecute($sqlGruop);
            $groups = $db->getResult();

            @$pp_group_id = $groups[0]['cus_group_id'];

            if(isset ($pp_group_id)){
                $cus_group_id=$pp_group_id;
            }else{
                 $cus_group_id=DIRECT;
            }
    //end of the define groups

   // settype($is_active, "SmallInt");
  $is_active=($value['cus_enabled']==1?0:1);

      if($value['cus_f_name']==''){
        $fname='.';
      }else{
         $fname=$value['cus_f_name'] ;
      }

          if ($value['cus_l_name']==''){
            $lname='-';
          }else{
           $lname=$value['cus_l_name'] ;
          }


   $web_id=$value['curr_id'];
   $st_id=$value['lang_id'];

   $website_id;
   $store_id;

  if(isset ($value['curr_id'])){
      if($web_id==CURR_USD_ID){
          //USD
          $wesite_id=USD_SITE_ID;
          $store_id=ENGLISH_US_STORE_VIEW_ID;
          }
      else if($web_id==CURR_EUR_ID){
          //Euro
          $wesite_id=EUR_SITE_ID;
          if($st_id==LANG_FR){$store_id=FRENCH_STORE_VIEW_ID;}
          else if($st_id==LANG_DE){$store_id=GERMAN_STORE_VIEW_ID;}
          else if($st_id==LANG_ES){$store_id=ESPANOL_STORE_VIEW_ID;}
          else if($st_id==LANG_IT){$store_id=ITALIANO_STORE_VIEW_ID;}
          else if($st_id==LANG_PT){$store_id=PORTUGUES_STORE_VIEW_ID;}

          }
      else if($web_id==CURR_GBP_ID){
          //GBP
          $wesite_id=GBP_SITE_ID;
          $store_id=ENGLISH_UK_STORE_VIEW_ID;
          }
  }else{
      $wesite_id=GBP_SITE_ID;
      $store_id=ENGLISH_UK_STORE_VIEW_ID;
  }
$email= $value['cus_email'];

/// echo "email--$email --";
// //die ();//

    try {

        $customerInfo = array(
                'customer_id'=> $value['cus_id'],
                'created_at' => $date1,
                'taxvat'     => $value['cus_vatnumber'],
                'firstname'  => $fname,
                'lastname'   => $lname,
                'email'      => $email,
                'confirmation' => $is_active,
                'password_hash' => $value['password'],
                'dob' =>  $value['date_of_birth'],
                'website_id'=> $wesite_id,
                'store_id' => $store_id,
                'group_id' => $cus_group_id,
                'created_in' =>'Admin'
              );
              //print_r($customerInfo);
              //die ();
        if($last_cus_id==0 && $last_dup_cus_id ==0){
            $duplicate=1;
            $migrated=1;
            $email=$email;
        }else{
             $duplicate=0;
             $migrated=1;
        }

$customer_email = $email;  // email adress that will pass by the questionaire
$customer_fname =$fname;      // we can set a tempory firstname here
$customer_lname = $lname;       // we can set a tempory lastname here
//$passwordLength = 10;                    // the lenght of autogenerated password

$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId($wesite_id);
$customer->loadByEmail($customer_email);
/*
* Check if the email exist on the system.
* If YES,  it will not create a user account.
*/

if(!$customer->getId()) {

   //setting data such as email, firstname, lastname, and password

  $customer->setEmail($customer_email);
  $customer->setTaxvat($value['cus_vatnumber'])
          ->setCreatedAt($date1)
          ->setDob($value['date_of_birth'])
          ->setGroupId($cus_group_id)
          ->setConfirmation($is_active)
          ->setCreatedIn('Admin')
          ->setStoreId($store_id)
          ->setWebsiteId($wesite_id)
          ->setEntityId($value['cus_id']);
  $customer->setFirstname($customer_fname);
  $customer->setLastname($customer_lname);
  $customer->setPassword( $value['password']);

}

  //the save the data and send the new account email.
  $customer->save();
  $result=$customer->getId();
  //$customer->setConfirmation(null);
  //$customer->save();
  //$customer->sendNewAccountEmail();
  //
  //api funtion calling
     //$result=$client->call($session, 'customer.create',array($customerInfo));
        $log->LogInfo("New Customer Created With pp_cus_id-" .$pp_customer_id."  Magento id-$result and  Sucsesfully Added to Magento DB ");
        //var_dump($result);
           ///--------------------------------map the table(magento and pp)

            $exquery_map = "INSERT INTO ".TBL_MIGRATION_CUSTOMER_CREATE." (
                        `pp_cus_id` ,`mage_id`,email_duplicate,migrated)
                        VALUES (
                        $pp_customer_id, $result,$duplicate,$migrated);";

            $res = $db->executeNonReturn($exquery_map);
   if ( !$res ) throw new Exception("Insert failed to mapping table. SQL: ".$exquery_map);
            $log->LogInfo(" pp_cus_id-" .$pp_customer_id." and Magento id-$result Sucsesfully Added PP Mapping table ");


            if($last_cus_id==0 && $last_dup_cus_id ==0){

            $migrated=0;
            $result=0;
            $duplicate=1;
            $dulicate_email_not_migrated_sql="SELECT cus_id FROM tbl_customer
                                                    where cus_email='".$email."'
                                                    ORDER BY `cus_id` ASC ;";

                $db->queryExecute($dulicate_email_not_migrated_sql);
                $res_dulicate_email_not_migrated_sql = $db->getResult();
                $res_dulicate_email_not_migrated_count = count($res_dulicate_email_not_migrated_sql);

            for($i=0;$i< $res_dulicate_email_not_migrated_count-1;$i++){

                     $pp_customer_not_migrated_id=$res_dulicate_email_not_migrated_sql[$i]['cus_id'];

                     $exquery_map = "INSERT INTO ".TBL_MIGRATION_CUSTOMER_CREATE." (
                                `pp_cus_id` ,`mage_id`,email_duplicate,migrated)
                                VALUES (
                                $pp_customer_not_migrated_id, $result,$duplicate,$migrated);";

                    $res = $db->executeNonReturn($exquery_map);
                    if ( !$res ) throw new Exception("Insert failed to mapping table. SQL: ".$exquery_map);
                    $log->LogInfo(" pp_cus_id-" .$pp_customer_not_migrated_id."-- duplicating Email - not migrated to magento  ");
            }
        }

        ///----------------------------------
       // print("# Customer id $pp_customer -  Migrate Sucsesfully -new Magento Id- $result \n");

    } catch (Exception $exc) {
        print("pp Customer Id ".$pp_customer_id." -  Migrate Fail..!!!!\n");
        $log->LogError(" Error Occerd Customer id " .$pp_customer_id . " Migrate ".$exc);
        die("pp Customer Id ".$pp_customer_id." -  Migrate Fail..!!!!...\n");
        //continue;


    }




}

print("# ---End Of customer Migration Script----\n");
print("# Memory Usage : " . round((memory_get_usage() / 1048576), 2) . "MB \n");
$time_end = date("Y-m-d G:i:s");
print "# --End time'.$time_end.....\n";
?>

Magento SOAP API customer create

My first experience with Magento Creating customers in magento using soap api. (Reffer-http://www.magentocommerce.com/api/soap/introduction.html )

Task-Migrate current customers to magento system.

Note- But using SOAP api its wasting time to migrate. so i used model class directly to migrate  customers.but this is the perfect way to migrate customers.

*****
in this way we can migrate customer addresses, products, orders and any other things in current e-commerce sites.
*****


customer_create.php

<?php

require_once('../config/script_config.php');
require_once('../class/error_log_class.php');
require_once('../class/db_class.php');
require_once('../class/common_functions.php');


 $time_now = date("Y-m-d G:i:s");
 echo '# --start time'.$time_now;

print("\n# Starting Script (customer Create)\n");
print("# Memory Usage : ".round((memory_get_usage()/1048576),2) ."MB \n");

$com_func = new CommonFunctions();
$com_func->setCustomParameters( array("-nor") );
$cmd_args = $com_func->getArgs($argv);

$mage_num_rec   = $cmd_args['-nor'];

$log = new Logger(LOG_PATH.'customer_create_log.txt', LOG_LEVEL);

$setUTF="SET character_set_results =  'utf8',
             character_set_client =  'utf8',
             character_set_connection = 'utf8',
             character_set_database =  'utf8',
             character_set_server =  'utf8';";

$db = new Database();
$db->connect();

try{
 


$query_max_id="SELECT  IFNULL(MAX(pp_cus_id),0) AS pp_cus_id FROM ".TBL_MIGRATION_CUSTOMER_CREATE."
                where email_duplicate=0;";
$db->queryExecute($query_max_id);
$rows = $db->getResult();


$query_dup_max_id="SELECT  IFNULL(MAX(pp_cus_id),0) AS pp_dup_cus_id FROM ".TBL_MIGRATION_CUSTOMER_CREATE."
               ;";
$db->queryExecute($query_dup_max_id);
$dup_rows = $db->getResult();


$last_cus_id = $rows[0]['pp_cus_id'];
$last_dup_cus_id = $dup_rows[0]['pp_dup_cus_id'];


if($last_cus_id==0 && $last_dup_cus_id ==0 ){

echo "Migrating customers with duplicate email addresses \n";
$exquery = " SELECT COUNT( cs.cus_id ) ,
                                    cs.cus_id,
                                    cs.cus_vatnumber,
                                    cs.cus_created,
                                    cs.cus_enabled,
                                    cs.date_of_birth,
                                    cs.cus_f_name,
                                    cs.cus_l_name,
                                    cs.cus_email,
                                    cs.password,
                                    cs.lang_id,
                                    cs.curr_id
                                FROM  (select * from `tbl_customer` ORDER BY cus_id DESC) AS cs
                                WHERE cs.cus_id >0 and cs.`cus_email`<>''
                                GROUP BY cs.`cus_email`
                                HAVING COUNT( cs.`cus_id` ) >1
                                ORDER BY cs.`cus_id` ASC ;";

}else{


$exquery = "SELECT COUNT( cs.`cus_id` ) ,
                    cs.cus_id,
                    cs.cus_vatnumber,
                    cs.cus_created,
                    cs.cus_enabled,
                    cs.date_of_birth,
                    cs.cus_f_name,
                    cs.cus_l_name,
                    cs.cus_email,
                    cs.password,
                    cs.lang_id,
                    cs.curr_id
                    FROM  `tbl_customer` cs
                    JOIN tbl_order tr ON cs.`cus_id` = tr.`cus_id`
                    JOIN tbl_order_part tp ON tr.order_id = tp.order_id
                    WHERE cs.cus_id >$last_cus_id
                    AND cs.`cus_email` <>  ''
                    AND tr.order_status<>0 and tr.order_status<>7
                    AND tp.op_completed
                    BETWEEN  '".ORDER_FROM_DATE."'
                    AND  '".ORDER_TO_DATE."'
                    GROUP BY cs.`cus_email`
                    HAVING COUNT( cs.`cus_id` ) =1
                    ORDER BY cs.`cus_id` ASC
                    LIMIT $mage_num_rec ;";
 }



$db->executeNonReturn($setUTF);
$db->queryExecute($exquery);
$res = $db->getResult();
//print_r($res);
$res_count = count($res);

if($res_count==0){
    $log->LogInfo("No Customers For Migrate in given limit $time_now ");
      die("No Customers For Migrate in given limit");

}
 

print("# $res_count Customers For Migrate \n");
$log->LogInfo("succesefully connect to mysql and found $res_count Customers For Migrate  ");

}  catch (Exception $e){
$log->LogError(" Login Faild for mysql " .$time_now."..\n");
die("Login Faild for mysql....\n");

}


$num =0;

 try {

        // If some stuff requires api authentification,
        $client = new SoapClient(WSDL_URL);
        // then get a session token
        $session = $client->login(API_USER, API_PWD);


        print("# Succsefully Connect To SOAP Server And Logged Succsesfully \n");
         $log->LogInfo("# Succsefully Connect To SOAP Server And Logged Succsesfully $time_now ");

    } catch (Exception $exc) {
        print("# There Was an Error , When Try to Connect SOAP server \n");
        $log->LogError(" Login Faild for " . API_USER);
        die("SOAP Connection Error. Data -" . $time_now."..\n");
    }  

foreach ($res as $value) {
    //for local Dev Tesing
    $num++;
    $result = null;
    $pp_customer_id=$value['cus_id'];

    $date1=$value['cus_created'];

    // define groups
        $sqlGruop="SELECT t.order_id,IFNULL(teo.ex_seller_id,0) as cus_group_id
            FROM tbl_order t
            join tbl_external_order teo
            on t.order_id=teo.order_id
            left join tbl_external_seller tes
            on tes.ex_id=teo.ex_seller_id
            where t.cus_id=$pp_customer_id
            order by t.order_id DESC";
            $db->executeNonReturn($setUTF);
            $db->queryExecute($sqlGruop);
            $groups = $db->getResult();

            @$pp_group_id = $groups[0]['cus_group_id'];

            if(isset ($pp_group_id)){
                $cus_group_id=$pp_group_id;
            }else{
                 $cus_group_id=DIRECT;
            }
    //end of the define groups

   // settype($is_active, "SmallInt");
  $is_active=($value['cus_enabled']==1?0:1);

      if($value['cus_f_name']==''){
        $fname='.';
      }else{
         $fname=$value['cus_f_name'] ;
      }

          if ($value['cus_l_name']==''){
            $lname='-';
          }else{
           $lname=$value['cus_l_name'] ;
          }

 
   $web_id=$value['curr_id'];
   $st_id=$value['lang_id'];

   $website_id;
   $store_id;

  if(isset ($value['curr_id'])){
      if($web_id==CURR_USD_ID){
          //USD
          $wesite_id=USD_SITE_ID;
          $store_id=ENGLISH_US_STORE_VIEW_ID;
          }
      else if($web_id==CURR_EUR_ID){
          //Euro
          $wesite_id=EUR_SITE_ID;
          if($st_id==LANG_FR){$store_id=FRENCH_STORE_VIEW_ID;}
          else if($st_id==LANG_DE){$store_id=GERMAN_STORE_VIEW_ID;}
          else if($st_id==LANG_ES){$store_id=ESPANOL_STORE_VIEW_ID;}
          else if($st_id==LANG_IT){$store_id=ITALIANO_STORE_VIEW_ID;}
          else if($st_id==LANG_PT){$store_id=PORTUGUES_STORE_VIEW_ID;}

          }
      else if($web_id==CURR_GBP_ID){
          //GBP
          $wesite_id=GBP_SITE_ID;
          $store_id=ENGLISH_UK_STORE_VIEW_ID;
          }
  }else{
      $wesite_id=GBP_SITE_ID;
      $store_id=ENGLISH_UK_STORE_VIEW_ID;
  }
$email= $value['cus_email'];

/// echo "email--$email --";
// //die ();//

    try {

        $customerInfo = array(
                'customer_id'=> $value['cus_id'],
                'created_at' => $date1,
                'taxvat'     => $value['cus_vatnumber'],
                'firstname'  => $com_func->convert_to_UTF($fname),
                'lastname'   => $com_func->convert_to_UTF($lname),
                'email'      => $email,
                'confirmation' => $is_active,
                'password_hash' => $value['password'],
                'dob' =>  $value['date_of_birth'],
                'website_id'=> $wesite_id,
                'store_id' => $store_id,
                'group_id' => $cus_group_id,
                'created_in' =>'Admin'
              );
              //print_r($customerInfo);
              //die ();
        if($last_cus_id==0 && $last_dup_cus_id ==0){
            $duplicate=1;
            $migrated=1;
            $email=$com_func->convert_to_UTF($email);
        }else{
             $duplicate=0;
             $migrated=1;
        }

       
//encoding="utf-8"
     $result=$client->call($session, 'customer.create',array($customerInfo));
        $log->LogInfo("New Customer Created With pp_cus_id-" .$pp_customer_id."  Magento id-$result and  Sucsesfully Added to Magento DB ");
        //var_dump($result);
           ///--------------------------------map the table(magento and pp)
       
            $exquery_map = "INSERT INTO ".TBL_MIGRATION_CUSTOMER_CREATE." (
                        `pp_cus_id` ,`mage_id`,email_duplicate,migrated)
                        VALUES (
                        $pp_customer_id, $result,$duplicate,$migrated);";
         
            $res = $db->executeNonReturn($exquery_map);
   if ( !$res ) throw new Exception("Insert failed to mapping table. SQL: ".$exquery_map);
            $log->LogInfo(" pp_cus_id-" .$pp_customer_id." and Magento id-$result Sucsesfully Added PP Mapping table ");


            if($last_cus_id==0 && $last_dup_cus_id ==0){

            $migrated=0;
            $result=0;
            $duplicate=1;
            $dulicate_email_not_migrated_sql="SELECT cus_id FROM tbl_customer
                                                    where cus_email='".$email."'
                                                    ORDER BY `cus_id` ASC ;";

                $db->queryExecute($dulicate_email_not_migrated_sql);
                $res_dulicate_email_not_migrated_sql = $db->getResult();
                $res_dulicate_email_not_migrated_count = count($res_dulicate_email_not_migrated_sql);

            for($i=0;$i< $res_dulicate_email_not_migrated_count-1;$i++){

                     $pp_customer_not_migrated_id=$res_dulicate_email_not_migrated_sql[$i]['cus_id'];

                     $exquery_map = "INSERT INTO ".TBL_MIGRATION_CUSTOMER_CREATE." (
                                `pp_cus_id` ,`mage_id`,email_duplicate,migrated)
                                VALUES (
                                $pp_customer_not_migrated_id, $result,$duplicate,$migrated);";

                    $res = $db->executeNonReturn($exquery_map);
                    if ( !$res ) throw new Exception("Insert failed to mapping table. SQL: ".$exquery_map);
                    $log->LogInfo(" pp_cus_id-" .$pp_customer_not_migrated_id."-- duplicating Email - not migrated to magento  ");
            }
        }

        ///----------------------------------
       // print("# Customer id $pp_customer -  Migrate Sucsesfully -new Magento Id- $result \n");
         
    } catch (Exception $exc) {
        print("pp Customer Id ".$pp_customer_id." -  Migrate Fail..!!!!\n");
        $log->LogError(" Error Occerd Customer id " .$pp_customer_id . " Migrate ".$exc);
        //die("pp Customer Id ".$pp_customer_id." -  Migrate Fail..!!!!...\n");
        continue;
       

    }




}

print("# ---End Of customer Migration Script----\n");
print("# Memory Usage : " . round((memory_get_usage() / 1048576), 2) . "MB \n");
$time_end = date("Y-m-d G:i:s");
print "# --End time'.$time_end.....\n";

?>