<?php

/* * ********************************************
  Author: Joe Hunt
  Author: Tom Moulton - added Export of many types and import of the same
  Name: Import of CSV formatted items
  Free software under GNU GPL
 * ********************************************* */
$page_security = 'SA_CSVIMPORT';
$path_to_root = "../../..";
include_once($path_to_root . "/inventory/includes/item_adjustments_ui.inc");

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");

include_once($path_to_root . "/inventory/includes/inventory_db.inc");
include_once($path_to_root . "/inventory/includes/db/items_codes_db.inc");
include_once($path_to_root . "/dimensions/includes/dimensions_db.inc");

if (isset($_GET['NewAdjustment']) || !isset($_SESSION['adj_items'])) {
    handle_new_order();
}

function check_stock_id($stock_id) {
    $sql = "SELECT * FROM " . TB_PREF . "stock_master where stock_id = ". db_escape($stock_id);
    $result = db_query($sql, "Can not look up stock_id");
    $row = db_fetch_row($result);
    if (!$row[0])
        return 0;
    return 1;
}

function handle_new_order() {
    if (isset($_SESSION['adj_items'])) {
        $_SESSION['adj_items']->clear_items();
        unset($_SESSION['adj_items']);
    }

    $_SESSION['adj_items'] = new items_cart(ST_INVADJUST);
    $_SESSION['adj_items']->fixed_asset = isset($_GET['FixedAsset']);
    $_POST['date'] = new_doc_date();
    if (!is_date_in_fiscalyear($_POST['date']))
        $_POST['date'] = end_fiscalyear();
    $_SESSION['adj_items']->tran_date = $_POST['date'];
}

function can_process() {
    global $SysPrefs;

    $adj = &$_SESSION['adj_items'];

    if (count($adj->line_items) == 0) {
        display_error(_("You must enter at least one non empty item line."));
        set_focus('stock_id');
        return false;
    }

    if (!check_reference($_POST['ref'], ST_INVADJUST)) {
        set_focus('ref');
        return false;
    }

    if (!is_date($_POST['date'])) {
        display_error(_("The entered date for the adjustment is invalid."));
        set_focus('date');
        return false;
    } elseif (!is_date_in_fiscalyear($_POST['date'])) {
        display_error(_("The entered date is out of fiscal year or is closed for further data entry."));
        set_focus('date');
        return false;
    } elseif (!$SysPrefs->allow_negative_stock()) {
        $low_stock = $adj->check_qoh($_POST['location'], $_POST['date']);

        if ($low_stock) {
            display_error(_("The adjustment cannot be processed because it would cause negative inventory balance for marked items as of document date or later."));
            unset($_POST['import']);
            return false;
        }
    }
    return true;
}

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'];

    if ($etype == 1) {
        $fname = "items.csv";
        $sql = "SELECT 'ADJ' as type, sm.stock_id as item_code, sm.description, 0 as qty,0 as cost FROM " . TB_PREF . "stock_master sm 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 Items");

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 = 0;
        $errors = array();
        // type, item_code, stock_id, description, category, units, qty, mb_flag, currency, price
        while ($data = fgetcsv($fp, 4096, $sep)) {
            if ($lines++ == 0)
                continue;
            list($type, $code, $description, $qty, $cost) = $data;
            $type = strtoupper($type);

            if ($type == 'ADJ') {
                if (check_stock_id($code)) {
                    $item_info = get_item_edit_info($code);
                    add_to_order($_SESSION['adj_items'], $code, $qty, $item_info["material_cost"]);
                    $i++;
                } else {
                    $errors[] = "Stock $code | $description Item does not exist";
                }
            }
        }
        @fclose($fp);

        if (!count($errors) && can_process()) {
            $trans_no = add_stock_adjustment($_SESSION['adj_items']->line_items,
                    $_POST['location'], $_POST['date'], $_POST['ref'], "Bulk Stock Adjustment");
            new_doc_date($_POST['date']);
            $_SESSION['adj_items']->clear_items();
            unset($_SESSION['adj_items']);
        }
        if(count($errors)){
            foreach ($errors as $error){
                display_error($error);
            }
        } else if ($i > 0)
            display_notification("$i items QOH has been adjusted. Trans No.:".$trans_no);
    } 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%");

    if (!isset($_POST['sep']))
        $_POST['sep'] = ",";

    table_section_title("Adjustment Details");
    locations_list_row("To Location:", 'location', null);
    date_row(_("Date:"), 'date', '', true);
    ref_row(_("Reference:"), 'ref', '', $Refs->get_next(ST_INVADJUST, null, array('location' => get_post('location'), 'date' => get_post('date'))), false, ST_INVADJUST);
    text_row("Field separator:", 'sep', $_POST['sep'], 2, 1);
    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%");

    table_section_title("Export Selection");
    ?>
    <tr>
        <td>Export Type:</td>
        <td><select  name='export_type' class='combo' title='' >
                <option value='1'>Item</option>
            </select>
        </td>
    </tr>
    <?php

    end_table(1);

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

    end_form();
}

end_page();
