<?php
/**********************************************************************
***********************************************************************/

$page_security = 'SA_SUBCONTRACTOR_PURCHASE_ORDER';
if (!@$_GET['popup'])
	$path_to_root = "..";
else	
	$path_to_root = "../..";

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 . "/includes/approval_functions.inc"); 
include_once($path_to_root . "/reporting/includes/reporting.inc");

include_once($path_to_root . "/includes/db/approval_functions_db.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_items_db.inc");
include_once($path_to_root . "/projects/includes/db/subcontractor_purchase_orders_db.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_item_groups_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");


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

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

page(_($help_context = "Subcontractor Purchase Orders"), false, false, "", $js);

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


$scpo_no = -1;
 
if (isset($_GET['SCPO_No']))
{
    $_POST['SCPO_No'] = $_GET['SCPO_No'];
    set_session_variable("ST_SUBCONTRACTOR_PURCH_ORDER_no", $scpo_no);
}


if (isset($_GET['NewOrder']))
{
    $_POST['SCPO_No'] = -1;
    set_session_variable("ST_SUBCONTRACTOR_PURCH_ORDER_no", $_POST['SCPO_No']);
} 

if (isset($_POST['SCPO_No']) && $_POST['SCPO_No'] > 0){
    $scpo_no = $_POST['SCPO_No'];
}
else{
    if(!isset($_POST['SCPO_No']) > 0){
        $_POST['SCPO_No'] = -1;
        set_session_variable("ST_SUBCONTRACTOR_PURCH_ORDER_no", $_POST['SCPO_No']);
    }else{
        $scpo_no = get_session_variable('ST_SUBCONTRACTOR_PURCH_ORDER_no');
    }
}

if (isset($_GET['Processed_SCPO_No'])) 
{
	//return;
        
    $trans_no = $_GET['Processed_SCPO_No'];
    $trans_type = ST_UTILITY_BILLS;
    $message = get_session_variable('ST_UTILITY_BILLS_messages');
    clear_session_variable('ST_UTILITY_BILLS_messages');
    
	display_notification_centered($message);

	hyperlink_no_params("$path_to_root/projects/subcontractor_purchase_orders.php", _("Create another &Subcontractor Purchase Order"));
        
        hyperlink_no_params("$path_to_root/projects/inquiry/subcontractor_purchase_orders_inquiry.php", _("Edit another &Subcontractor Purchase Order"));
        
        hyperlink_no_params("$path_to_root/projects/inquiry/approve_subcontractor_purchase_order_inquiry.php", _("Approve &Subcontractor Purchase Orders"));
       
        display_note(print_document_link($trans_no, _("&Print this Project Purchase Order"), true, $trans_type), 0, 0);

//	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");

	display_footer_exit();
}

function can_delete_sc_purchase_order_details($scpo_no)
{
    $line_count = get_sc_purchase_orders_line_count($scpo_no);
    if(!($line_count > 0)){
        $message = "This is the last line. It can not be deleted.";
        display_error($message);
        return false;
    }
    
    return true;

}

function can_process_sc_purchase_order_header($scpo_no)
{
    global $Refs;
    
    if($scpo_no > 0){
        $scpoh = get_sc_purchase_orders_header ($scpo_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 Subcontractor 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_SUBCONTRACTOR_PURCH_ORDER, $scpoh['project_id'], $scpoh['next_approval_group_id'] , $current_user_id, $scpoh['created_by'], $scpo_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
        
    }
    
    if(!$Refs->is_valid(get_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(get_post('reference'), ST_SUBCONTRACTOR_PURCH_ORDER, $scpo_no);
    if($ref_msg){
        $message = $ref_msg;
        $set_focus = 'reference';
        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(!($_POST['supplier_id'] > 0))
    {
        $message = "Please select a supplier.";
        $set_focus = 'supplier_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }      

    if(!is_date($_POST['date']))
    {
        $message = "Date entered is not a valid date.";
        $set_focus = 'date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if(!($_POST['tax_group_id'] > 0))
    {
        $message = "Please select a tax group.";
        $set_focus = 'tax_group_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
      
    return array("success" => true, "message" => "");    
}

 
function can_process_sc_purchase_order_line($scpo_no)
{    
    if($_POST['item_type'] == 0)
    {
        if(!(strlen($_POST['description']) > 0)){
            $message = "Description can not be empty.";
            $set_focus = 'description';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }
    else{
        if(!($_POST['item_id'] > 0))
        {
            $message = "Please select a BOQ Item.";
            $set_focus = 'task_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
    }

    if(!$_POST['unit_id'] > 0){
            $message = "Please select an unit.";
            $set_focus = 'unit_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
        
    if(!(check_num('quantity', 0.0001)))
    {
        $message = "Quantity should be greater than zero.";
        $set_focus = 'quantity';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!(check_num('rate', 0.0001)))
    {
        $message = "Rate should be greater than zero.";
        $set_focus = 'rate';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!is_date($_POST['period_from']))
    {
        $message = "Period from date is not a valid date.";
        $set_focus = 'period_from';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if(!is_date($_POST['period_to']))
    {
        $message = "Period to date is not a valid date.";
        $set_focus = 'period_to';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
    
    if(date1_greater_date2($_POST['period_from'], $_POST['period_to']))
    {
        $message = "Period from date cannot be greater than period to date.";
        $set_focus = 'period_to';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
    
    if(!($_POST['task_id'] > 0))
    {
        $message = "Please select a Budget.";
        $set_focus = 'task_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }    
              
    return array("success" => true, "message" => "");    
}

   

function save_sc_purchase_orders_header(&$scpo_no)
{     
    $scpo_no = write_sc_purchase_order_header($scpo_no, $_POST['reference'], 
                                        $_POST['project_id'], $_POST['supplier_id'],
                                        $_POST['date'], $_POST['rate_include_taxes'],
                                        $_POST['tax_group_id'], $_POST['approval_status']=0, 
                                        $_POST['agreement_reference'], $_POST['header_comment'],
                                        $_POST['payment_terms']);   
    
    if($scpo_no > 0){
        set_session_variable("ST_SUBCONTRACTOR_PURCH_ORDER_no", $scpo_no);
        return array("success" => true, 'trans_no' => $scpo_no, "message" => "SubContractor purchase order header information have been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save SubContractor purchase order header.");
    }
}


function save_sc_purchase_order_detail(&$scpo_no, $selected_id)
{
    if($_POST['item_type'] == 1){
        $boq_item_id = $_POST['item_id'];
        $unit_id = $_POST['unit_id'];
        $_POST['description'] = '';
    }else{
        $boq_item_id = 0;
        $unit_id = $_POST['unit_id'];
    }
    
    write_sc_purchase_order_detail($scpo_no, $selected_id, $_POST['item_type'], 
                                    $_POST['description'], $boq_item_id, $unit_id, 
                                    input_num('quantity'), input_num('rate'),
                                    $_POST['period_from'],
                                    $_POST['period_to'], $_POST['task_id'],
                                    $_POST['comment'], $_POST['tax_group_id'], $_POST['rate_include_taxes'] );
    
    return array("success" => true, 'trans_no' => '', "message" => " ");
}


function save_sc_purchase_order(&$scpo_no, $selected_id)
{    
    $h_msg = can_process_sc_purchase_order_header($scpo_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_sc_purchase_order_line($scpo_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_sc_purchase_orders_header($scpo_no);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $scpo_no, "message" => $msg["message"]);
    }

    $msg = save_sc_purchase_order_detail($scpo_no, $selected_id);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $scpo_no, "message" => $msg["message"]);
    }
    
    commit_transaction();
    if($scpo_no > 0){
        return array("success" => true, 'trans_no' => $scpo_no, "message" => $msg["message"]);
    }
    else{
        return array("success" => true, 'trans_no' => $scpo_no, "message" => "Subcontractor purchase orders $scpo_no has been created.");
    }

}

function display_sc_purchase_order_header($scpo_no)
{
    global $approval_statuses, $Refs;
    
    if($scpo_no > 0){
        $scpo_header = get_sc_purchase_orders_header($scpo_no);
        
        $project_id = $scpo_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;
        }  
        
        $_POST['project_id'] = $scpo_header['project_id'];
    
        if(!isset($_POST['reference'])){
            $_POST['reference'] = $scpo_header['reference'];
        }

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

        if(!isset($_POST['rate_include_taxes'])){
            $_POST['rate_include_taxes'] = $scpo_header['rate_include_taxes'];
        }
        
        if(!isset($_POST['tax_group_id'])){
            $_POST['tax_group_id'] = $scpo_header['tax_group_id'];
        }
        
        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $scpo_header['project_description'];
        }
        
        if(!isset($_POST['approval_status'])){
            $_POST['approval_status'] = $scpo_header['approval_status'];
        }
        
        if(!isset($_POST['agreement_reference'])){
            $_POST['agreement_reference'] = $scpo_header['agreement_reference'];
        }
        
        if(!isset($_POST['header_comment'])){
            $_POST['header_comment'] = $scpo_header['comment'];
        }
        
        if(!isset($_POST['payment_terms'])){
            $_POST['payment_terms'] = $scpo_header['payment_terms'];
        }
    
    }
    else{
        
        $_POST['reference'] = $Refs->get_next(ST_SUBCONTRACTOR_PURCH_ORDER);
        $_POST['approval_status'] = 0;
    }
        
    start_outer_table(TABLESTYLE2, "width=55%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "50%");
        
        text_row("Reference:", 'reference', null, null, null);  
        
        if($scpo_no > 0){
            label_row("Project:", $_POST['project_description']);   
            hidden('project_id', $_POST['project_id']);
        }else{
            project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true); 
        }
        
        $project = get_project($_POST['project_id']);
        
        $_POST['customer_name'] = $project['customer_name']; 
        $_POST['customer_id'] = $project['customer_id']; 
           
       
        supplier_list_row("Supplier:", 'supplier_id', null, 'Select a Supplier', true);
               
        date_row("Date", 'date');
        
        payment_terms_list_row("Payment Terms:", 'payment_terms');
              
        table_section(2, "50%");
        yesno_list_row("Rate Include Taxes:", 'rate_include_taxes', null, "Yes", "No", false);
      
        $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, 'Select a Tax Group', true);            
             
        text_row("Agreement Reference:", 'agreement_reference', null, null, null); 
        
        textarea_row("Comment:", 'header_comment', null, 25, 1);
        
        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $scpo_no."&source_type_id=".ST_SUBCONTRACTOR_PURCH_ORDER, "Approval Status");
        label_row($s,$approval_statuses[$_POST['approval_status']]);  
     
//    end_table(1);

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



function display_sc_purchase_order_details($selected_id, $scpo_no)
{      
    global $Ajax;              
       
    $result = get_sc_purchase_order_details($scpo_no);     
         
    start_table(TABLESTYLE, "width=98%");
    $th = array(_('Item Type'),_("BOQ Item"), _("Units"), _('Quantity'), _('Rate'),
                _('Period From'),_('Period To'),_("Amount"),
                _('Budget'), "", "");              
  
    div_start('sc_purchase_orders');
        $Ajax->activate('sc_purchase_orders');
    div_end();
    
    table_header($th);
    $k = 0; //row colour counter
      
    $total_scpo=0;
    while ($myrow = db_fetch($result))
    {
        if($selected_id != $myrow["id"]){
            alt_table_row_color($k);


            if($myrow["item_type"] == 0){
                $item_type = "Description";
            }else{
                $item_type = "BOQ Item";
            }
            label_cell($item_type);

            if($myrow["item_type"] == 1){

                if($myrow['boq_item_id'] > 0){
                    label_cell($myrow['boq_item_code']." - ".$myrow['boq_item_description']);
                }else{
                    label_cell("");
                }

            }else{
                label_cell($myrow['description']);
            }

            if($myrow["item_type"] == 1){
                if($myrow['boq_item_id'] > 0){
                    $unit_name = $myrow['unit'];
                }else{
                    $unit_name = "";
                }

            }else{
                $unit_name = $myrow['unit_name'];
            }

            label_cell($unit_name);
            label_cell(number_format($myrow["quantity"], 3), "align=right");
            label_cell(number_format($myrow["rate"], 3), "align=right");
            label_cell(sql2date($myrow["period_from"]), "align=center");
            label_cell(sql2date($myrow["period_to"]), "align=center");

            $amount = $myrow["quantity"] * $myrow["rate"];
            label_cell(number_format($amount, 2), "align=right");
            label_cell($myrow['budget_code']." - ".$myrow["budget_description"]);  
            
            
            $total_scpo += $amount; 
            edit_button_cell("Edit".$myrow["id"], _("Edit"));    
            delete_button_cell("Delete".$myrow["id"], _("Delete"));

            end_row(); 
            
            if(strlen($myrow["comment"]) > 0){
                alt_table_row_color($k);
                label_cell('');
                label_cell("<b>".$myrow["comment"]."</b>", "colspan= 10");
                end_row(); 
            }
            

            
        
        }
    
        else{
            $total_scpo += display_sc_purchase_orders_edit_controls($selected_id, $Mode);
        }
      
    }
    
    if(!($selected_id > 0)){
       display_sc_purchase_orders_edit_controls($selected_id, $Mode);
    }
    
    start_row();
    label_cell("Total", "align=right colspan=7");
    
//    if($selected_id > 0){
//        label_cell("<b>".number_format($total_scpo, 2)."</b>", "align=right");
//    }else{
        label_cell("<b>".number_format($total_scpo, 2)."</b>", "align=right");
//    }
   
    end_row();
    
    end_table();
  
}


function display_sc_purchase_orders_edit_controls($selected_id, &$Mode)
{
    $line_total = 0;
    
    echo "<td colspan=9>";
    start_outer_table();
    table_section(1);

    if($selected_id > 0){
        $scpo_detail = get_sc_purchase_orders_line($selected_id);
    }

    
    if($selected_id > 0 && 
                (isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] != $selected_id)){

        $_POST['item_type'] = $scpo_detail['item_type'];
        $_POST['description'] = $scpo_detail['description'];
        $_POST['unit_id'] = $scpo_detail['unit'];
        $_POST['quantity'] = $scpo_detail['quantity'];
        $_POST['rate'] = $scpo_detail['rate'];

        $_POST['period_from'] = sql2date($scpo_detail['period_from']);
        $_POST['period_to'] = sql2date($scpo_detail['period_to']);
        $_POST['task_id'] = $scpo_detail['task_id'];
        $_POST['item_id'] = $scpo_detail['boq_item_id'];

        $_POST['comment'] = $scpo_detail['comment'];
        $_POST['item_boq_group_id'] = $scpo_detail['item_boq_group_id'];
        $_POST['task_boq_group_id'] = $scpo_detail['task_boq_group_id'];
        
        $line_total = $scpo_detail['quantity'] * $scpo_detail['rate'];;
    }
    else{
        if(!isset($_POST['item_boq_group_id'])){
            $_POST['item_boq_group_id'] = 0;
        }
        if(!isset($_POST['task_boq_group_id'])){
            $_POST['task_boq_group_id'] = 0;
        }
    }


    hidden('selected_id', $selected_id );
    hidden('previous_selected_id', $selected_id );

    
    
    yesno_list_row("Item Type:", 'item_type', null, "BOQ Item", "Description", true);
    

    if($_POST['item_type'] == 0){
//        text_row("Description:", 'description', null, 50, 500);
        textarea_row("Description:", 'description', null, 30, 1);
        stock_units_list_row("Unit :", 'unit_id', null, true, 'Please select a unit');     
    }else{
        project_boq_item_groups_list_row("BOQ Item Group:", "item_boq_group_id", $_POST['project_id'], null, "No BOQ Item Group", true);
        group_boq_items_list_row("BOQ Item:", "item_id", $_POST['project_id'], $_POST['item_boq_group_id'], null, false, true);
          
        $boq_item = get_project_boq_item_details($_POST['item_id']);
        
        label_row("Unit:", $boq_item['unit_name']);
        hidden('unit_id', $boq_item['unit']);
    }
    
        
        
    
    
    table_section(2);
    amount_row("Quantity:", 'quantity');
    amount_row("Rate:", 'rate');

    date_row("Period From :", 'period_from');
    date_row("Period To :", 'period_to');
    
    if($_POST['item_type'] == 0){
        $_POST['boq_group_id'] = 0;
    }

    table_section(3);
    project_boq_item_groups_list_row("BOQ Item Group:", "task_boq_group_id", $_POST['project_id'], null, "No BOQ Item Group", true);
    group_tasks_list_row("Budget :", 'task_id', $_POST['project_id'], $_POST['task_boq_group_id'], null, _('Select a budget')); 
    
    table_section(4);
    textarea_row("Comments :", 'comment', null, 30, 4);
    
    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 Item"), "colspan=2",
		    _('Add new item to document'), true);
	}

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

}

function can_release_sc_purchase_order($scpo_no)
{
    $line_count = get_sc_purchase_orders_line_count($scpo_no);
    if (!($line_count > 0))
    {
        display_error("There are no details entered. Can not release this document.");
        return false;
    }
    
    $ubh = get_sc_purchase_orders_header($scpo_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 Subcontractor Purchase Order status does not allow further updating.");
        return false;
    }
    
    return true;
}


function can_process_tax($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($scpo_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($scpo_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($scpo_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($scpo_no);
            
    label_row("Total Amount:", $ub_header['total']);
     
    
    //$project = get_project($_POST['project_id']);
              
    $taxes_total = display_selected_tax_types($scpo_no, get_post('tax_group_id')); 
           
    label_row("Taxes Total:", number_format($taxes_total, 2));
    
    end_table(1);
}


function save_sc_purchase_order_taxes($scpo_no){
    
    $tax_msg = can_process_tax($_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($scpo_no);
    $taxes_array = calculate_common_item_taxes($scpo_lines_total, $_POST['tax_group_id'], $_POST['rate_include_taxes']);    
    
//    $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($scpo_no, $taxes_array);
    commit_transaction();
    
    return array("success" => true, "message" => "Taxes have been updated.");
}


function release_sc_purchase_order_for_approval($scpo_no)
{    
    if(!can_release_sc_purchase_order($scpo_no)){
        return;
    }
    
    begin_transaction();
    $rub_msg = release_sc_purchase_order($scpo_no);
    if($rub_msg['success'] !== true){
        cancel_transaction();
        display_error($rub_msg['message']);
        return;
    }

    commit_transaction();
    clear_session_variable("ST_SUBCONTRACTOR_PURCH_ORDER_no");
    set_session_variable('ST_SUBCONTRACTOR_PURCH_ORDER_messages', $rub_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_SCPO_No=$scpo_no");
    
    // meta forward
}

function send_sc_purchase_order_back_to_originator($scpo_no)
{        
    begin_transaction();
     
    $scpoh = get_sc_purchase_orders_header($scpo_no);

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

    $sbdo_msg = send_back_to_document_originator(ST_SUBCONTRACTOR_PURCH_ORDER, $scpo_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_SUBCONTRACTOR_PURCH_ORDER_no");
    set_session_variable('ST_SUBCONTRACTOR_PURCH_ORDER_messages', $sbdo_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_SCPO_No=$scpo_no");
        
}


function reject_sc_purchase_order($scpo_no)
{
    begin_transaction();
    $scpoh = get_sc_purchase_orders_header($scpo_no);

    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_SUBCONTRACTOR_PURCH_ORDER, $scpo_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_SUBCONTRACTOR_PURCH_ORDER_no");
    set_session_variable('ST_SUBCONTRACTOR_PURCH_ORDER_messages', $rj_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "Processed_SCPO_No=$scpo_no");
    

}

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


if(isset($_POST['Update_Release_Sub_PO']))
{
    release_sc_purchase_order_for_approval($scpo_no);
}


if (isset($_POST['Back_To_Originator_Sub_PO'])){

    send_sc_purchase_order_back_to_originator($scpo_no);        
} 

if (isset($_POST['Reject_Sub_PO'])){

    reject_sc_purchase_order($scpo_no);        
}


if(isset($_POST['Save_SC_Purchase_Orders'])){
        
    $h_msg = can_process_sc_purchase_order_header($scpo_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_sc_purchase_orders_header($scpo_no);
    
        if($msg['success'] !== true){
            cancel_transaction();
            display_error($msg['message']);
        }
        else{
            update_sc_purchase_order_taxes($scpo_no, $_POST['tax_group_id'], $_POST['rate_include_taxes']);
            commit_transaction();
            $_POST['SCPO_No'] = $msg['trans_no'];
            display_notification($msg['message']);
            $Mode = 'RESET';
        }
    }

}


if(isset($_POST['AddItem']) || isset($_POST['UpdateItem'])){
        
    $msg = save_sc_purchase_order($scpo_no,$selected_id);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        $_POST['SCPO_No'] = $msg['trans_no'];
        display_notification($msg['message']);
        display_notification("Taxes have been recalculated and updated.");
        $Mode = 'RESET';
    }

}


if(isset($_POST['Save_Tax'])){
    
    $spo_msg = save_sc_purchase_order_taxes($scpo_no);
    if($spo_msg['success'] !== true){
        display_error($spo_msg['message']);
    }
    else{
        $_POST['SCPO_No'] = $scpo_no;
        display_notification($spo_msg['message']);
        $Mode = 'RESET';
    }
}


if (isset($_POST['CancelItemChanges'])){

    $selected_id = -1;
}


if (isset($_POST['cancel'])){
    $Mode = 'RESET';
    $selected_id = -1;
    unset($_POST);
}  



if ($Mode == 'Delete')
{
    if(can_delete_sc_purchase_order_details($scpo_no)){
//        begin_transaction();
        $recs = delete_sc_purchase_order_details($selected_id);
        if($recs == 1){
            update_sc_purchase_order_taxes($scpo_no, $_POST['tax_group_id'], $_POST['rate_include_taxes']);
//            commit_transaction();
            $_POST['SCPO_No'] = $scpo_no;

            $Mode = 'RESET';
            display_notification(_("Subcontractor purchase order has been deleted."));
        }
        else{
          //  cancel_transaction();
            display_error(_("Subcontractor purchase order could not be deleted."));
        }
    }
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
}
    $Ajax->activate('_page_body');
    $Ajax->activate('billing_items');
//--------------------------------------------------------------------------------------------------------------
if (!@$_GET['popup'])
start_form();


display_sc_purchase_order_header($scpo_no);   

if($scpo_no > 0){
    submit_center_first('Save_SC_Purchase_Orders', _("Save"), '', 'default');
   
    br(2);
    
    submit_center_first('Update_Release_Sub_PO', "Release for Approval", '', 'default');
    submit('Back_To_Originator_Sub_PO', 'Back To Originator', true, '', 'default');
    submit_center_last('Reject_Sub_PO', "Reject", '', 'default');	
}

br(2);

//------------------------------------------------------------------------------------------------------------
     
          
display_sc_purchase_order_details($selected_id, $scpo_no);
   
//end_table(1);

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

//display_sc_purchase_orders_edit_controls($selected_id, $Mode);


//if($selected_id > 0){
//    submit_center_first('Update_SC_purchase_orders', _("Update"), '', 'default');
//    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//}
//else{        
//    submit_center_first('Add_SC_purchase_orders', _("ADD"), '', 'default');
//    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
//}

br();

 
if($scpo_no > 0){
    display_tax_edit_controls($scpo_no);
    
    submit_center_first('Save_Tax', _("Save Taxes"), '', 'default');
    
    br();
}
 

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



?>
