<?php 
ini_set('max_execution_time', 28800000);
require("../config/config.php");

$list_sql = "select * from import_customer_data where status ='0' order by id asc";
$customer_data = $db_cust->query($list_sql);

$total_cnt = $db_cust->affected_rows;

if($total_cnt > 0){
    while($rec = $db_cust->fetch_array($customer_data)){
        $sql = "select customer_id from customers order by customer_id desc limit 0,1";
        $code_result = $db_cust->query_first($sql);
        if($db_cust->affected_rows > 0){
            $last_customer_id = $code_result['customer_id'] + 1;
        }else{
            $last_customer_id = 1;
        }

        $city_sql = "select id,city_code from cities where location ='" . $rec['city'] . "' limit 0,1 ";
        $city_res = $db_cust->query_first($city_sql);
        if ($db_cust->affected_rows > 0) {
            $data['customer_city_code'] = $city_res['city_code'];
        }

        $country_sql = "select id,CountryRegionId from master_country where ShortName ='" . $rec['country'] . "' limit 0,1 ";
        $country_res = $db_cust->query_first($country_sql);
        if ($db_cust->affected_rows > 0) {
            $data['customer_country'] = $country_res['CountryRegionId'];
        }

        $state_sql = "select id,state_name,state_code from states where state_name ='" . $rec['state'] . "' limit 0,1 ";
        $state_res = $db_cust->query_first($state_sql);
        if ($db_cust->affected_rows > 0) {
            $data['customer_state_code'] = $state_res['state_code'];
        }

        $data['customer_group'] = $rec['customer_group'];
        $data["customer_name"] = $rec['customer_name'];
        $data['customer_state'] = $rec['state'];
        $data["customer_address"] = $rec['address_1'];

        $data["customer_address_2"] = $rec['address_2'];
        $data["customer_address_3"] = $rec['address_3'];

        $data["customer_city"] = $rec['city'];
        $data["customer_pincode"] = $rec['zip_postal_code'];
        $data["customer_phone"] = $rec['phone'];
        $data["customer_fax"] = $rec['fax'];
        $data["customer_email_id"] = $rec['email'];
        $data["customer_website"] = $rec['website'];
        $data["customer_contact_person"] = $rec['customer_contact_name'];

        $data["customer_contact_person_phone"] = $rec['mobile'];

        $data["customer_created_ts"] = "NOW()";
        $data["customer_created_by"] = '1';
        $data["customer_from"] = '1';
        $data["customer_currency"] = $rec['currency'];

        $customer_code = "CUST".str_pad($last_customer_id, 6, '0', STR_PAD_LEFT);
        $data["customer_code"] = $customer_code;
        $data['import_status'] = 1;

        $db_cust->query_insert("customers", $data);
        unset($data);

        $db_cust->query("update import_customer_data set status = '1' where id ='".$rec['id']."'");

    }
    echo "Done.";
}else{
    echo "No data.";
}


//$db_cust->close();
?>
