<?php



function can_delete_purchase_order_details($p_order_no)
{
    $line_count = get_purchase_orders_line_count($p_order_no);
        if(($line_count > 0)){
            $message = "This purchase order Id '$p_order_no' has received itmes. It can not be deleted.";
            display_error($message);
            return false;
        }    
        return true;
}

function can_process_local_purchase_order_header($order_no)
{
    global $Refs;
    
    if($order_no > 0){
        $scpoh = get_local_purchase_order_header ($order_no);
        if(!($scpoh['approval_status'] == AS_NEW || $scpoh['approval_status'] == AS_WITH_THE_APPROVER || $scpoh['approval_status'] == AS_AWAITING_APPROVAL || $scpoh['approval_status'] == AS_BACK_TO_ORIGINATOR)){
            $message = ("This Purchase Order status does not allow further updating.");
            return array("success" => false, "focus_to" => '', "message" => $message);
        }
        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document(ST_PURCHORDER, $scpoh['project_id'], $scpoh['next_approval_group_id'] , $current_user_id, $scpoh['created_by'], $order_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
        
    }
    
    if(!$Refs->is_valid($_POST['reference'])){
        $message = "Please enter a reference.";
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
//    if($pa_id == -1 && !is_new_reference(get_post('reference'), ST_PROJECT_PAYMENT_APPLICATION)){
    
    $ref_msg = reference_exists($_POST['reference'], ST_PURCHORDER, $order_no);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if(!($_POST['supplier_id'] > 0))
    {
        $message = "Please select a supplier.";
        $set_focus = 'supplier_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }   
    
    if (!isset($_POST['StkLocation']) || $_POST['StkLocation'] == "")
    {
        $message = "Please select a receiving location.";
        $set_focus = 'import_payment_term_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if (!($_POST['import_payment_term_id'] > 0))
    {
        $message = "Please select a payment term.";
        $set_focus = 'import_payment_term_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
    if (!($_POST['project_id'] > 0))
    {
        $message = "Please select a Project.";
        $set_focus = 'project_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
    
       

    if(!is_date($_POST['ord_date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'ord_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    $curr_rate = get_date_exchange_rate($_POST['curr_code'], $_POST['ord_date']);    
    if(!($curr_rate > 0))
    {
        $message = "This supplier currency rate is not defined.";
//        $set_focus = 'curr_rate';
        return array("success" => false, "focus_to" => '', "message" => $message);         
    }

    
//    if (!($_POST['po_total'] > 0))
//    {
//        $message = "po_total shhould greater than zero.";
//        $set_focus = 'project_id';
//        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
//    }
      
    return array("success" => true, "message" => "");    
}


function can_process_import_purchase_order_header($order_no)
{
    global $Refs;
    
//    if(!(strlen($_POST['sub_total_name']) > 0))  
//    {
//        $message = "Airfreight should be greater than zero.";
//        $set_focus = 'freight_value';
//        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
//    }
    
    if(!(check_num('freight_value',0)))  
    {
        $message = "Value entered for freignt is invalid.";
        $set_focus = 'freight_value';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!(check_num('insurance_value',0))) 
    {
        $message = "Value entered for insurance is invalid.";
        $set_focus = 'insurance_value';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    return array("success" => true, "message" => "");  
}

 
function can_process_purchase_order_line($order_no)
{    
    if(!($_POST['item_code']) > 0){
            $message = "Please select an item.";
            $set_focus = 'item_code';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!strlen($_POST['item_description']) > 0){
            $message = "Item description can not be empty.";
            $set_focus = 'item_description';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!strlen($_POST['tran_unit']) > 0){
            $message = "Please select an unit.";
            $set_focus = 'tran_unit';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
        
    if(!(check_num('order_unit_qty', 0.0001)))
    {
        $message = "Quantity should be greater than zero.";
        $set_focus = 'order_unit_qty';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
              
    if(!(is_date($_POST['delivery_date'])))
    {
        $message = "Delivery Date is not valid date.";
        $set_focus = 'delivery_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
              
    if(!(check_num('order_unit_price', 0.0001)))
    {
        $message = "Price should be greater than zero.";
        $set_focus = 'order_unit_price';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
              
    if(($_POST['order_unit_price_discount'] < 0))  
    {
        $message = "Discount should be positive number.";
        $set_focus = 'order_unit_price_discount';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }

//        if(isset($_POST['order_unit_price_discount']) && $_POST['order_unit_price_discount'] > 0){
//            $po_total = $_POST['order_unit_qty'] * ($_POST['order_unit_price'] * (1 - $_POST['order_unit_price_discount']/100));
//            $_POST['po_total'] = $po_total;
//        }else{
//            $po_total = $_POST['order_unit_qty'] * ($_POST['order_unit_price']);
//            $_POST['po_total'] = $po_total;
//        }
              
    return array("success" => true, "message" => "");    
}

   


function save_purchase_order_header(&$order_no)
{    
    $_POST['po_total'] = 0;
    
    $order_no = write_purchase_order_header(ST_IMPORT_PURCHORDER, $order_no, $_POST['reference'], 
                                            $_POST['project_id'], $_POST['supplier_id'],
                                            $_POST['ord_date'], $_POST['tax_included'],
                                            $_POST['tax_group_id'], "", $_POST['import_payment_term_id'],
                                            $_POST['supp_ref'], $_POST['StkLocation'], $_POST['delivery_address'],
                                            $_POST['po_total'],0,0,0, $_POST['row_state'],  $_POST['curr_code'], $_POST['curr_rate']);  
                                           //$_POST['total_scpo'], $_POST['taxes_total'], $_POST['generated_po'], $_POST['next_approval_group_id']
    
    if($order_no > 0){
        set_session_variable("ST_PURCH_ORDER_no", $order_no);
        return array("success" => true, 'trans_no' => $order_no, "message" => "Import purchase order header information have been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save Import purchase order header.");
    }
}


function save_import_purchase_order_header($order_no)
{     
    write_import_purchase_order_header($order_no, $_POST['sub_total_name'], $_POST['freight_name'],input_num('freight_value'), 
                                                    $_POST['insurance_name'], input_num('insurance_value'), $_POST['total_name'],
                                                    $_POST['payment_term_details']);  
    if($order_no > 0){
//        set_session_variable("ST_PURCH_ORDER_no", $order_no);
        return array("success" => true, 'trans_no' => $order_no, "message" => "Import purchase order header information have been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save Import purchase order header.");
    }
}


function save_purchase_order_detail($order_no, $selected_id)
{
    $convesion_factor = 1;
    $alternate_unit = $_POST['tran_unit'];

    get_convertion_factor2($_POST['item_code'], $alternate_unit, $convesion_factor);
    
    $ou_price = input_num('order_unit_price');
    $unit_price = ($ou_price / $convesion_factor);
    $quantity = input_num('order_unit_qty') * $convesion_factor;//if select 1 box but it has 10 items inside that bxox so have to * with convesion fac

    
    write_purchase_order_detail($order_no, $_POST['item_code'], $_POST['item_description'], $_POST['delivery_date'], 
                                $unit_price, $quantity, $convesion_factor,
                                $alternate_unit, input_num('order_unit_qty'), input_num('order_unit_price'), 
                                input_num('order_unit_price_discount'),
                                input_num('minimum_price'), input_num('minimum_price_discount'),
                                $_POST['min_price_supplier_id'], $_POST['project_site_id'], $selected_id);

    
    return array("success" => true, 'trans_no' => '', "message" => " ");
}



function save_import_po(&$order_no, $selected_id)
{    
    $h_msg = can_process_local_purchase_order_header($order_no);      
    if($h_msg["success"] !== true) 
    {          
        if(isset($h_msg["focus_to"])){
            set_focus($h_msg["focus_to"]);
        }
        return array("success" => false, "message" => $h_msg["message"]);
    }
        
    $h_msg = can_process_import_purchase_order_header($order_no);       
    if($h_msg["success"] !== true) 
    {          
        if(isset($h_msg["focus_to"])){
            set_focus($h_msg["focus_to"]);
        }
        return array("success" => false, "message" => $h_msg["message"]);
    }
        
    $line_msg = can_process_purchase_order_line($order_no);
        if($line_msg['success'] !== true){
            if(isset($line_msg["focus_to"])){
                set_focus($line_msg["focus_to"]);
            }
            return array("success" => false, "message" => $line_msg["message"]);
        }
    
    begin_transaction();
    $msg = save_purchase_order_header($order_no);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $order_no, "message" => $msg["message"]);
    }
    
    $msg = save_import_purchase_order_header($order_no);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $order_no, "message" => $msg["message"]);
    }

    $msg = save_purchase_order_detail($order_no, $selected_id);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $order_no, "message" => $msg["message"]);
    }
       
    $rate_include_taxes = 0;
    $po_tax_total = input_num('freight_value') + input_num('insurance_value');
    update_purchase_order_header_totals($order_no, $po_tax_total, $rate_include_taxes);
    
    commit_transaction();
    if($order_no > 0){
        return array("success" => true, 'trans_no' => $order_no, "message" => $msg["message"]);
    }
    else{
        return array("success" => true, 'trans_no' => $order_no, "message" => "Subcontractor purchase orders $order_no has been created.");
    }

}

function display_import_purchase_order_header($order_no)
{
    global $Ajax, $Refs, $approval_statuses;
    
    $order_no > 0 ? display_heading("Import Purchase Order ".$order_no):"";
    
    br(1);
    
    $tran_type = ST_PURCHORDER;
    
    if($order_no > 0){
        $editable = true;
        $local_po_header = get_local_purchase_order_header($order_no);
        $import_po_header = get_import_purchase_order_header($order_no);
        
        if(!isset($_POST['project_id'])){
            $project_id = $local_po_header['project_id'];
        }
        $project_id = $local_po_header['project_id'];
        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($project_id, $user_id);
        if($cap['success'] !== true) 
        {
            display_error($cap["message"]);
            set_focus('project_id');
            display_footer_exit();
            exit;
        }  
        
    
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $local_po_header['reference'];
        }

        if(!isset($_POST['ord_date'])){
            $_POST['ord_date'] = sql2date($local_po_header['ord_date']);
        }
        
        if(!isset($_POST['supplier_id'])){
            $_POST['supplier_id'] = $local_po_header['supplier_id'];
        }

        if(!isset($_POST['tax_included'])){
            $_POST['tax_included'] = $local_po_header['tax_included'];
        }
        
        if(!isset($_POST['tax_group_id'])){
            $_POST['tax_group_id'] = $local_po_header['tax_group_id'];
        }
        
        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $local_po_header['project_description'];
        }
        
        if(!isset($_POST['approval_status'])){
            $_POST['approval_status'] = $local_po_header['approval_status'];
        }
        
        if(!isset($_POST['header_comment'])){
            $_POST['header_comment'] = $local_po_header['comments'];
        }
        
        if(!(isset($_POST['import_payment_term_id']) && $_POST['import_payment_term_id'] > 0)){
            $_POST['import_payment_term_id'] = $local_po_header['terms_indicator'];
        }
        
        if(!(isset($_POST['payment_term_details']) && strlen($_POST['payment_term_details']) > 0)){
            $_POST['payment_term_details'] = $import_po_header['payment_term_details'];
        }
        
        if(!isset($_POST['supp_ref'])){
            $_POST['supp_ref'] = $local_po_header['requisition_no'];
        }
        
        if(!isset($_POST['delivery_address'])){
            $_POST['delivery_address'] = $local_po_header['delivery_address'];
        }
        
        if(!isset($_POST['StkLocation'])){
            $_POST['StkLocation'] = $local_po_header['into_stock_location'];
        }
        
        if(!isset($_POST['project_id'])){
            $_POST['project_id'] = $local_po_header['project_id'];
        }
        
        if(!isset($_POST['curr_code'])){
            $_POST['curr_code'] = $local_po_header['curr_code'];
        }
        
        if(!isset($_POST['curr_rate'])){
            $_POST['curr_rate'] = $local_po_header['curr_rate'];
        }
        
        $_POST['order_no'] = $local_po_header['order_no'];
            
//        $_POST['total_scpo'] = 0;
        $_POST['$taxes_total'] = 0;
        $_POST['generated_po'] = 0;
        $_POST['next_approval_group_id'] = 0;
        $_POST['tax_included '] = 0;
        //$_POST['curr_rate'] = 1;
        
        hidden('row_state', $local_po_header['row_state']);
        
       
    }
    else{
        $Refs = new references();
        $_POST['reference'] = $Refs->get_next(ST_PURCHORDER);
        $_POST['ord_date'] = Today();
        $_POST['approval_status'] = 0;
        $_POST['tax_included'] = 0;
        $_POST['supp_ref'] = '';
//        $_POST['StkLocation'] = "";
        $_POST['delivery_address'] = "";
        $_POST['header_comment'] = "";
        $order_no = 0;
        $editable = true;
        $_POST['total_scpo'] = 0;
        $_POST['$taxes_total'] = 0;
        $_POST['generated_po'] = 0;
        $_POST['next_approval_group_id'] = 0;
        $_POST['order_no'] = 0;
//        $_POST['project_id'] = 0;
      
        if(isset($_POST['new_order'])){
            $_POST['curr_code'] = '';
        }
            
        //$_POST['curr_rate'] = 1;
        $_POST['tax_included '] = 0;
        hidden('row_state', 0);
        
        $_POST['terms_indicator']  = 0;
        
        
    }
       
    
    
    start_outer_table(TABLESTYLE2, "width=88%"); // outer table
    start_table(TABLESTYLE2);  
    
    
        table_section(1);//----------------------------------------------------------
        
        if ($editable)
        {
            ref_row(_("Reference:"), 'reference');
        }
        else
        {
            hidden('reference', $_POST['reference']);
            label_row(_("Reference:"), $_POST['reference']);
        }
        
        
        
        other_currency_suppliers_list_row("Supplier:", 'supplier_id', null, 'Select a Supplier', true);
        
        $sup_details = get_supplier($_POST['supplier_id']);
        if(!(isset($_POST['tax_group_id']) && $_POST['tax_group_id'] > 0)){
            $_POST['tax_group_id'] = $sup_details['tax_group_id'];   
        }
        //tax_groups_list_row("Tax Group:", 'tax_group_id', null, false, true);
        hidden('tax_group_id', 0);
        
        date_row("Date:", 'ord_date');
        
        supplier_credit_row('supplier_id', null);
        
//        $supp_currency = get_supplier($_POST['supplier_id']);
        label_row(_("Supplier Currency:"), $sup_details['curr_code']);
        hidden('curr_code', $sup_details['curr_code']);
        
        if(isset($sup_details['curr_code']) && strlen($sup_details['curr_code']) > 0){
            $curr_rate = get_date_exchange_rate($sup_details['curr_code'], $_POST['ord_date']);
            label_row(_("Currency Rate:"), number_format($curr_rate,2));
            hidden('curr_rate', $curr_rate);
        }
        else{
            hidden('curr_rate', 0);
        }
        
//     $curr_rate = exchange_rate_display(get_company_currency(), null, $_POST['ord_date']);

   
        
        

//        locations_list_row(_("Receive Into:"), 'StkLocation', null, false, true);

        
              
        table_section(2);//------------------------------------------
        
        text_row(_("Supplier's Reference:"), 'supp_ref', null, 16, 15);
        
        if ($editable)
        {
            locations_list_row(_("Receive Into:"), 'StkLocation', null, 'Slect a location', false);
        }
        else
        {
            hidden('StkLocation', $_POST['StkLocation']);
            locations_list_row(_("Receive Into:"), $_POST['StkLocation'], null, false, true);
        }
        
        
        if ($tran_type == ST_SUPPINVOICE){
		date_row(_("Due Date:"), 'due_date', '', false, 0, 0, 0, null, true);
        }


        
//        if(!(isset($_POST['terms_indicator']) && $_POST['terms_indicator'] > 0)){
//            if($order_no > 0){
//                $_POST['terms_indicator'] = $_POST['terms_indicator'];
//            }
//        }

//        payment_terms_list_row("Payment Terms:", 'terms_indicator', null, false, true);
        import_payment_terms_list_row("Payment Terms:", 'import_payment_term_id', null, "Select an import payment term");

//        get_payment_terms_to_order($order, $_POST['supplier_id'], $_POST['import_payment_term_id']);
    
  	text_row(_("Payment Term Details:"), 'payment_term_details', null, 40, 200);
        
        
        
        
        if ($editable)
        {
            project_list_row(_("Project:"), 'project_id', null, _('Select a Project'), true);
            
            if(isset($_POST['job_reference']) && !list_updated('project_id')){
                label_row(_("Job Reference:"), $_POST['job_reference']);
            }

            if(list_updated('project_id') && $_POST['project_id'] != -1)
            {
                $job_ref = get_job_ref($_POST['project_id']);
                $_POST['job_reference'] = $job_ref['description'];
                label_row(_("Job Reference:"), $_POST['job_reference']);
            }    
            
            //tasks_list_row(_("Budget:"), 'task_id', $_POST['project_id'], $task_id, _('Select a budget'), true);
            
//            if ($_POST['project_id'] != -1)
//            {
//                $result = get_approval_path($_POST['project_id'], "PO");
//                label_row(_("Approval Path:"), $result['approval_path_name']);
//            }
//            else {
//                label_row(_("Approval Path:"),"");
//            }
            
            
            //yesno_list_row("Use Future Budgets", 'use_future_budgets', $order->use_future_budgets, "Yes", "No");
        }
        else
        {
            if(isset($_POST['project_id'])){
                $_POST["project_id"]  = $_POST["project_id"];
            }

            $_POST["approval_path_id"] = 0;
            $_POST["approval_path_description"] = '';
            
            

//            locations_list_row(_("Issuing Location:"), 'issuing_location', $order->issuing_location);
            if(!$order->generated_po){
                project_list_row(_("Job:"), 'project_id', $_POST['project_id'], FALSE,TRUE);                
            }
            else{
                hidden('project_id', $_POST['project_id']);
            }
            
            if(isset($_POST["job_reference"]) && !list_updated('project_id')){
                label_row(_("Job Reference:"), $_POST["job_reference"]);
            }

            if(list_updated('project_id') && $_POST['project_id'] != -1)
            {
                $job_ref = get_job_ref($_POST['project_id']);
                $_POST["job_reference"] = $job_ref['description'];
                label_row(_("Job Reference:"), $_POST["job_reference"]);
            } 
            //tasks_list_row(_("Budget:"), 'task_id', $order->project_id, $order->task_id,false, TRUE);
            
            if(isset($_POST['project_id'])){
                $_POST['project_id']  = $_POST["project_id"];
                $approval_path = get_approval_path($_POST['project_id'], "PO");
                if($approval_path){
                    $_POST['approval_path_id'] = $approval_path['approval_path_id'];
                    $_POST['approval_path_description'] = $approval_path['approval_path_name'];
                }
            }
            
            label_row("Approval Path:", $_POST['approval_path_description']);
            
            //yesno_list_row("Use Future Budgets", 'use_future_budgets', $order->use_future_budgets, "Yes", "No");
            
            $s = get_project_trans_view_str(98, $_POST['order_no']."&source_type_id=".ST_PURCHORDER, "Approval Status");
            //label_cell($s);
            label_row($s,$approval_statuses[$_POST['approval_status']]);
        }
        
        
        
        table_section(3);//------------------------------------------
        
        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $order_no."&source_type_id=".ST_PURCHORDER, "Approval Status");
//            display_view_cell($s,$approval_statuses[$po->approval_status], "class='tableheader2'");
            label_row($s,$approval_statuses[$_POST['approval_status']]);
            
        if (!isset($_POST['StkLocation']) || $_POST['StkLocation'] == "" ||
            isset($_POST['_StkLocation_update']) || !isset($_POST['delivery_address']) ||
            $_POST['delivery_address'] == "")
        {
            /*If this is the first time the form loaded set up defaults */

            //$_POST['StkLocation'] = $_SESSION['UserStockLocation'];
            $sql = "SELECT delivery_address, phone FROM ".TB_PREF."locations WHERE loc_code=".db_escape($_POST['StkLocation']);
            $result = db_query($sql,"could not get location info");

            if (db_num_rows($result) == 1)
            {
                    $loc_row = db_fetch($result);
                    $_POST['delivery_address'] = $loc_row["delivery_address"];
//                            $Ajax->activate($_POST['delivery_address']);
//                    $_POST['StkLocation'] = $_POST['StkLocation'];
//                    $_POST['delivery_address'] = $_POST['delivery_address'];

            }
//            else
//            { /*The default location of the user is crook */
//                    display_error(_("The default stock location set up for this user is not a currently defined stock location. Your system administrator needs to amend your user record."));
//            }
        }

	textarea_row(_("Deliver to:"), 'delivery_address', $_POST['delivery_address'], 30, 4);
       
        if($order_no>0){
            $link = get_imports_trans_view_str(ST_IMPORT_PO_COST_DETAIL_EDIT, $order_no,"Edit landing cost details");
            label_row('Landed Costs:',$link);
        }
        
        hidden('tax_included', '');
//        hidden('curr_code', $_POST['curr_code']);
        hidden('curr_rate', '');
         
     
//    end_table(1);

    end_outer_table(1); // outer table
    hidden('SCPO_No', $order_no);
 
}

function display_import_purchase_order_summary($order_no)
{
    $import_po_header = get_import_purchase_order_header($order_no);

    if($import_po_header['order_no'] > 0) { 
        if(!isset($_POST['sub_total_name'])){
            $_POST['sub_total_name'] = $import_po_header['sub_total_name'];
        }
        if(!isset($_POST['freight_name'])){
            $_POST['freight_name'] = $import_po_header['freight_name'];
        }
        if(!isset($_POST['freight_value'])){
            $_POST['freight_value'] = $import_po_header['freight_value'];
        }
        if(!isset($_POST['insurance_name'])){
            $_POST['insurance_name'] = $import_po_header['insurance_name'];
        }
        if(!isset($_POST['insurance_value'])){
            $_POST['insurance_value'] = $import_po_header['insurance_value'];
        }
        if(!isset($_POST['total_name'])){
            $_POST['total_name'] = $import_po_header['total_name'];
        }
        if(isset($_POST['line_total'] )){
            $total = input_num('line_total') + input_num('freight_value') + input_num('insurance_value');
        }
    }else{   
        
        $_POST['sub_total_name'] = '';
        $_POST['freight_name'] = '';
        $_POST['freight_value'] = 0;
        $_POST['insurance_name'] = '';
        $_POST['insurance_value'] = 0;
        $_POST['total_name'] = '';
        if(isset($_POST['line_total'] )){
            $total = input_num('line_total') + input_num('freight_value') + input_num('insurance_value');
        }
    }
        
}

function get_payment_terms_to_order(&$order, $supplier_id, $terms_indicator = 0)
{
    if($terms_indicator > 0){
        $pt = get_import_payment_term($terms_indicator);
        return array( 
            'terms_indicator' => $terms_indicator,
            'description' => $pt['description'],
            'days_before_due' => 0, 
            'day_in_following_month' => 0 );
    }
    else{
//        $myrow = get_supplier_payment_terms_details($supplier_id);
        $myrow = get_import_payment_term($terms_indicator);
        return array( 
            'terms_indicator' => $myrow['id'],
            'description' => $myrow['description'],
            'days_before_due' => 0, 
            'day_in_following_month' => 0 );
    }
}



function display_purchase_order_details($selected_id, $order_no)
{      
    global $Ajax;   
    
    br(1);
    
    display_heading(_("Order Items"));
     
    div_start('po_table');
    $result = get_purchase_order_details($order_no);     
         
    start_table(TABLESTYLE, "width=98%");
    $th = array(_('Id'
            . ''), _('Item Code'), _("Item Description"), _("Quantity"), _('Received'), 
                _('Unit'), _('Delivery Date'), _('Site'), _("Price"), _('Discount'), _("Line Total"), _(""), _(""));              
  
    div_start('sc_purchase_orders');
        $Ajax->activate('sc_purchase_orders');
    div_end();
    
    table_header($th);
    $k = 0; //row colour counter
      
    $total_po = 0;
    $line_total = 0;
    while ($myrow = db_fetch($result))
    {
        $line_no = $myrow["po_detail_item"];
        
        if($selected_id != $myrow["po_detail_item"]){
            alt_table_row_color($k);

            label_cell($myrow['po_detail_item'], 'align=center');
//            label_cell($myrow['order_no'], 'align=center');
            label_cell($myrow['item_code'], 'align=center');
            
            $item_description = $myrow['editable_description'] == 1 ? 
                                    (strlen($myrow['description']) > 0 ? $myrow['description'] : $myrow['item_description']) : 
                                    $myrow['item_description'];
            
            label_cell($item_description);
            
            qty_cell($myrow['order_unit_qty'], false, get_qty_dec($myrow['item_code']));
                    
//            qty_cell($myrow['quantity_received'], false, get_qty_dec($myrow['item_code']));
            
            qty_cell($myrow['quantity_received'], false, get_qty_dec($myrow['item_code']));
    		if($myrow['order_unit'] == ""){
                    label_cell($myrow['units'], 'align=center');
                }
                else{
                    label_cell($myrow['order_unit'], 'align=center');
                }
//			if ($myrow['trans_type'] == ST_PURCHORDER){
        	    label_cell(sql2date($myrow['delivery_date']), 'align=center');
//            }
            if($myrow['project_site_name'] != null){
                label_cell($myrow['project_site_name'], 'align=center');
            }else{
                label_cell('', 'align=center');
            }
            
            
            amount_decimal_cell($myrow['order_unit_price']);
            amount_decimal_cell($myrow['order_unit_price_discount']);
            
            $discounted_minimum_price = $myrow['minimum_price'] * (1-$myrow['minimum_price_discount']/100);
//            amount_cell($discounted_minimum_price);
            amount_cell($myrow['line_total']);
            
                $line_total += $myrow['line_total'];
                hidden('line_total', $line_total);
			
            edit_button_cell("Edit$line_no", _("Edit"), _('Edit document line'));
                        
            delete_button_cell("Delete$line_no", _("Delete"), _('Remove line from document'));
			
            end_row();
	}
        else{
            if(!isset($_POST['Delete'.$line_no])){
                $total_po += display_purchase_orders_edit_controls($selected_id, $order_no);
            }
        }

    }
 
    
    if(!($selected_id > 0)){
       display_purchase_orders_edit_controls($selected_id, $Mode);
    }
   
    end_row();
    
    echo "<td colspan=11>";
    start_table(null,"align=right");
    display_import_purchase_order_summary($order_no);
        
        start_row();
            if(!(isset($_POST['sub_total_name']) && strlen($_POST['sub_total_name']) > 0)){
                $_POST['sub_total_name'] = "Sub total";
            }
            text_cells('Sub Total Display Name:', 'sub_total_name', null, 60,"", false, "colspan=3 align=right", "", "align=right");
//            textarea_cells('Sub Total Display Name:', 'sub_total_name', null, 100, 1, null, "", "colspan=3");
//            label_cell("Sub Total:", "align=right style='font-weight:bold; color:black;'");
            label_cell(number_format($line_total, 2), "align=right style='font-weight:bold; color:black;'");
        end_row();

        start_row();
            if(!(isset($_POST['freight_name']) && strlen($_POST['freight_name']) > 0)){
                $_POST['freight_name'] = "Freight";
            }
            text_cells('Freight Display Name:', 'freight_name', null, 60,"", false, "colspan=3 align=right", "", "align=right");
//            label_cell("Freight:", "align=right style='font-weight:bold; color:black;'");
            amount_cells('', 'freight_value');
        end_row();

        start_row();
            if(!(isset($_POST['insurance_name']) && strlen($_POST['insurance_name']) > 0)){
                $_POST['insurance_name'] = "Insurance";
            }
            text_cells('Insurance Display Name:', 'insurance_name', null, 60,"", false, "colspan=3 align=right", "", "align=right");
//            label_cell("Insurance:", "align=right style='font-weight:bold; color:black;'");
            amount_cells('', 'insurance_value');
        end_row();

        start_row();
            if(!(isset($_POST['total_name']) && strlen($_POST['total_name']) > 0)){
                $_POST['total_name'] = "Total";
            }
            text_cells('Total Display Name:', 'total_name', null, 60,"", false, "colspan=3 align=right", "", "align=right");
//            label_cell("Total:", "align=right style='font-weight:bold; color:black;'");
            
                if(isset($_POST['freight_value']) && $_POST['freight_value'] > 0){
                    $_POST['freight_value'] = $_POST['freight_value'];
                }else{
                    $_POST['freight_value'] = 0;
                }
                
                if(isset($_POST['insurance_value']) && $_POST['insurance_value'] > 0){
                    $_POST['insurance_value'] = $_POST['insurance_value'];
                }else{
                    $_POST['insurance_value'] = 0;
                }
                
                $total = $line_total + input_num('freight_value') + input_num('insurance_value');

//                hidden('po_total', $total);
            label_cell(number_format($total, 2), "align=right style='font-weight:bold; color:black;'");
        end_row();
     
        end_table();
    echo "</td>";
    end_table();
    
    div_end();
  
}


function display_purchase_orders_edit_controls($selected_id, &$Mode)
{
    $line_total = 0;
    
    echo "<td colspan=11>";
    start_outer_table();
    
    table_section(1);//---------------------------------------------------------
  
    if($selected_id > 0){
        $po_detail = get_po_line_details($selected_id);
    }
    
    if($selected_id > 0 && (isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] != $selected_id)){
 
        $_POST['item_code'] = $po_detail['item_code'];
        $_POST['item_description'] = $po_detail['editable'] == 1 ? 
                                    (strlen($po_detail['description']) > 0 ? $po_detail['description'] : $po_detail['item_master_description']) : 
                                    $po_detail['item_master_description'];
        $dec = get_qty_dec($_POST['item_code']);
        $_POST['quantity_ordered'] = qty_format($po_detail['quantity_ordered'], $_POST['item_code'], $dec);
        $_POST['order_unit_qty'] = qty_format($po_detail['order_unit_qty'], $po_detail['item_code'], $dec);
        $_POST['price'] = price_decimal_format($po_detail['order_unit_price'], $dec2);
        $_POST['order_unit_price'] = price_decimal_format($po_detail['order_unit_price'], $dec2);
        $_POST['delivery_date'] = sql2date($po_detail['delivery_date']);
        $_POST['order_unit'] = $po_detail['order_unit']; 
        $_POST['project_site_id'] = $po_detail['project_site_id'];
        $_POST['order_unit_price_discount'] = price_decimal_format($po_detail['order_unit_price_discount'], $dec2);
        $_POST['minimum_price'] = price_decimal_format($po_detail['minimum_price'], $dec2);
        $_POST['minimum_price_discount'] = price_decimal_format($po_detail['minimum_price_discount'], $dec2);
        
        hidden('item_code', $_POST['item_code']);
        if($po_detail['editable'] == 1){
            label_row("Itemcode:",$_POST['item_code']);
            text_row("Description: ", "item_description", null, 30, 500);            
        }
        else{
            label_row("Itemcode:",$_POST['item_code']);
            label_row("Description :", $_POST['item_description']);
            hidden('item_description', $_POST['item_description']);
        }
    }
    else{
        $_POST['delivery_date'] = Today();
            
        if(!isset($_POST[''])){
            $_POST[''] = 1.00;
        }
        
        if(isset($_POST['tran_unit'])){
            $tran_unit = $_POST['tran_unit'];
        }
        
        if(list_updated('supplier_id') || list_updated('item_code') || list_updated('tran_unit') || list_updated('project_id')){
            
            $sup_price = get_supplier_price($_POST['item_code'], $_POST['supplier_id'], $_POST['project_id'], $_POST['tran_unit'], $_POST['delivery_date']);    

            if(isset($sup_price['price'])){
                $_POST['order_unit_price'] = $sup_price['price'];
                $_POST['order_unit_price_discount'] = $sup_price['discount'];
            }
            else{
                $_POST['order_unit_price'] = 0.00;
                $_POST['order_unit_price_discount'] = 0.00;
            }
        }
        
        $order_unit_price = 0;
        $order_unit_price_discount =0;
        
        if(!(isset($_POST['item_code']))){
            $_POST['item_code'] = "";
        }
        if(!(isset($_POST['tran_unit']))){
            $_POST['tran_unit'] = "";
        }
        
        if(!isset($_POST['order_unit_price'])){
            $sup_price = get_supplier_price($_POST['item_code'], $_POST['supplier_id'], $_POST['project_id'], $_POST['tran_unit'], $_POST['delivery_date']);    
            $order_unit_price = $sup_price['price'];
            $order_unit_price_discount = $sup_price['discount'];
        }
        else{
            $order_unit_price = $_POST['order_unit_price'];
        }
        $_POST['order_unit_price'] = $order_unit_price;
        
        
        if(isset($_POST['order_unit_price_discount'])){
            $order_unit_price_discount = $_POST['order_unit_price_discount'];
        }
        $_POST['order_unit_price_discount'] = $order_unit_price_discount;
        
        $line_total = round(input_num('') * input_num('order_unit_price'),  user_price_dec());

        $order_unit_min_price = 0;
        $order_unit_min_price_discount = 0;
        $min_price_sup_id = 0;
        
        if(strlen($_POST['item_code']) > 0 && strlen($_POST['tran_unit']) > 0){
            $min_price = get_purchase_minimum_price($_POST['item_code'], $_POST['project_id'], $_POST['tran_unit'], $_POST['delivery_date']);
        }

        if(isset($min_price['price'])){
            $order_unit_min_price = $min_price['price'];
            $order_unit_min_price_discount = $min_price['discount'];
            $min_price_sup_id = $min_price['supplier_id'];
        }

        $_POST['minimum_price_discount'] = $order_unit_min_price_discount;
        hidden('minimum_price', $order_unit_min_price);
        hidden('minimum_price_discount' );
        hidden('min_price_supplier_id', $min_price_sup_id);
        
        $discounted_min_price = number_format2($order_unit_min_price*(1-$order_unit_min_price_discount/100),2);
        
        
        if($selected_id > 0){
            hidden('item_code', $_POST['item_code']);
            if($po_detail['editable'] == 1){
                label_row("Itemcode:",$_POST['item_code']);
                text_row("Description: ", "item_description", null, 30, 500);            
            }
            else{
                label_row("Itemcode:",$_POST['item_code']);
                label_row("Description :", $_POST['item_description']);
                hidden('item_description', $_POST['item_description']);
            }
        }
        else{
            stock_items_list_row('Select Item:', 'item_code', null, false, true, false, true);
            $stock_item = get_stock_item_edit_info($_POST['item_code']);
            hidden('item_description', $stock_item['description']);
        }
            
    }
    
    
    
        
    units_list_row('Unit:', 'tran_unit', $_POST['item_code'], null, false, true);
    
    qty_cells('Quantity:', 'order_unit_qty', null, null, null, 2);


    hidden('selected_id', $selected_id );
    hidden('previous_selected_id', $selected_id );
 
    
    table_section(2);//---------------------------------------------------------
    
    
    
     
    $tran_unit = $_POST['tran_unit'];

    date_row('Delivery Date:', 'delivery_date', '', null, 0, 0, 0);

    project_sites_list_row('Project Site:', 'project_site_id', $_POST['project_id'], null, "Select a job");
        

    table_section(3);//-------------------------=-------------------------------   
    
    
    if(!isset($_POST['delivery_date'])){
            $_POST['delivery_date'] = $_POST['OrderDate'];
        }
        
        if(list_updated('supplier_id') || list_updated('item_code') || list_updated('tran_unit') || list_updated('project_id')){
            $sup_price = get_supplier_price(get_post('item_code'), get_post('supplier_id'), $_POST['project_id'], $_POST['tran_unit'], $_POST['delivery_date']);    

            if(isset($sup_price['price'])){
                $_POST['order_unit_price'] = $sup_price['price'];
                $_POST['order_unit_price_discount'] = $sup_price['discount'];
            }
            else{
                $_POST['order_unit_price'] = 0.00;
                $_POST['order_unit_price_discount'] = 0.00;
            }
        }

        $order_unit_price = 0;
        $order_unit_price_discount =0;

        if(!isset($_POST['order_unit_price'])){
            $sup_price = get_supplier_price(get_post('item_code'), get_post('supplier_id'), $_POST['project_id'], $_POST['tran_unit'], $_POST['delivery_date']);    
            $order_unit_price = $sup_price['price'];
            $order_unit_price_discount = $sup_price['discount'];
        }
        else{
            $order_unit_price = $_POST['order_unit_price'];
        }
        $_POST['order_unit_price'] = $order_unit_price;
        
        
        if(isset($_POST['order_unit_price_discount'])){
            $order_unit_price_discount = $_POST['order_unit_price_discount'];
        }
        $_POST['order_unit_price_discount'] = $order_unit_price_discount;
        
        amount_row('Price Before Tax:', 'order_unit_price', null, null, null, 2);
        amount_row('Discount:', 'order_unit_price_discount', null, null, null, 2);
        //hidden('price', $_POST['price']);
        

        //$line_total = $_POST['qty'] * $_POST['price'] * (1 - $_POST['Disc'] / 100);
        $line_total = round(input_num('') * input_num('order_unit_price'),  user_price_dec());

        $order_unit_min_price = 0;
        $order_unit_min_price_discount = 0;
        $min_price_sup_id = 0;
            
        //$base_unit_min_price = get_purchase_minimum_price(get_post('item_code'), get_post('tran_unit'));
        if(strlen(get_post('item_code')) > 0 && strlen(get_post('tran_unit')) > 0){
            $min_price = get_purchase_minimum_price(get_post('item_code'), $_POST['project_id'], $_POST['tran_unit'], sql2date($_POST['delivery_date']));
        }

        if(isset($min_price['price'])){
            $order_unit_min_price = $min_price['price'];
            $order_unit_min_price_discount = $min_price['discount'];
            $min_price_sup_id = $min_price['supplier_id'];
        }

        $_POST['minimum_price_discount'] = $order_unit_min_price_discount;
        hidden('minimum_price', $order_unit_min_price);
        hidden('minimum_price_discount' );
        hidden('min_price_supplier_id', $min_price_sup_id);


//    table_section(4);//---------------------------------------------------------
    
    
    $discounted_min_price = number_format2($order_unit_min_price*(1-$order_unit_min_price_discount/100),2);
//    amount_row('Discounted Min Price', 'discounted_min_price', false, $discounted_min_price);
    hidden('discounted_min_price', 0);
//    amount_row('Line Total', 'line_total', false, $line_total);

    
    end_outer_table();
    echo "</td>";

    if ($selected_id > 0){
        button_cell('UpdateItem', _("Update"), _('Confirm changes'), ICON_UPDATE);
        button_cell('CancelItemChanges', _("Cancel"), _('Cancel changes'), ICON_CANCEL);
        hidden('LineNo', $selected_id);
        set_focus('qty');
    }else{
        submit_cells('AddItem', _("Add"), "colspan=2 align=center", _('Add new item to document'), true);
    }

        return $line_total;
//    end_row();
    
//    end_table();
    
//    end_table(1);
//    div_end();

}

function can_release_purchase_order($order_no)
{
    $line_count = get_purchase_orders_line_counts($order_no);
    if (!($line_count > 0))
    {
        display_error("There are no details entered. Can not release this document.");
        return false;
    }
    
    $ubh = get_purchase_order_header($order_no);
    if(!($ubh['approval_status'] == AS_NEW || $ubh['approval_status'] == AS_WITH_THE_APPROVER || $ubh['approval_status'] == AS_AWAITING_APPROVAL || $ubh['approval_status'] == AS_BACK_TO_ORIGINATOR)){
        display_error("This Import Purchase Order status does not allow further updating.");
        return false;
    }
    
    return true;
}




function can_process_import_po_taxes($tax_group_id)
{
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
     
    foreach ($tax_types_array as $tax_type){
       
//        if($tax_type['tax_type_id'] == 1 || $tax_type['tax_type_id'] == 2){
        $postname = 'manual_tax_value_'.$tax_type['tax_type_id'];
        if(isset($_POST[$postname])){
           if(!(check_num($postname, 0.00000001))){
                $message = "Entered tax rate should be greater than zero.";
                $set_focus = 'manual_tax_value_'.$tax_type['tax_type_id'];
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        }
    }
    
    return array("success" => true, "focus_to" => '', "message" => '');
}


function display_selected_tax_types($order_no, $tax_group_id)
{
    $taxes_total = 0;
    
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
    foreach ($tax_types_array as $tax_type) {
        if($tax_type['rate'] > 0){
            $tax_amount = get_sc_purchase_orders_tax_type_amount($order_no, $tax_type['tax_type_id']);
            $_POST['manual_tax_value_'.$tax_type['tax_type_id']] = $tax_amount;
            amount_row($tax_type['tax_type_name'], 'manual_tax_value_'.$tax_type['tax_type_id']);   
        }
        else{
            $tax_amount = 0;
        }
        $taxes_total += $tax_amount;
    }
    
    return $taxes_total;
}


function display_tax_edit_controls($order_no)
{
    start_table(TABLESTYLE, "width=20%");
    $th = array(_('Tax Type'),_('Amount'));              

    table_header($th);
    $k = $total_sc_purchase_order = 0; //row colour counter
    
    $ub_header = get_sc_purchase_orders_header($order_no);
            
    label_row("Total Amount:", $ub_header['total']);
     
    
    //$project = get_project($_POST['project_id']);
              
    $taxes_total = display_selected_tax_types($order_no, get_post('tax_group_id')); 
           
    label_row("Taxes Total:", number_format($taxes_total, 2));
    
    end_table(1);
}



function save_import_po_order_taxes($order_no){
    
    $tax_msg = can_process_import_po_taxes($_POST['tax_group_id']);
    if($tax_msg["success"] !== true) 
    {          
        if(isset($tax_msg["focus_to"])){
            set_focus($tax_msg["focus_to"]);
        }
        return array("success" => false, "message" => $tax_msg["message"]);
    }
    
    $scpo_lines_total = get_sc_purchase_order_lines_total($order_no);
    $taxes_array = calculate_common_item_taxes($scpo_lines_total, $_POST['tax_group_id'], $_POST['tax_included']=null);    
    
//    $tax_types_array = get_tax_group_items_as_array($_POST['tax_group_id']);
              
    foreach ($taxes_array as &$tax_type){
        $postname = 'manual_tax_value_'.$tax_type['tax_type_id'];
//        if($tax_type['tax_type_id'] == 1 || $tax_type['tax_type_id'] == 2){
        if(isset($_POST[$postname]) && $_POST[$postname] > 0){

            $tax_value = input_num($postname);
            $tax_type['Value'] = $tax_value;            
        }       
//        }    
    }  

//    begin_transaction();
//    update_sc_purchase_order_taxes_manual($order_no, $taxes_array);
//    commit_transaction();
    
    return array("success" => true, "message" => "Taxes have been updated.");
}


function release_import_po_for_approval($order_no)
{    
    if(!can_release_purchase_order($order_no)){
        return;
    }
    
    begin_transaction();
    $rub_msg = release_purchase_order($order_no);
    if($rub_msg['success'] !== true){
        cancel_transaction();
        display_error($rub_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_PURCH_ORDER_no");
    set_session_variable('ST_PURCH_ORDER_messages', $rub_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_SCPO_No=$order_no");
    
    // meta forward
}

function send_import_po_back_to_originator($order_no)
{        
    begin_transaction();
     
    $scpoh = get_purchase_order_header_record($order_no);

    $current_user_id = $_SESSION['wa_current_user']->user;

    $sbdo_msg = send_back_to_document_originator(ST_PURCHORDER, $order_no, $scpoh['project_id'],
                                    $scpoh['next_approval_group_id'], $current_user_id, $scpoh['row_state'], 
                                    $scpoh['created_by']);
    
    if($sbdo_msg['success'] !== true){
        display_error_cancel($sbdo_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_PURCH_ORDER_no");
    set_session_variable('ST_PURCH_ORDER_messages', $sbdo_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_SCPO_No=$order_no");
        
}


function reject_import_po($order_no)
{
    begin_transaction();
    $scpoh = get_purchase_order_header_record($order_no);

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_PURCHORDER, $order_no, $scpoh['project_id'],
                    $scpoh['next_approval_group_id'], $current_user_id, $scpoh['row_state']);
    
    if($rj_msg['success'] !== true){
        display_error_cancel($rj_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_PURCH_ORDER_no");
    set_session_variable('ST_PURCH_ORDER_messages', $rj_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_SCPO_No=$order_no");
    

}




function save_import_po_header($order_no, &$Mode){
        
    $h_msg = can_process_local_purchase_order_header($order_no);   
    
    if($h_msg["success"] !== true){          
        if(isset($h_msg["focus_to"])){
            set_focus($h_msg["focus_to"]);
        }
        display_error($h_msg['message']);
    }
    else{   
        begin_transaction();
        $msg = save_purchase_order_header($order_no);
    
        if($msg['success'] !== true){
            cancel_transaction();
            display_error($msg['message']);
        }
        
        $msg = save_import_purchase_order_header($order_no);
        if($msg["success"] !== true){
            cancel_transaction();
            return array("success" => false, 'trans_no' => $order_no, "message" => $msg["message"]);
        }else{
//            update_sc_purchase_order_taxes($order_no, $_POST['tax_group_id'], $_POST['tax_included']);
            
            $rate_include_taxes = 0;
            $po_tax_total = input_num('freight_value') + input_num('insurance_value');
            update_purchase_order_header_totals($order_no, $po_tax_total, $rate_include_taxes);
    
            commit_transaction();
            $_POST['SCPO_No'] = $msg['trans_no'];
            display_notification($msg['message']);
            $Mode = 'RESET';
        }
    }

}


