<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_SALESUPLOADPOSSALES';

$path_to_root = "../..";

include_once($path_to_root . "/includes/ui/items_cart.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
//include_once($path_to_root . "/includes/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
//include_once($path_to_root . "/payroll/includes/payroll_db.inc");
//include_once($path_to_root . "/admin/db/fiscalyears_db.inc");
include_once($path_to_root . "/sales/sales_upload/add_sales.inc");
include_once($path_to_root . "/sales/sales_upload/add_payments.inc");
include_once($path_to_root . "/sales/sales_upload/add_benefit.inc");
include_once($path_to_root . "/sales/sales_upload/add_credit_note.inc");
include_once($path_to_root . "/sales/sales_upload/allocate_payment.inc");
include_once($path_to_root . "/sales/sales_upload/add_refund.inc");
include_once($path_to_root . "/sales/sales_upload/allocate_refund.inc");

include_once($path_to_root . "/loyalty/includes/db/benefits_db.inc");
include_once($path_to_root . "/loyalty/includes/db/members_db.inc");
include_once($path_to_root . "/sales/includes/db/pos_invoices_db.inc");
include_once($path_to_root . "/sales/includes/sales_upload_common.inc");

$js = '';

if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}


if (!@$_GET['popup'])
	page(_($help_context = "Sales Upload"));

//----------------------------------------------------------------------------------------
simple_page_mode(true);


//--------------------------------------------------------------------------------------------------

//if ($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM')



if (get_post('cancel')) 
{
    $selected_id = -1;
    $_POST['selected_id'];
    clear_data();
    set_focus('work_time_code');
    $Ajax->activate('controls');
}
//--------------------------------------------------------------------------------------------------


function clear_data()
{
    unset($_POST['date']);
    unset($_POST['work_time_code']);
    unset($_POST['comment']);
}

//--------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------


if ($Mode == 'RESET')
{
	$selected_id = -1;
}

//if (list_updated('employee_code')) 
//	$Ajax->activate('Entitlements');
//--------------------------------------------------------------------------------------------------

if (!@$_GET['popup'])
	start_form();

//--------------------------------------------------------------------------------------------------
function move_file($filename){
    global $path_to_root;

    $dir_path_name = $path_to_root.'/lakecity_uploads/uploaded_files';
    
    if(!file_exists($dir_path_name)){
        mkdir($dir_path_name);
    }
    
    $current_file_path_name = $path_to_root.'/lakecity_uploads/'.$filename;    
    $new_file_path_name = $path_to_root.'/lakecity_uploads/uploaded_files/'.$filename;  
    
    $n = 0;
    while(file_exists($new_file_path_name)){
        $n++;
        $new_file_path_name = $path_to_root.'/lakecity_uploads/uploaded_files/'.$filename."_".$n; 
    }
     
    copy($current_file_path_name, $new_file_path_name);
    
    if(file_exists($new_file_path_name)){
        unlink($current_file_path_name);
    }
    
}


function upload($selected_id){
    
    $prefix = substr($selected_id, 0, 2);
    
    if($prefix == "F_"){
        $filename = substr($selected_id,2);
        upload_file($filename);
    }
    
    if($prefix == "R_"){
        $id = substr($selected_id,2);
        reupload_invoice($id);
    }
    
}

function get_customer_id($invoice){
    
    $customer_id = $invoice['customer_id'];
    
    if($customer_id > 0){
        return $customer_id;
    }
    
    $pos_customer_type = $invoice['pos_customer_type'];
    if($pos_customer_type == "Member"){
        $mci_row = get_members_customer_id($invoice['member_no']);
        if($mci_row == null){
            $customer_id = 1;
        }
        else{
            $customer_id = $mci_row['debtor_no'];
        }
    }
    else if($pos_customer_type == "Customer"){
        if($invoice['customer_id'] == 0 || $invoice['customer_id'] == ""){
            $customer_id = 1;
        }
    }
    else{
        $customer_id = 1;
    }    
    
    return $customer_id;
    
}




function upload_file($filename){
    global $path_to_root;

    br(2);
    
    $file_path_name = $path_to_root.'/lakecity_uploads/'.$filename;    
    $file_content = file_get_contents($file_path_name);

    $data = json_decode($file_content,true);
    if($data == null){
        display_error("Invalid file format"); 
        return;
    }

    foreach ($data as $invoices){
        foreach ($invoices as $invoice){
            upload_invoice($invoice, $filename);
        }
    }
    
    move_file($filename);
    
}


function add_default_values(&$invoice)
{
    $invoice['customer_id'] = get_customer_id($invoice);

    $customer_short_name = "";
    $csn_row = get_customer_short_name($invoice['customer_id']);

    if($csn_row == null){
        return array("passed" => false, "message" => _("Customer[".$invoice['customer_id']."] short_name is blank"));
    }

    $customer_short_name = $csn_row['debtor_ref'];
    $customer_branch_code = 0;
    $bId_row = get_customer_branch_code($customer_short_name);
    if($bId_row == null){
        return array("passed" => false, "message" => _("Customer[".$invoice['customer_id']."] branch_id is zero"));
    }

    $customer_branch_code = $bId_row["branch_code"];
    $invoice['branch_id'] = $customer_branch_code;
    
    if(strlen($invoice['deliver_to']) < 2){
        $invoice['deliver_to'] = "N/A";
    }
    if(strlen($invoice['delivery_address']) < 2){
        $invoice['delivery_address'] = "N/A";
    }
    
    return array("passed" => true, "message" => _(""));
}



function get_invoice_total(&$invoice)
{
    $invoice_total = 0;
    
    foreach($invoice['Items'] as $item) {
	if($item['line_status'] != "V"){
            if($item['line_status'] == "G"){
                $item['line_discount_total_value'] = $item['price'];
            }
            
            $line_total = $item['price'] * $item['qty'];
            
            if($item['price'] < 0){
                $item['price'] = -$item['price'];
            }
            
            if($item['price'] > 0){
                $item_discount_value = $item['line_discount_total_value'] / $item['qty'];
                $item_discount_percentage = $item_discount_value / $item['price'];
                $item['discount'] = $item_discount_percentage;
            }
            
            $line_total = $line_total * (1 - $item['discount']);
        
        }
        
        $invoice_total += $line_total;
    }
    
    $invoice[] = "invoice_total";
    $invoice["invoice_total"] = $invoice_total;
    
    return $invoice_total;
}
            
function upload_invoice($invoice, $filename = "")
{
    build_invoice_reference($invoice);
    
    $invoice_reference = ($invoice["reference"]);
    $json_invoice = json_encode($invoice); 

    $rec_id = add_to_sales_upload_log($invoice_reference, $json_invoice, $filename);

    if($rec_id == 0){
        add_to_sales_upload_log($invoice_reference, "Could not add the invoice into sales upload log", $filename);
        return;
    }
    
    $invoice[] = "trans_no";
    $invoice["trans_no"] = 0;

    $adv_msg = add_default_values($invoice);
    if($adv_msg["passed"] == false){
        update_sales_upload_log($rec_id,$invoice_reference, $filename,true,$adv_msg["message"]);
        return;
    }
    
    if(get_invoice_total($invoice) < 0){
            $cn_msg = credit_note_add($invoice);
            if($cn_msg["passed"] == true){
                update_sales_upload_log($rec_id,$invoice_reference, $filename,true,"Credit note:".$cn_msg["message"]);
            }
            else{
                update_sales_upload_log($rec_id,$invoice_reference, $filename,0,$cn_msg["message"]);
            }

            get_debtor_trans_no($invoice, ST_CUSTCREDIT);

            if($invoice["trans_no"] == 0){
                update_sales_upload_log($rec_id,$invoice_reference, $filename,true,"Credit note [".$invoice['reference']."] not available in the database");
                return;
            }

            foreach ($invoice['Payments'] as $pos_refund){  
                $ra_msg = refund_add($invoice,$pos_refund);
                if($ra_msg["passed"] == true){
                    update_sales_upload_log($rec_id,$invoice_reference, $filename,true,"Refund:".$ra_msg["message"]);
                }
                else{
                    update_sales_upload_log($rec_id,$invoice_reference, $filename,0,$ra_msg["message"]);
                }
            }
    }
    else{

            $sa_msg = sales_add($invoice);
            if($sa_msg["passed"] == true){
                update_sales_upload_log($rec_id,$invoice_reference, $filename,true,"Invoice:".$sa_msg["message"]);
            }
            else{
                update_sales_upload_log($rec_id,$invoice_reference, $filename,0,$sa_msg["message"]);
            }

            get_debtor_trans_no($invoice, ST_SALESINVOICE);

            if($invoice["trans_no"] == 0){
                update_sales_upload_log($rec_id,$invoice_reference, $filename,true,"Invoice[".$invoice['reference']."] not available in the database");
                return;
            }


            foreach ($invoice['Payments'] as $pos_payment){  
                $pa_msg = payment_add($invoice,$pos_payment);
                if($pa_msg["passed"] == true){
                    if($pos_payment['payment_method'] == "Customer Account"){
                        update_sales_upload_log($rec_id,$invoice_reference, $filename,true,"Pos Cust. Acc. Payment:".$pa_msg["message"]);
                    }
                    else{
                        update_sales_upload_log($rec_id,$invoice_reference, $filename,true,"Payment:".$pa_msg["message"]);
                    }
                }
                else{
                    update_sales_upload_log($rec_id,$invoice_reference, $filename,0,$pa_msg["message"]);
                }
            }

            foreach ($invoice['promotion_benefits'] as $pos_benefit){       
                $ba_msg = benefit_add($invoice,$pos_benefit);
                if($ba_msg["passed"] == true){
                    update_sales_upload_log($rec_id,$invoice_reference, $filename,true,"Benefit:".$ba_msg["message"]);
                }
                else{
                    update_sales_upload_log($rec_id,$invoice_reference, $filename,true,$ba_msg["message"]);
                }
            }
    }
    
    add_pos_invoice($invoice);
      
}


function reupload_invoice($id){    
    
    $myrow = get_unuploaded_invoice_details($id);

    $invoice = $myrow["invoice_details"];
    $invoice = str_replace("&quot;", '"', $invoice);
    $invoice = str_replace("\/", "/", $invoice);
    $invoice = json_decode($invoice,true);
    
    $filename =  $myrow["filename"];
    
    upload_invoice($invoice,$filename);
    
}


function display_file_list()
{
    global $path_to_root;
    
    $dir = $path_to_root.'/lakecity_uploads';
    $file_list = scandir($dir, 1);

    //br();
    display_heading("File List");
    br();

    start_table(TABLESTYLE, "width=30%");

    $th = array(_("File Name"), "");

    table_header($th);

    $k = $j = 0; //row colour counter

    foreach($file_list as $file_name){
        if((strlen($file_name)> 2) && (!is_dir($dir."/".$file_name))){
        
            alt_table_row_color($k);
            label_cell($file_name);

            //edit_button_cell("Edit"."F_".$file_name, _("Edit"));
            select_button_cell("Edit"."F_".$file_name, _("Select1"), _("Upload this file"));

            end_row();
        }

    } 

    end_table();

    div_end();
}

function display_unuploaded_invoices()
{
    $result = get_all_unuploaded_invoices();

    br(2);
    display_heading("Failed Records");
    br();

    start_table(TABLESTYLE, "width=90%");

    $th = array(_("Id"),_("Reference"),_("File Name"),_("Aded On"),_("Error Message"), "");

    table_header($th);

    $k = $j = 0; //row colour counter

    while ($myrow = db_fetch($result)){
        
        alt_table_row_color($k);
        label_cell($myrow["id"]);
        label_cell($myrow["invoice_reference"]);
        //label_cell($myrow["invoice_details"]);
        label_cell($myrow["filename"]);
        label_cell($myrow["added_on"]);
        label_cell($myrow["error_message"]);

        //edit_button_cell("Edit"."R_".$myrow["id"], _("Edit"));
        select_button_cell("Edit"."R_".$myrow["id"], _("Select1"), _("Upload this invoice"));

        end_row();

    } //end of while loop

    end_table();

    div_end();
}

echo "<br/>";
//-----------------------------------------------------------------------------------------------




//-----------------------------------------------------------------------------------------------

hidden('selected_id', $selected_id);

div_start('controls');

if(strlen($selected_id)>2)
{
    upload($selected_id);
}


//submit_add_or_update_center($selected_id == -1, '', 'both');
//submit_center('update_date', 'Update Date', true, false);
//if($selected_id > 0)
//{
//    submit_center_first('update_date', _("Update Date"), '','default');
//    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//}
display_file_list();
display_unuploaded_invoices();

div_end();
br();



br();

if (!@$_GET['popup'])
{
	end_form();
	end_page(@$_GET['popup'], false, false);
}
?>
