<?php
/**********************************************************************
	Copyright (C) Evolve Techniologies
	Author : Danushka Widanage
	Email : dwidanage@gmail.com
	Company : Evolve Technologies(pvt)Ltd
***********************************************************************/
$page_security = 'SA_CSVIMPORT_SUPPLIER';
$path_to_root="../..";

include($path_to_root . "/includes/session.inc");
add_access_extensions();

include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");






function download_file($filename, $saveasname='')
{
    if (empty($filename) || !file_exists($filename))
    {
        return false;
    }
    if ($saveasname == '') $saveasname = basename($filename);
    header('Content-type: application/vnd.ms-excel');
    header('Content-Length: '.filesize($filename));
    header('Content-Disposition: attachment; filename="'.$saveasname.'"');
    readfile($filename);

    return true;
}

// change this from file to mysql $result
function download_csv($filename, $saveasname='')
{
    if (empty($filename) || !file_exists($filename))
    {
        return false;
    }
    if ($saveasname == '') $saveasname = basename($filename);
    header('Content-type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="'.$saveasname.'"');
// print all results, converting data as needed
    return true;
}

$action = 'import';
if (isset($_GET['action'])) $action = $_GET['action'];
if (isset($_POST['action'])) $action = $_POST['action'];

if (isset($_POST['export'])) {
    $etype = 0;
    if (isset($_POST['export_type'])) $etype = $_POST['export_type'];
    $sales_type_id = 0;
    if (isset($_POST['sales_type_id'])) $sales_type_id = $_POST['sales_type_id'];
    $currency = "USD";
    if (isset($_POST['currency'])) $currency = $_POST['currency'];
    if ($etype == 1) {
        $fname = "items.csv";
        $sql = "SELECT 'ITEM' as type, sm.stock_id as item_code, sm.stock_id, sm.description, sc.description as category, sm.units, '' as dummy, sm.mb_flag, '' as price, d.name as dimension FROM ".TB_PREF."stock_master sm left join ".TB_PREF."stock_category sc on sm.category_id = sc.category_id left join ".TB_PREF."dimensions d on sm.dimension_id = d.id left join ".TB_PREF."prices as p on sm.stock_id = p.stock_id WHERE sm.inactive = 0";
    }

    $result = db_query($sql, "Could not select csv data");
    if (db_num_rows($result) > 0) {
        // header('Content-type: application/vnd.ms-excel');
        header('Content-type: text/x-csv');
        header('Content-Disposition: attachment; filename='.$fname);
        $i = 0;
        while ($csv = db_fetch_assoc($result)) {
            $hdr = '';
            $str = '';
            while (list($k, $d) = each($csv)) {
                if ($i == 0) $hdr .= $k . ",";
                $str .= htmlspecialchars_decode($d) . ",";
            }
            if ($i == 0) echo $hdr . "\n";
            echo $str."\n";
            $i++;
        }
        exit;
    } else display_notification("No Results to download.");
}

page("Import of CSV formatted Suppliers");

if (isset($_POST['import'])) {
	if (isset($_FILES['imp']) && $_FILES['imp']['name'] != '') {
		$filename = $_FILES['imp']['tmp_name'];
		$sep = $_POST['sep'];

		$fp = @fopen($filename, "r");
		if (!$fp)
			die("can not open file $filename");

		$lines = $i = $j = $k = $b = $u = $p = $pr = $dm_n = 0;
		// type, item_code, stock_id, description, category, units, qty, mb_flag, currency, price
		while ($data = fgetcsv($fp, 8192, $sep)) {
			//if ($lines++ == 0) continue;
			//list($type, $code, $id, $description, $category, $units, $qty, $mb_flag, $currency, $price) = $data;
			list($cust_name, $cust_address, $cust_phone, $cust_short_name,  $cust_email) = $data;
			$type = strtoupper($type);
			$mb_flag = strtoupper($mb_flag);

			//if ($type == 'ITEM') {
                     
				$cust_short_arry = str_split($cust_name, 15); 
				$cust_short_key = $cust_short_arry[0];
				//print_r($cust_short_key);	
				//exit;	     	
				    $sql = "INSERT INTO `".TB_PREF."debtors_master` (`name`, debtor_ref, address,curr_code, credit_status, payment_terms )
				   			VALUES ('$cust_name', '$cust_short_key', '$cust_address', 'USD', 1, 1)";
					db_query($sql, "The Contact Details could not be added 1");
					
					$sql = "SELECT MAX(debtor_no) AS new_debtor FROM `".TB_PREF."debtors_master`";
					$result = db_query($sql, "Cannot select");
					$grn_row = db_fetch_assoc($result);
					$debtor_no = $grn_row['new_debtor'];
					$new_debtor_no = $grn_row['new_debtor']+1;
					
					$sql = "INSERT INTO `".TB_PREF."cust_branch`(debtor_no, br_name, branch_ref, br_address, area, salesman, default_location, tax_group_id,
							sales_discount_account, receivables_account, payment_discount_account, default_ship_via, br_post_address, contact_name)
							VALUES ($debtor_no, '$cust_name', '$cust_short_key', '$cust_address', 1, 1, 'DEF', 1, '4510', '1200', '4500', 1, '$cust_address', '$cust_short_name')";
					db_query($sql, "The Contact Details could not be added 2");
					
					$sql = "INSERT INTO `".TB_PREF."crm_persons`(ref, name, address, phone, email)
							VALUES('$cust_name', '$cust_short_key', '$cust_address', '$cust_phone', '$cust_email')";
					db_query($sql, "The Contact Details could not be added 3");
					
					
					$sql = "SELECT MAX(person_id) AS new_person_id FROM `".TB_PREF."crm_contacts`";
					$result = db_query($sql, "Cannot select");
					$row_crm = db_fetch_assoc($result);
					$new_person_id = $row_crm['new_person_id']+1;
					
					$sql = "INSERT INTO `".TB_PREF."crm_contacts`(person_id, type, action, entity_id)
							VALUES ($new_person_id, 'cust_branch', 'general', $debtor_no)";
					db_query($sql, "The Contact 4");							




				  $i++;
			   
			//}

		}
		@fclose($fp);

		if ($i+$j > 0) display_notification("$i Customer posts created, $j Customer posts updated.");

	} else display_error("No CSV file selected");
}

if ($action == 'import') echo 'Import';
else hyperlink_params($_SERVER['PHP_SELF'], _("Import"), "action=import", false);
echo '&nbsp;|&nbsp;';
if ($action == 'export') echo 'Export';
else hyperlink_params($_SERVER['PHP_SELF'], _("Export"), "action=export", false);
echo "<br><br>";

if ($action == 'import') {
    start_form(true);

    start_table(TABLESTYLE2, "width=40%");


    table_section_title("Separator, Location, Tax and Sales Type");
    text_row("Field separator:", 'sep', $_POST['sep'], 2, 1);
    locations_list_row("To Location:", 'location', null);
    item_tax_types_list_row("Item Tax Type:", 'tax_type_id', null);
    sales_types_list_row("Sales Type:", 'sales_type_id', null);
    label_row("CSV Import File:", "<input type='file' id='imp' name='imp'>");

    end_table(1);

    submit_center('import', "Import CSV File");

    end_form();
}
if ($action == 'export') {
    start_form(true);

    start_table(TABLESTYLE2, "width=40%");

    $company_record = get_company_prefs();
    $currency = $company_record["curr_default"];
    hidden('currency', $currency);

    table_section_title("Export Selection");
?>
<tr>
<td>Export Type:</td>
<td><select  name='export_type' class='combo' title='' >
<option value='1'>Customer</option>
<option value='2'>Supplier</option>
</select>
</td>
</tr>
<?php
    sales_types_list_row("Sales Type (for Price Lists):", 'sales_type_id', null);

    end_table(1);

    hidden('action', 'export');
    submit_center('export', "Export CSV File");

    end_form();
}

    end_page();
?>
