<?php

/**
 * ModernBill -> ClientExec export tool.
 * Author: NEWEDGE Services Inc.
 * Website: www.newedge.com
 */

require_once dirname(__FILE__).'/include/config/config.locale.php';

$fp = tmpfile();
fwrite($fp, "***,users\n");
fwrite($fp, "id,firstname,lastname,address,email,city,state,zip,phone,country,company,status,password\n");
mysql_connect($locale_db_host, $locale_db_login, $locale_db_pass);
mysql_select_db($locale_db_name);

$query = "SELECT * FROM client_info";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $data = array(
                        $row['client_id'],
                       '"'.$row['client_fname'].'"',
                        '"'.$row['client_lname'].'"',
                        '"'.$row['client_address']." ".$row['client_address_2'].'"',
                        '"'.$row['client_email'].'"',
                        '"'.$row['client_city'].'"',
                        '"'.$row['client_state'].'"',
                        '"'.$row['client_zip'].'"',
                        '"'.$row['client_phone1'].'"',
                        '"'.$row['client_country'].'"',
                        '"'.$row['client_company'].'"',
                        '"'.status2ce($row['client_status']).'"',
                        '"'.$row['client_real_pass'].'"'
    );
    fwrite($fp, implode(",", $data)."\n");
}
fwrite($fp, "\n");

/* Packages */
fwrite($fp, "***,packages\n");
fwrite($fp, "id,name,monthly,quarterly,semiannually,annually,setup,description,packagetype\n");

$query = "SELECT pack_id, pack_name, pack_price, pack_setup, pack_comments, pack_display FROM package_type";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $prices = explode('|', $row['pack_price']);
    if (sizeof($prices) != 6) continue;
    $setup = explode('|', $row['pack_setup']);
    $data = array(
                        $row['pack_id'],
                        '"'.$row['pack_name'].'"',
                        $prices[0],
                        $prices[1],
                        $prices[2],
                        $prices[3],
                        $setup[0],
                        '"'.$row['pack_comments'].'"',
                        $row['pack_display']
    );
    fwrite($fp, implode(',', $data)."\n");
}
fwrite($fp, "\n");

/* Package Addons */
fwrite($fp, "***,packageaddons\n");
fwrite($fp, "id,packageid,description\n");

$query = "SELECT var_id, pack_id, variable_caption FROM package_variables";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $data = array(
                        $row['var_id'],
                        $row['pack_id'],
                        '"'.$row['variable_caption'].'"'
    );
    fwrite($fp, implode(',', $data)."\n");
}
fwrite($fp, "\n");

/* Package Addon Options */
fwrite($fp, "***,packageaddonoptions\n");
fwrite($fp, "packageaddonid,detail,monthly,quarterly,semiannually,annually,setup\n");

$query = "SELECT var_id, possible_values FROM package_variables";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $options = explode(',', $row['possible_values']);
    foreach ($options as $option) {
        $values = explode('|', $option);
        if (sizeof($values) != 8) continue;
        $data = array(
                        $row['var_id'],
                        '"'.trim($values[0]).'"',
                        $values[2],
                        $values[3],
                        $values[4],
                        $values[5],
                        $values[7]
        );
        fwrite($fp, implode(',', $data)."\n");
    }
}
fwrite($fp, "\n");

/* Client Packages */

/* Client Package Addons */

/* Client Invoices */
fwrite($fp, "***,invoices\n");
fwrite($fp, "id,clientid,amount,datedue,datepaid,description,detail,tax\n");
$query = "SELECT invoice_id, client_id, invoice_amount, invoice_date_due, invoice_date_paid, invoice_snapshot, invoice_comments, invoice_tax FROM client_invoice";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    $data = array(
                    $row['invoice_id'],
                    $row['client_id'],
                    $row['invoice_amount'],
                    date("Y-m-d", $row['invoice_date_due']),
                    ($row['invoice_date_paid'] > 0)? date("Y-m-d", $row['invoice_date_paid']) : 0,
                    '"Account Billing"',
                    '"'.str_replace("\n", " ", str_replace("\r\n", " ", strip_tags($row['invoice_snapshot']))).'"',
                    $row['invoice_tax']
    );
    fwrite($fp, implode(',', $data)."\n");	
}
fwrite($fp, "\n");

fseek($fp, 0);
$fstat = fstat($fp);

@set_time_limit(0);
ob_end_clean();
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"mbdata.csv\"");
header("Content-Length: ".$fstat['size']);

// work-around IE bug when using SSL
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header("Expires: 0");
while (!feof($fp)) { 
    echo fread($fp, 4096); 
}
fclose($fp);
exit;

function status2ce($status) {
    switch($status) {
        case '1': // inactive
            return -1;
        case '2': // active
            return 1;
        case '3': // pending
            return 0;
        case '4': // cancelled
            return -2;
        case '5': // fraud
            return -3;
        default: // just in case default to pending
            return 0;
    }
}
?>