<?php

$page_security = 'SA_SETUPCOMPANY';
//$page_security = 'SA_CSVIMPORT';
$path_to_root="../..";
global $unknown;

include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/modules/Kvcodes_importexport/includes/ui/allocation_cart.inc");
include($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/fixed_assets/includes/fixed_assets_db.inc");
include_once($path_to_root . "/inventory/includes/item_adjustments_ui.inc");
include_once($path_to_root . "/inventory/includes/inventory_db.inc");
include_once($path_to_root . "/gl/includes/db/gl_db_trans.inc");    
include_once($path_to_root . "/modules/Kvcodes_importexport/includes/import.inc"); 
include_once($path_to_root . "/admin/db/maintenance_db.inc");

add_access_extensions();
$js = '';
if ($SysPrefs->use_popup_windows)
    $js .= get_js_open_window(800, 500);


if(isset($_GET['dl'])){
    
    header("Content-type: text/csv");
    header('Content-Disposition: attachment; filename='.$_GET['dl']);
    echo file_get_contents(company_path().'/csv/tmp/'.$_GET['dl']); 
    if(file_exists(company_path().'/csv/tmp/'.$_GET['dl']) && !is_dir(company_path().'/csv/tmp/'.$_GET['dl']))     
        unlink(company_path().'/csv/tmp/'.$_GET['dl']);
    exit();
}

if(!get_post('_tabs_sel')){
    $_POST['_tabs_sel'] ='items';
    if(isset($_SESSION['chart_of_accounts'])){
        unset($_SESSION['chart_of_accounts']);
    }
    if(isset($_SESSION['dublicate_system_gls'])){
        unset($_SESSION['dublicate_system_gls']);
    } 
}elseif(get_post('_tabs_sel') !='chart_of_accounts'){
    if(isset($_SESSION['chart_of_accounts'])){
        unset($_SESSION['chart_of_accounts']);
    }
    if(isset($_SESSION['dublicate_system_gls'])){
        unset($_SESSION['dublicate_system_gls']);
    }  
}

if(isset($_POST["Export"])){
    global $SysPrefs, $path_to_root, $Refs;
        if(get_post('_tabs_sel') == 'items'){
            export_items();
        } elseif(get_post('_tabs_sel') == 'customers'){
            export_customers();
        }elseif(get_post('_tabs_sel') == 'suppliers'){
            export_suppliers();
        }elseif(get_post('_tabs_sel') == 'journal'){
            export_journal_entires();
        }elseif(get_post('_tabs_sel') =='chart_of_accounts'){
            backup_chart_of_accounts();
            if(!check_value('coa_ids'))
                export_coa_with_ids();
            else{
                export_chart_of_accounts();
            }
        }elseif(get_post('_tabs_sel') == 'bom'){
            export_bom();
        }
}

function can_process()
{
    if(get_post('_tabs_sel') == 'bank_statement' && $_POST['bank_name']==-1){
        display_error(_('Bank template should be selected'));
        return false;
    }
    return true;
}

if(isset($_POST["Import"]) && can_process()){
    global $SysPrefs, $path_to_root, $Refs;
    if(!file_exists(company_path().'/csv')){
        mkdir(company_path().'/csv');
    }

    $path_parts = pathinfo($_FILES["file"]["name"]);

    if($_FILES["file"]["name"] && ($_FILES['file']['type'] =='text/csv' || $path_parts['extension'] == 'csv' ) && $_FILES['file']['error']==0){
        $file_path =company_path()."/csv/".random_id();
        move_uploaded_file($_FILES['file']['tmp_name'],$file_path);

        if(get_post('_tabs_sel') == 'items'){
            import_items($file_path);
        }
        elseif(get_post('_tabs_sel') == 'fa_items'){
            import_fa_items($file_path);
        }
         elseif(get_post('_tabs_sel') == 'customers'){
            import_customers($file_path);
        }elseif(get_post('_tabs_sel') == 'suppliers'){
             import_suppliers($file_path);
        }elseif(get_post('_tabs_sel') == 'adjustment'){
             import_inventory($file_path);
        }
        elseif(get_post('_tabs_sel') == 'journal'){
             import_journal($file_path);
        }
        elseif(get_post('_tabs_sel') == 'bank_statement'){
            if($_POST['bank_name'] !=-1){
                import_bank_statements($file_path);
            }else{
                display_error('Select bank name');
            }
        }elseif(get_post('_tabs_sel')== 'chart_of_accounts'){
            if(!check_value('coa_ids'))
                import_chart_of_accounts_ids($file_path);
            else
                import_chart_of_accounts($file_path);
        }elseif(get_post('_tabs_sel') == 'bom'){
            import_bom($file_path);
        }
    }else{
       
        if($_FILES['file']['error']==4)display_error('No file selected');
        elseif($_FILES['file']['type'] !=='text/csv')
            display_error('Uploaded file must be .csv format');
        elseif($_FILES['file']['error']!=4)display_error('Error occurs in uploaded file');
    }
    //display_error($_FILES['file']['type'].$ext);
}

if(isset($_POST['submit_coa'])){
    if(!check_value('coa_ids'))
        import_coa_ids();
    else
        import_coa();       
}
if(get_post('coarestore')){
    import_coa_sql();
}
page("Import Export", false, false, "", $js);
// if(get_post('_tabs_sel') == 'items'){
//     page("Items CSV Import", false, false, "", $js);
// }
// elseif(get_post('_tabs_sel') == 'customers'){
//     page("Customers CSV Import", false, false, "", $js);
// }
// elseif(get_post('_tabs_sel') == 'suppliers'){
//     page("Suppliers CSV Import", false, false, "", $js);
// }
// elseif(get_post('_tabs_sel') == 'adjustment'){
//     page("Inventory Adjustment CSV Import", false, false, "", $js);
// }
// elseif(get_post('_tabs_sel') == 'journal'){
//     page("Journal Entries  CSV Import", false, false, "", $js);
// }
// elseif(get_post('_tabs_sel') == 'bank_statement'){
//     page("Bank Statement  CSV Import", false, false, "", $js);
// }elseif(get_post('_tabs_sel') == 'chart_of_accounts'){
//     page("Chart of accounts  CSV Import", false, false, "", $js);
// }elseif(get_post('_tabs_sel') == 'bom'){
//     page("BOM CSV Import", false, false, "", $js);
// }


function view_popup_link($link_text, $url, $icon=false)
{
    global $path_to_root;
    
    if (user_graphic_links() && $icon)
        $link_text = set_icon($icon, $link_text);

    $href = $path_to_root . $url;
    // <a target='_blank' href='$path_to_root/gl/manage/exchange_rates.php?' onclick=\"javascript:openWindow(this.href,this.target); return false;\"> here</a>
    return "<a target='_blank' href='$href' onclick=\"javascript:openWindow(this.href,this.target); return false;\">" . $link_text . "</a>";
}


function get_system_gls(){
    return $system_gl = [
    'retained_earnings_act' => _('Retained Earnings'), 
    'profit_loss_year_act' => _('Profit/Loss Year'), 
    'exchange_diff_act' => _('Exchange Variances Account'), 
    'bank_charge_act' => _('Bank Charges Account'), 


    'freight_act' => _('Shipping Charged Account'), 
    'deferred_income_act' => _('Deferred Income Account'), 


    'debtors_act' => _('Receivable Account'), 
    'default_sales_act' => _('Customer Sales Account'), 
    'default_sales_discount_act' => _('Sales Discount Account'), 
    'default_prompt_payment_act' => _('Prompt Payment Discount Account'), 


    'creditors_act' => _('Payable Account'), 
    'pyt_discount_act' => _('Purchase Discount Account'), 
    'grn_clearing_act' => _('GRN Clearing Account'),


    'default_inv_sales_act' => _('Inventory Sales Account'), 
    'default_inventory_act' => _('Inventory Account'),
    'default_cogs_act' => _('C.O.G.S. Account'), 
    'default_adj_act' => _('Inventory Adjustments Account'),
    'default_wip_act' => _('WIP Account'), 


    'default_loss_on_asset_disposal_act' => _('Loss On Asset Disposal Account'),
    ];
}
function system_gls_cells($name,$selected_id=null,$all_option=false){
    

     $options =array('spec_option'=> $all_option?$all_option:$all_option,
        'spec_id' => -1,
        'selected_id'=>$selected_id);
    echo "<td>";
    echo array_selector($name, null, get_system_gls(),$options);
    echo "</td>";

}

function banks_list_row($label,$name, $selected_id=null, $all_option=false,$submit_on_change=false){
    global $path_to_root;
    $banks_list =array();
    $dir=$path_to_root . "/modules/Kvcodes_importexport/includes/bank_templates";
    $bank_templates = scandir($dir);
    

    foreach ($bank_templates as $key => $bank_template) {
        if($bank_template =="."|| $bank_template == "..")
            continue;
        $file =fopen($dir."/".$bank_template, "r");
        $line =0;
        $counter=1;
        while(! feof($file)){
            if($counter >5){
                break;
            }
            $line =fgets($file);
            if(strpos($line,'$bank_name') !== false){
                
                $string_array = explode('"',$line);     
                $banks_list[pathinfo($bank_template, PATHINFO_FILENAME)]=$string_array[1];
                break;
            }
            $counter ++;
        }

       fclose($file);
    }
    if($banks_list){
        $options =array('selected_id'=>$selected_id,'spec_option'=>$all_option,'spec_id'=>-1,'select_submit'=>$submit_on_change);
        array_selector_row($label,$name, $selected_id, $banks_list,$options);
    }else{
        display_error("There is no bank template available !");
    }
    
}
function print_content(){
    if(get_post('_tabs_sel') == 'items'){
        $sample_link = '<a  href="samples/Items.csv">'._("Items CSV Format").'</a>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=items";

    }
     if(get_post('_tabs_sel') == 'fa_items'){
        $sample_link = '<a  href="samples/Items.csv">'._("Items CSV Format").'</a>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=fa_items";

    }
    elseif(get_post('_tabs_sel') == 'customers'){
        $sample_link = '<a  href="samples/Customers.csv">'._("Customers CSV Format").'</a>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=customers";

    }
    elseif(get_post('_tabs_sel') == 'suppliers'){
        $sample_link = '<a  href="samples/Suppliers.csv">'._("Suppliers CSV Format").'</a>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=suppliers";

    }
    elseif(get_post('_tabs_sel') == 'adjustment'){
        $sample_link = '<a  href="samples/adjustment_import.csv">'._("Item Adjustment CSV Format").'</a>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=adjustment";

    }
    elseif(get_post('_tabs_sel') == 'journal'){
        $sample_link = '<a  href="samples/journal_entries.csv">'._("Journal entry CSV Format").'</a>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=journal";

    }
    elseif(get_post('_tabs_sel') == 'bank_statement'){
        $sample_link = '<a  href="samples/default_bank_statement.csv">'._("Bank Statement CSV Format").'</a> <span class="overduefg"> Default date format is yyyy-mm-dd</span>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=bank_statement";
    }elseif(get_post('_tabs_sel') == 'chart_of_accounts'){
        if(!check_value('coa_ids'))
            $sample_link = '<a  href="samples/chart_of_accounts_ids.csv">'._("Chart of accounts CSV Format").'</a>';
        else
            $sample_link = '<a  href="samples/chart_of_accounts.csv">'._("Chart of accounts CSV Format").'</a>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=chart_of_accounts";
    }elseif(get_post('_tabs_sel') == 'bom'){
        $sample_link = '<a  href="samples/bom.csv">'._("BOM CSV Format").'</a>';
        $sys_info_link="/modules/Kvcodes_importexport/view/sys_info.php?type=bom";
    }


    br(2);
    div_start('input_tbl');
    start_table(TABLESTYLE2, "width='30%'"); // outer table


    if(get_post('_tabs_sel') !="chart_of_accounts")
        label_row("View system info",view_popup_link(_("View"),$sys_info_link));
    if(get_post('_tabs_sel') =='bank_statement'){
        banks_list_row('Select Bank Template','bank_name',null,"Select Template",true);
    }
    if(get_post('_tabs_sel') =="chart_of_accounts")
        check_row(_("COA with auto ID's"),"coa_ids",null, true);
    if(get_post('_tabs_sel') !="bank_statement" || get_post('bank_name') =='default_bank_statement')
        label_row("Download Sample file:", $sample_link);

    label_row("CSV Import File:", "<input type='file' id='file' name='file'>");
    end_table(1);
    div_end();

    hidden('max_rows',500);   



    if(isset($_SESSION['chart_of_accounts']) && !empty($_SESSION['chart_of_accounts'])){
        display_note(_("Marked rows system gl account is already assigned ."), 0, 0, "class='overduefg'");
        start_table(TABLESTYLE2,"width=80%");
        $th =array('Code','Parent Code','Name','Type / Group','Class Name','Class type', 'System Gl');
        table_header($th);
        foreach ($_SESSION['chart_of_accounts'] as  $key=> $myrow) {
            if(isset($_SESSION['dublicate_system_gls']) && !empty($_SESSION['dublicate_system_gls']) && array_key_exists($key,$_SESSION['dublicate_system_gls'])){
                start_row("class='overduebg'");
            }else{
                start_row();  
            }

            label_cell($myrow['code']);
            label_cell($myrow['parent_code']);
            label_cell($myrow['name']);
            label_cell($myrow['type']);
            label_cell($myrow['class_name']);
            label_cell($myrow['class_type']);
            system_gls_cells($key.'_system_gl',null,_("Select System Gl"));
            end_row();
        }
        end_table(2);
        submit_center_first('submit_coa', "Submit");
    }else{
        submit_center_first('Import', "Import CSV File");
        if(get_post('_tabs_sel') != 'adjustment' &&get_post('_tabs_sel') != 'bank_statement' &&get_post('_tabs_sel')!="chart_of_accounts"){
             submit_center_last('Export', "Export CSV File");
        }
        if(get_post('_tabs_sel')=="chart_of_accounts"){
            if(file_exists(dirname(__FILE__).'/backups/chart_of_accounts.sql')){
                submit('Export', "Export CSV File"); 
                submit_center_last('coarestore', "Restore Previous");
            }else{
                submit_center_last('Export', "Export CSV File"); 
            }
        }
    }
     br();
}


if(list_updated('coa_ids')){
    $Ajax->activate('tabs');
}

if(list_updated('bank_name')){
    $Ajax->activate('input_tbl');
}
start_form(true);





$tabs_ar = array(
        'items' => array(_('&Items'), (user_check_access('SA_ITEM') ? true : null)),
        'fa_items' => array(_('&FA Items'), (user_check_access('SA_ITEM') ? true : null)),
        'customers' => array(_('&Customers'), (user_check_access('SA_CUSTOMER') ? true : null)),
        'suppliers' => array(_('&Suppliers'), (user_check_access('SA_SUPPLIER') ? true : null)),
        'adjustment' => array(_('&Inventory Adjustment'), (user_check_access('SA_INVENTORYADJUSTMENT') ? true : null)),
        'bank_statement' => array(_('&Bank Statements'), (user_check_access('SA_BANKACCOUNT') ? true : null)),
        'journal' => array(_('&Journal Entries'),(user_check_access('SA_JOURNALENTRY') ? true : null)),
        'chart_of_accounts' => array(_('Chart of accounts'),(user_check_access('SA_GLACCOUNT') ? true : null)),
        'bom' => array(_('BOM'),(user_check_access('SA_BOM') ? true : null)),
    ); 

tabbed_content_start('tabs', $tabs_ar);
    
    switch (get_post('_tabs_sel')) {
        default:
        case 'items':
            print_content();
            break;
        case 'fa_items':
            print_content();
            break;    
        case 'customers':
            print_content();
            break;
        case 'suppliers':
            print_content();

            break;
        case 'adjustment':
            print_content();
            break;
        case 'bank_statement':
            print_content();
            break;

        case 'journal' :
            print_content();
            break;
        case 'chart_of_accounts':            
            print_content();
            break; 
        case 'bom':            
            print_content();
            break;
    };
tabbed_content_end();
end_form();


end_page();
?>