<?php
ini_set('display_errors',1);
if (! defined ( 'sugarEntry' ) || ! sugarEntry) die ( 'Not A Valid Entry Point' );



//importProduktow();
//importKontrahentow();
importZamowien();
//ecmprices_ecmproducts
 

function importVatow(){
	global $current_user;
	$db_presta = getConnectionPresta();
	$db_saas = getConnectionSaas();
	
	foreach($db_saas->query('SELECT id FROM ecmvats') as $old_row) {
		$old_array[$old_row['id']] = true;
	}
	foreach($db_presta->query('
	SELECT 
		ps_tax_rules_group.id_tax_rules_group,
		ps_tax_rule.id_tax,
		ps_tax_lang.name,
		ps_tax.rate,
		ps_tax_rules_group.date_add,
		ps_tax_rules_group.date_upd
	FROM
		ps_tax_rules_group,
		ps_tax_rule,
		ps_tax_lang,
		ps_tax
	WHERE
		ps_tax_rules_group.id_tax_rules_group = ps_tax_rule.id_tax_rules_group
			AND ps_tax_rule.id_tax = ps_tax_lang.id_tax
			AND ps_tax_rule.id_tax = ps_tax.id_tax
	GROUP BY ps_tax_rules_group.id_tax_rules_group') as $category_row) {
		$insert_array = array();
		$insert_array['id'] = $category_row['id_tax_rules_group'];
		$insert_array['date_entered'] = $category_row['date_add'];
		$insert_array['date_modified'] = $category_row['date_upd'];
		$insert_array['modified_user_id'] = $current_user->id;
		$insert_array['assigned_user_id'] = $current_user->id;
		$insert_array['created_by'] = $current_user->id;
		$insert_array['deleted'] = 0;
		$insert_array['name'] = $category_row['name'];
		$insert_array['value'] = $category_row['rate'];
		$insert_array['id'] = $category_row['id_tax_rules_group'];
		
		if($old_array[$category_row['id_tax_rules_group']]){
			$db_saas->query("DELETE FROM ecmvats WHERE id='" . $category_row['id_category'] ."'");
		}
		$insert_keys = array_keys($insert_array);
		$insert_values = array_values($insert_array);
		$insert_query = "INSERT INTO ecmvats (" . implode(",",$insert_keys) .") VALUES ('" . implode("','",$insert_values) . "');";
		$db_saas->query($insert_query);
	}
}

function importKategorii(){
	global $current_user;
	$db_presta = getConnectionPresta();
	$db_saas = getConnectionSaas();
	$old_array = array();
	
	foreach($db_saas->query('SELECT id FROM ecmproductcategories') as $old_row) {
		$old_array[$old_row['id']] = true;
	}
	foreach($db_presta->query('SELECT * FROM ps_category') as $category_row) {
		$category_lang_result = $db_presta->query('SELECT * FROM ps_category_lang WHERE id_lang=2 AND id_category=' . $category_row['id_category']);
		$category_lang = $category_lang_result->fetch();
		
		$insert_array = array();
		$insert_array['id'] = $category_row['id_category'];
		$insert_array['date_entered'] = $category_row['date_add'];
		$insert_array['date_modified'] = $category_row['date_upd'];
		$insert_array['modified_user_id'] = $current_user->id;
		$insert_array['assigned_user_id'] = $current_user->id;
		$insert_array['created_by'] = $current_user->id;
		$insert_array['deleted'] = 0;
		$insert_array['name'] = $category_lang['name'];
		$insert_array['to_module'] = 'EcmProducts';

		if($old_array[$category_row['id_category']]){
			$db_saas->query("DELETE FROM ecmproductcategories WHERE id='" . $category_row['id_category'] ."'");
		}
		$insert_keys = array_keys($insert_array);
		$insert_values = array_values($insert_array);
		$insert_query = "INSERT INTO ecmproductcategories (" . implode(",",$insert_keys) .") VALUES ('" . implode("','",$insert_values) . "');";
		$db_saas->query($insert_query);
	}
}

function importProduktow(){
	importVatow();
	importKategorii();
	global $current_user;
	$db_presta = getConnectionPresta();
	$db_saas = getConnectionSaas();
	
	
	$res = $db_saas->query("SELECT id FROM ecmprices WHERE name='Presta' LIMIT 1");
	
	var_dump($res->num_rows);
	if($res->num_rows == 0){
		$db_saas->query("INSERT INTO ecmprices(id,name,deleted,active) VALUES ('" . uniqid ("ecmprice_",true) . "','Presta',0,1)");
	}
	foreach($db_saas->query("SELECT id FROM ecmprices WHERE name='Presta' LIMIT 1") as $tmp) {
		$prceid = $tmp['id'];
	}
	foreach($db_saas->query("SELECT id,value,name FROM ecmvats") as $tmp) {
		$vats[$tmp['id']] = $tmp;
	}
	
	foreach($db_presta->query('SELECT * FROM ps_product') as $product_row) {
		//usuwanie starego rekordu produktu
		$db_saas->query("DELETE FROM ecmproducts WHERE id='" . $product_row['id_product'] ."'");
		//usuwanie starej ceny
		$del_query = "DELETE FROM ecmprices_ecmproducts WHERE ecmprice_id='" . $prceid ."' AND ecmproduct_id='" . $product_row['id_product'] ."'";
		$db_saas->query($del_query);
		
		//pobieranie polskiej nazwy produktu
		$product_lang_result = $db_presta->query('SELECT * FROM ps_product_lang WHERE id_product=' . $product_row['id_product']);
		$product_lang = $product_lang_result->fetch();
		
		$insert_array = array();
		$insert_array['id'] = $product_row['id_product'];
		$insert_array['date_entered'] = $product_row['date_add'];
		$insert_array['date_modified'] = $product_row['date_upd'];
		$insert_array['modified_user_id'] = $current_user->id;
		$insert_array['assigned_user_id'] = $current_user->id;
		$insert_array['created_by'] = $current_user->id;
		$insert_array['deleted'] = 0;
		$insert_array['name'] = $product_lang['name'];
		$insert_array['code'] = $product_row['reference'];
		$insert_array['product_active'] = 1;
		$insert_array['unit_id'] = 1;
		$insert_array['status'] = 1;
		$insert_array['flag'] = 1;
		$insert_array['product_active'] =  $product_row['active'];
		
		$insert_array['vat_id'] = $product_row['id_tax_rules_group'];
		$insert_array['vat_value'] = $vats[$product_row['id_tax_rules_group']]['value'];
		$insert_array['vat_name'] = $vats[$product_row['id_tax_rules_group']]['name'];
		
		$insert_array['product_category_id'] = $product_row['id_category_default'];

		$price_query = "INSERT INTO ecmprices_ecmproducts VALUES ('" . uniqid ("presta_price",true) . "','" . $prceid . "','". $product_row['id_product'] ."','" . $product_row['price'] . "')";
		$db_saas->query($price_query);
		$insert_keys = array_keys($insert_array);
		$insert_values = array_values($insert_array);
		
		$insert_query = "INSERT INTO ecmproducts (" . implode(",",$insert_keys) .") VALUES ('" . implode("','",$insert_values) . "');";
		$db_saas->query($insert_query);
	}
}

function importKontrahentow(){
	global $current_user;
	$db_presta = getConnectionPresta();
	$db_saas =  getConnectionSaas();
	
	foreach($db_presta->query('SELECT * FROM ps_customer') as $customer_row) {
		$db_saas->query("DELETE FROM accounts WHERE id='" . $customer_row['id_customer'] ."'");
		$adress_result = $db_presta->query('SELECT * FROM ps_address WHERE id_customer=' . $customer_row['id_customer']);
		$adress = $adress_result->fetch();
		
		
		$insert_array = array();
		$insert_array['id'] = $customer_row['id_customer'];
		$insert_array['date_entered'] = $customer_row['date_add'];
		$insert_array['date_modified'] = $customer_row['date_upd'];
		$insert_array['modified_user_id'] = $current_user->id;
		$insert_array['assigned_user_id'] = $current_user->id;
		$insert_array['created_by'] = $current_user->id;
		$insert_array['deleted'] = 0;
		$insert_array['account_type'] = 'rec';
		$insert_array['name'] = trim($customer_row['firstname'] . ' ' . $customer_row['lastname']);
		$insert_array['billing_address_street'] = trim($adress['address1'] . ' ' .$adress['address2']);
		$insert_array['billing_address_city'] = trim($adress['city']);
		$insert_array['billing_address_postalcode'] = trim($adress['postcode']);
		//$insert_array['billing_address_country'] = 'Polska';
		$insert_array['register_address_street'] = trim($adress['address1'] . ' ' .$adress['address2']);
		$insert_array['register_address_city'] = trim($adress['city']);
		$insert_array['register_address_postalcode'] = trim($adress['postcode']);
		//$insert_array['register_address_country'] = 'Polska';
		//$insert_array['phone_office'] = round($order_row['total_products'],2);
		//$insert_array['phone_alternate'] = round($order_row['total_products_wt'],2);
		$insert_array['is_vat_free'] = 0;
		$insert_array['currency_id'] = 'PLN';
		$insert_array['invoice_type'] = 'K';
		$insert_array['index_dbf'] = $customer_row['email'];
		
		$insert_keys = array_keys($insert_array);
		$insert_values = array_values($insert_array);
		
		$insert_query = "INSERT INTO accounts (" . implode(",",$insert_keys) .") VALUES ('" . implode("','",$insert_values) . "');";
		$db_saas->query($insert_query);
		
	}
}

function importujStatusyZamowien(){
	$db_presta = getConnectionPresta();
	$db_saas = getConnectionSaas();
	foreach($db_presta->query('SELECT * FROM ps_order_state_lang where id_lang=2') as $status_row) {
		$db_saas->query("DELETE FROM dom_lists WHERE dom_name = 'ecmsales_status_dom' AND key='" .  $status_row['id_order_state'] ."' AND lang='pl_pl'");
		$db_saas->query("INSERT INTO dom_lists VALUES ('id_order_state_" . $status_row['id_order_state']. "', 'pl_pl','ecmsales_status_dom', '" . $status_row['id_order_state'] ."', '" .$status_row['name']  . "')");
	}
}

function importujMetodyPlatnosci(){
	$db_presta = getConnectionPresta();
	$db_saas = getConnectionSaas();
	foreach($db_presta->query('SELECT payment,module FROM ps_orders GROUP BY module') as $payment) {
		$db_saas->query("DELETE FROM dom_lists WHERE dom_name = 'payment_method_dom' AND key='" .  $payment['module'] ."' AND lang='pl_pl'");
		
		$db_saas->query("INSERT INTO dom_lists VALUES ('payment_method_dom_" . $payment['module']. "', 'pl_pl','payment_method_dom', '" . $payment['module'] ."', '" .$payment['payment']  . "')");
	} 
}

function importZamowien(){
	global $current_user;
	$db_presta = getConnectionPresta();
	$db_saas = getConnectionSaas();
	$EcmSale = new EcmSale();
	$EcmSysInfo = new EcmSysInfo();
	$number_template = $EcmSysInfo->getFormatNumberForModule('EcmSales');
	$stock_id = '9fc80fd4-fc09-f869-38f6-5641b962268d';
	foreach($db_saas->query("SELECT id,value,name FROM ecmvats") as $tmp) {
		$vats[$tmp['id']] = $tmp;
	}
	
	importujStatusyZamowien();
	importujMetodyPlatnosci();
	$db_saas->query("DELETE FROM ecmsales WHERE id != '9909730a-67ae-33c5-e22a-5658051e3fc0'");
	$db_saas->query("DELETE FROM ecmsaleitems WHERE id != '2a8f7cd5-bfe9-8be9-b306-566947b9d743'");
	


	foreach($db_presta->query('SELECT * FROM ps_orders') as $order_row) {
		$customer = null;
		$adress = null;
		$customer_result = $db_presta->query('SELECT * FROM ps_customer WHERE id_customer=' . $order_row['id_customer']);
		$customer = $customer_result->fetch();
		$adress_invoice_result = $db_presta->query('SELECT * FROM ps_address WHERE id_address=' . $order_row['id_address_invoice']);
		$adress_invoice = $adress_invoice_result->fetch();
		$adress_delivery_result = $db_presta->query('SELECT * FROM ps_address WHERE id_address=' . $order_row['id_address_delivery']);
		$adress_delivery = $adress_delivery_result->fetch();
		
		$document_no = '';
		if ($number_template != "") {
			require_once('include/ECM/EcmDocumentNumberGenerator/EcmDocumentNumberGenerator.inc.php');
			$dng = new EcmDocumentNumberGenerator('EcmSales');
			$document_no =  $dng->parseNumber($number_template, $stock_id);
		}
		
		$insert_array = array();
		$insert_array['id'] = $order_row['id_order'];
		$insert_array['date_entered'] = $order_row['date_add'];
		$insert_array['date_modified'] = $order_row['date_upd'];
		$insert_array['modified_user_id'] = $current_user->id;
		$insert_array['assigned_user_id'] = $current_user->id;
		$insert_array['created_by'] = $current_user->id;
		$insert_array['parent_document_no'] = $order_row['reference'];
		$insert_array['deleted'] = 0;
		$insert_array['document_no'] = $document_no;
		$insert_array['parent_id'] = $order_row['id_customer']; 
		$insert_array['parent_name'] = trim($customer['firstname'] . ' ' . $customer['lastname']);
		$insert_array['parent_index_dbf'] = $customer['email'];
		$insert_array['type'] = 'sales_order';
		$insert_array['status'] = $order_row['current_state'];
		$insert_array['register_date'] = $order_row['date_add'];
		$insert_array['parent_address_street'] = trim($adress_invoice['address1'] . ' ' .$adress_invoice['address2']);
		$insert_array['parent_address_city'] = trim($adress_invoice['city']);
		$insert_array['parent_address_postalcode'] = trim($adress_invoice['postcode']);
		$insert_array['parent_address_country'] = 'Polska';
		$insert_array['total_netto'] = round($order_row['total_products'],2);
		$insert_array['total_brutto'] = round($order_row['total_products_wt'],2);
		$insert_array['discount'] = round($order_row['total_discounts'],2);
		$insert_array['vats_summary'] = '';
		$insert_array['no_tax'] = 0;
		$insert_array['ecmpaymentcondition_text'] = $carrier['delay'];
		$insert_array['currency_id'] = 'PLN';
		$insert_array['delivery_date'] = substr($order_row['delivery_date'],0,10);
		$insert_array['shipping_address_street'] = trim($adress_delivery['address1'] . ' ' . $adress_delivery['address2']);
		$insert_array['shipping_address_city'] = trim($adress_delivery['city']);
		$insert_array['shipping_address_postalcode'] = trim($adress_delivery['postcode']);
		$insert_array['shipping_address_country'] = 'Polska';
		$insert_array['payment_method'] = $order_row['module'];
		
		$insert_keys = array_keys($insert_array);
		$insert_values = array_values($insert_array);
		
		$insert_query = "INSERT INTO ecmsales (" . implode(",",$insert_keys) .") VALUES ('" . implode("','",$insert_values) . "');";
		$db_saas->query($insert_query);
		foreach($db_presta->query('SELECT * FROM ps_order_detail WHERE id_order='. $order_row['id_order']) as $product_row) {
			$insert_product_array = array();
			$insert_product_array['id'] = $product_row['id_order_detail'];
			$insert_product_array['date_entered'] = $insert_array['date_entered'];
			$insert_product_array['date_modified'] = $insert_array['date_modified'];
			$insert_product_array['modified_user_id'] = $current_user->id;
			$insert_product_array['assigned_user_id'] = $current_user->id;
			$insert_product_array['created_by'] = $current_user->id;
			$insert_product_array['deleted'] = 0;
			$insert_product_array['ecmsale_id'] = $product_row['id_order'];
			$insert_product_array['ecmproduct_id'] = $product_row['product_id']; 
			
			$insert_product_array['code'] = $product_row['product_reference'];
			$insert_product_array['name'] = $product_row['product_name'];
			$insert_product_array['quantity'] = $product_row['product_quantity'];
			$insert_product_array['ecmvat_id'] = $product_row['id_tax_rules_group'];
			$insert_product_array['ecmvat_value'] = $vats[$product_row['id_tax_rules_group']]['value'];
			$insert_product_array['ecmvat_name'] = $vats[$product_row['id_tax_rules_group']]['name'];
			var_dump($product_row['id_tax_rules_group']); echo '<br>';
			var_dump($vats[$product_row['id_tax_rules_group']]); echo '<br>';
			//var_dump($product_row['id_tax_rules_group']); echo '<br>';
			$insert_product_array['price_start'] = $product_row['original_product_price'];
			$insert_product_array['price_netto'] = $product_row['unit_price_tax_excl'];
			$insert_product_array['price_brutto'] = $product_row['unit_price_tax_incl'];
			$insert_product_array['discount'] = $product_row['reduction_percent'];
			$insert_product_array['total_netto'] = $product_row['total_price_tax_excl'];
			$insert_product_array['total_brutto'] = $product_row['total_price_tax_incl'];

			
			$insert_product_keys = array_keys($insert_product_array);
			$insert_product_values = array_values($insert_product_array);
			$insert_product_query = "INSERT INTO ecmsaleitems (" . implode(",",$insert_product_keys) .") VALUES ('" . implode("','",$insert_product_values) . "');";
			$db_saas->query($insert_product_query);
		}
	}
}

function getConnectionPresta($host='localhost', $db_name='4ju', $user='root', $password='spire1234'){
	static $presta;
	if($presta == null){
		try {
			$presta = new PDO('mysql:host=' . $host.';dbname=' . $db_name .';charset=utf8', $user, $password);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			$presta = null;
			die();
		}
	}
	return $presta;
}

function getConnectionSaas($host='localhost', $db_name='preDb_8a7e080a76ef97c3e304cf463118ef9b', $user='root', $password='spire1234'){
	static $saas;
	if($saas == null){
		try {
			$saas = new PDO('mysql:host=' . $host.';dbname=' . $db_name .';charset=utf8', $user, $password);
		} catch (PDOException $e) {
			print "Error!: " . $e->getMessage() . "<br/>";
			$saas = null;
			die();
		}
	}
	return $saas;
}