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

$page_security = 'SA_SUBCONTRACTOR_INVOICE';
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 . "/projects/includes/db/subcontractor_invoices_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 = "Generate Subcontractor Invoice"), 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_INVOICE_no", $scpo_no);
}


if (isset($_GET['NewOrder']))
{
    $_POST['SCPO_No'] = -1;
    set_session_variable("ST_SUBCONTRACTOR_INVOICE_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_INVOICE_no", $_POST['SCPO_No']);
    }else{
        $scpo_no = get_session_variable('ST_SUBCONTRACTOR_INVOICE_no');
    }
}

if (isset($_GET['Generated_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Generated_ID'];
    $trans_type = ST_SUBCONTRACTOR_INVOICE;

    
    $message = ("Subcontractor Invoice $trans_no has been generated.");

    display_notification_centered($message);

    hyperlink_no_params("$path_to_root/projects/inquiry/subcontractor_purchase_orders_inquiry.php", _("Generate another &Subcontractor Invoice"));

    hyperlink_no_params("$path_to_root/projects/subcontractor_invoices.php?SCI_No=$trans_no", _("Edit this &Subcontractor Invoice"));
    
//    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();
}


if (isset($_GET['Closed_PO'])) 
{
	//return;
        
    $trans_no = $_GET['Closed_PO'];
    $trans_type = ST_SUBCONTRACTOR_INVOICE;

    
    $message = ("Subcontractor Purchase Order $trans_no has been closed for invoicing.");

    display_notification_centered($message);

    hyperlink_no_params("$path_to_root/projects/inquiry/subcontractor_purchase_orders_inquiry.php", _("Generate another &Subcontractor Invoice"));

    
//    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_sci($scpo_no)
{
    $sci_msg = can_process_sci_header($scpo_no);
     if($sci_msg["success"] !== true){
        return $sci_msg;
    }
         
    $result = get_sc_purchase_order_details($scpo_no); 
    
    $s_lines=0;
    while($row_d = db_fetch($result)){
        
        if((isset($_POST["selected_".$row_d["id"]])) && ($_POST["selected_".$row_d["id"]] == true))                 
        {
            $cpl_msg = can_process_sci_detail($scpo_no, $row_d['id']);
                if($cpl_msg["success"] !== true){
                return $cpl_msg;
            }
            
            $s_lines++;
        }        
    }    
    
    if($s_lines == 0){
        $message = "No Lines Selected";
        return array("success" => false, "focus_to" => '', "message" => $message);
    }
    
    return array("success" => true, "message" => "");      
}

function can_process_sci_header($scpo_no)
{            
    $scpoh = get_sc_purchase_orders_header ($scpo_no);
    if(!($scpoh['approval_status'] == AS_APPROVED)){
        $message = ("This Subcontractor Purchase Order is not approved. Can not generate an invoice from it.");
        return array("success" => false, "focus_to" => '', "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 (!($_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['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);
    }
    
    if(!($_POST['payment_term_id'] > 0))        
    {
        $message = "Please select a payment term.";
        $set_focus = 'payment_term_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
  
    return array("success" => true, "message" => "");    
}

 
function can_process_sci_detail($scpo_no, $selected_id)
{    
    if(!(check_num('quantity_'.$selected_id, 0.000001))){
        $message = "Line Id $selected_id : Invoice quantity should be greater than zero.";
        $set_focus = 'quantity_'.$selected_id;
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);         
    }
          
    $scpo_line = get_sc_purchase_orders_line($selected_id);

    if($scpo_line['item_type'] == 0)
    {
        if(!(strlen($scpo_line['description']) > 0)){
            $message = "Line Id $selected_id : Description is empty. Can not include this line.";
            $set_focus = 'description';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }
    else{
        if(!($scpo_line['boq_item_id'] > 0))
        {
            $message = "Line Id $selected_id : a BOQ Item is not selected. Can not include this line.";
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
    }

    if(!is_date($_POST['completed_date_'.$selected_id]))
    {
        $message = "Line Id $selected_id : Completed Date entered is not a valid date.";
        $set_focus = 'completed_date_'.$selected_id;
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    
    if (!($scpo_line['task_id'] > 0)){
        $message = "Line Id $selected_id : No budget is not selected. Can not include this line.";
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
        
    
    if(!(strlen($scpo_line['unit']) > 0)){
        $message = "Line Id $selected_id : No Unit is not selected. Can not include this line.";
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!(check_num2($scpo_line['rate'], 0.0001)))
    {
        $message = "Line Id $selected_id : Rate has to be positive. Can not include this line.";
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    $invoiced_qty = get_sc_po_line_invoiced_qty($selected_id);    
    $unapproved_invoices_qty = get_sc_po_line_unapproved_invoices_qty($selected_id);
    $po_line_qty = $scpo_line['quantity'];
    $new_qty = input_num('quantity_'.$selected_id);
    $total_qty = $new_qty + $invoiced_qty + $unapproved_invoices_qty;
    if($total_qty > $po_line_qty){
        $message = "Line Id $selected_id : Total quantity invoiced ". number_format($total_qty,3);
        $message .= " (this invoice ". number_format($new_qty,3).",";
        $message .= " approved invoices ". number_format($invoiced_qty,3).",";
        $message .= " unapproved invoices ". number_format($unapproved_invoices_qty,3).")";
        $message .= " will become higher than the PO line quantity ". number_format($po_line_qty,3).".";
        $set_focus = 'quantity_'.$selected_id;
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);   
    }
    
    return array("success" => true, "message" => "");    
}

  
function save_subcontractor_invoice_header(&$scpo_no)
{     
    global $Refs;
    
    $sci_taxes = array();
    $taxes_total = 0;
    $tax_group_id = get_post('tax_group_id');
    $tax_types_array = get_tax_group_items_as_array($tax_group_id);
    foreach ($tax_types_array as $tax_type){
        if(isset($_POST[$tax_type['tax_type_id'].'_msci_tax']) && input_num($tax_type['tax_type_id'].'_msci_tax') > 0){
            $tax_amount = input_num($tax_type['tax_type_id'].'_msci_tax');
            $a = array('tax_type_id' => $tax_type['tax_type_id'], 'tax_amount' => $tax_amount);
            $sci_taxes[] = $a;
            $taxes_total += $tax_amount;
        }
    }
    
    $payment_term_id = $_POST['payment_term_id'];
    $new_sc_inv_total = input_num('new_sc_inv_total');
    
    $due_date = calculate_duedate($payment_term_id, $_POST['date']);
    
    $sci_no = write_subcontractor_invoice_header(-1, $_POST['project_id'], $_POST['supplier_id'], $_POST['reference'], $_POST['supp_inv_ref'], 
                                        $payment_term_id, $_POST['date'], 
                                        $new_sc_inv_total, $taxes_total,                              
                                        '', 0,
                                        '', 0,
                                        $due_date , '', get_post('tax_group_id'), $sci_taxes, $scpo_no);   
        
        
    
    $Refs->save(ST_SUBCONTRACTOR_INVOICE, $sci_no, $_POST['reference']);
    
    if($sci_no > 0){
        set_session_variable("ST_SUBCONTRACTOR_INVOICE_no", $sci_no);
        return array("success" => true, 'trans_no' => $sci_no, "message" => "SubContractor invoice header information have been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save SubContractor invoice order header.");
    }
}


function save_subcontractor_invoice_details(&$scpo_no, $sci_no)
{
    $result = get_sc_purchase_order_details($scpo_no);     
     
    $k=0;
    $sequence = 10;
    while($row_a = db_fetch($result))
    {        
        if((isset($_POST['selected_'.$row_a['id']])) && ($_POST['selected_'.$row_a['id']] == true)){ 
                 
        alt_table_row_color($k);
        
        $po_line_id = $row_a['id'];
        $item_type = SCIIT_PO_LINE; 
        $boq_item_id = $row_a['boq_item_id'];

        $unit = $row_a['unit'];
        $rate = $row_a['rate'];

        $invoice_qty = input_num('quantity_'.$row_a['id']);
        $amount = $invoice_qty * $row_a['rate'];
        $task_id = $row_a['task_id'];         
        
        $selected_id=-1;
        $line_type=PILT_DETAIL;
        $category_id=0;
        $debit_account='';
        $credit_account='';
        $description = $row_a['description'];
        $completed_date= date2sql($_POST['completed_date_'.$row_a['id']]);
        $line_comment='';

    
        write_subcontractor_invoice_detail($sci_no, $selected_id, $line_type, $item_type, $po_line_id,
                                        $sequence, $boq_item_id, $description, $completed_date, $unit, 
                                        $invoice_qty, $rate, $amount, $line_comment,
                                        $task_id, $category_id, $debit_account, $credit_account);
      
        $sequence = $sequence + 10;
        }
    }
    return array("success" => true, 'trans_no' => '', "message" => " ");
}


function save_new_sc_invoice(&$scpo_no, $selected_id)
{  
    $sci_msg = can_process_sci($scpo_no);
    if($sci_msg['success'] !== true){
        display_error($sci_msg['message']);
        return;
    }
                       
    begin_transaction();
    $msg = save_subcontractor_invoice_header($scpo_no);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $scpo_no, "message" => $msg["message"]);
    }

    $new_sci_no = $msg['trans_no'];
    $msg_scid = save_subcontractor_invoice_details($scpo_no, $new_sci_no);
    if($msg["success"] !== true){
        cancel_transaction();
        return array("success" => false, 'trans_no' => $new_sci_no, "message" => $msg_scid["message"]);
    }

    
    commit_transaction();
    

    return array("success" => true, 'trans_no' => $new_sci_no, "message" => "Subcontractor Invoice $new_sci_no has been generated.");

//    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'];    
        
        $_POST['reference'] = $Refs->get_next(ST_SUBCONTRACTOR_INVOICE);
        

        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_term_id'])){
            $_POST['payment_term_id'] = $scpo_header['payment_terms'];
        }
        
    }
//    else{        
//        $_POST['reference'] = $Refs->get_next(ST_SUBCONTRACTOR_INVOICE);
   // }
        
    start_outer_table(TABLESTYLE2, "width=30%"); // outer table
    start_table(TABLESTYLE2);  
        table_section(1, "35%");
        
        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']; 
           
        if($scpo_no > 0){
            label_row("Supplier:", $scpo_header['supp_name']);
            hidden('supplier_id', $_POST['supplier_id']);
        }else{
            supplier_list_row("Supplier:", 'supplier_id', null, 'Select a Supplier', true);   
        }       
               
        date_row("Date", 'date');
              
        if($scpo_no > 0){
            if($_POST['rate_include_taxes'] == 1){
                $rate_include_taxes = "Yes";
            }else{
                $rate_include_taxes = "No";
            }
            
            label_row("Rate Include Taxes:", $rate_include_taxes);
            hidden('rate_include_taxes', $_POST['rate_include_taxes']);
        }else{
            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'];   
        }
        
        if($scpo_no > 0){
            label_row("Tax Group:", $scpo_header['tax_group_name']);
            hidden('tax_group_id', $_POST['tax_group_id']);
        }else{
            tax_groups_list_row("Tax Group:", 'tax_group_id', null, 'Select a Tax Group', true);     
        }
               
             
        if($scpo_no > 0){
            label_row("Agreement Reference:", $scpo_header['agreement_reference']);
            hidden('agreement_reference', $_POST['agreement_reference']);
        }else{
            text_row("Agreement Reference:", 'agreement_reference', null, null, null); 
        }
      
        payment_terms_list_row("Payment Term:", 'payment_term_id', null, 'Please select a Payment Term');
        text_row("Supp. Inv. Ref :", 'supp_inv_ref', null, null, null);           
        textarea_row("Comment:", 'header_comment', null, 25, 2);
       
     
    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(_("ID"),_('Item Type'),_("BOQ Item"), _('Period From'),_('Period To'),_("Units"), 
                _('Rate'), _('PO. Qty'), _("Invoiced Qty"), _("Quantity"),
                _("Amount"), _('Completed Date'), "");              
  
    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);

            label_cell($myrow['id']);
 
            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']);
            }
            
            label_cell(sql2date($myrow["period_from"]), "align=center");
            label_cell(sql2date($myrow["period_to"]), "align=center");

            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["rate"], 3), "align=right");
             
            label_cell(number_format($myrow["quantity"], 3), "align=right");
            label_cell($myrow["invoiced_qty"], "align=right");
            qty_cells(null, 'quantity_'.$myrow['id']);     
            
            

            $line_total = input_num('quantity_'.$myrow['id']) * $myrow["rate"];
            label_cell(number_format($line_total, 2), "align=right");
            
            $_POST['completed_date_'.$myrow['id']] = Today();
            date_cells(null, 'completed_date_'.$myrow['id']);
            
            check_cells(null, 'selected_'.$myrow['id'], null, false);            
            
            $total_scpo += $line_total; 

            end_row(); 

            alt_table_row_color($k);
            $task_name = $myrow['budget_code']." - ".$myrow["budget_description"]; 
            label_cell('');
            label_cell("<b>Budget: </b>".$task_name, "colspan= 11");
            label_cell('');
            end_row(); 
            
            
            if(strlen($myrow["comment"]) > 0){
                alt_table_row_color($k);
                label_cell('');
                label_cell("<b>Comment: </b>".$myrow["comment"], "colspan= 11");
                label_cell('');
                end_row(); 
            }           
        
        }
          
    }    
    
    start_row();
    label_cell("Total", "align=right colspan=10");    

    label_cell("<b>".number_format($total_scpo, 2)."</b>", "align=right");
   
    end_row();
    
    end_table();
    
    hidden('new_sc_inv_total', $total_scpo);
  
    return $total_scpo;
}


//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, $tax_factor)
{
    $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[$tax_type['tax_type_id'].'_msci_tax'] = $tax_amount * $tax_factor;
            amount_row($tax_type['tax_type_name'], $tax_type['tax_type_id'].'_msci_tax'); 
            
            $taxes_total += $tax_amount * $tax_factor;
        }
    }
      
    
        
    return $taxes_total;
}


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

//    table_header($th);
    
    display_heading("Tax Details");
    start_table(TABLESTYLE2, "width=25%");
    $k = $total_sc_purchase_order = 0; //row colour counter
    
    $ub_header = get_sc_purchase_orders_header($scpo_no);
    $tax_factor = $total_new_sc_invoice/$ub_header['total'];
            
    start_row();
    label_row("Total Amount:", number_format($total_new_sc_invoice, 2));
    end_row();
    
    //$project = get_project($_POST['project_id']);
              
    $taxes_total = display_selected_tax_types($scpo_no, get_post('tax_group_id'), $tax_factor); 
       
    start_row();    
    label_row("Taxes Total:", number_format($taxes_total, 2));
    end_row();
        
    end_table(1);
}

//function calculate_sc_po_task_remaining_totals($scpo_no)
//{        
//    $sc_po_details = get_sc_purchase_order_line_records($scpo_no);
//
//    while ($myrow = db_fetch($sc_po_details))
//    {
//        $a['row_id'] = $myrow['id'];
//        $a['stock_id'] = "";
//        $a['task_id'] = $myrow['task_id'];
//        $a['requested_qty'] = $myrow['quantity'];
//        $a['high_value_item'] = false;
//        $a['reference_cost'] = $myrow['rate'];
//        $a['standard_cost'] = $myrow['rate'];
//        $a['total_issued_qty'] = $myrow['invoiced_qty'];
//        $a['qty'] = $myrow['requested_qty'] - $a['total_issued_qty'];
//
//        $mr_details_array[] = $a;
//    }
//    
//    $mr_tasks_summary = calculate_task_remaining_totals($mr_details_array);
//    return $mr_tasks_summary;
//    
//}


function close_subcontractor_po($scpo_no)
{
    global $systypes_array;
    
    $can_close_scpo = false;
    
    $current_user_id = $_SESSION['wa_current_user']->user; 
    $sc_poh = get_sc_purchase_orders_header_record($scpo_no);
    
    begin_transaction();
    if($sc_poh['approval_status'] == AS_APPROVED || $sc_poh['approval_status'] == AS_ISSUED){
        $can_close_scpo = false;
        $tasks_summary = calculate_sc_po_task_remaining_totals($scpo_no);
//        get_task_cost_details($tasks_summary);
        $rta_msg = remove_task_allocations(ST_SUBCONTRACTOR_PURCH_ORDER, $scpo_no, 
                                $tasks_summary, $current_user_id);
        if($rta_msg['success'] !== true){
            cancel_transaction();
            return $rta_msg;
        }
        else{
            $can_close_scpo = true;
        }
    }
    else{
        $can_close_scpo = false;
        cancel_transaction();
        return array("success" => false, "message" => $systypes_array[ST_SUBCONTRACTOR_PURCH_ORDER]." # $scpo_no status does not allow closing it.");
    }
    
    
    if($can_close_scpo){
        
        $sc_po_close_msg = direct_update_document_status(ST_SUBCONTRACTOR_PURCH_ORDER, $scpo_no, AS_CLOSED, $sc_poh['row_state']);     

        if($sc_po_close_msg['success'] === true ){ 
            commit_transaction();
            return array("success" => true, "message" => $systypes_array[ST_SUBCONTRACTOR_PURCH_ORDER]." # $scpo_no has been closed.");
        }
        else{
            cancel_transaction();
            return array("success" => false, "message" => $sc_po_close_msg['message']);
        }
    }
    
    cancel_transaction();
    return array("success" => false, "message" => "Could not close ".$systypes_array[ST_SUBCONTRACTOR_PURCH_ORDER]." #". $scpo_no); 


//    update_sc_po_closed($scpo_no);
}

//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.");
//}

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

//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['Generate_SC_Invoice']) || isset($_POST['Generate_SC_Invoice_Close_PO'])){
           
    $cppd_msg = can_process_sci($scpo_no);
    if($cppd_msg['success'] !== true){
        display_error($cppd_msg['message']);
        return;
    }
    
    $msg = save_new_sc_invoice($scpo_no, $selected_id);
    
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        if(isset($_POST['Generate_SC_Invoice_Close_PO'])){
            $cscpo_msg = close_subcontractor_po($scpo_no);
            if($cscpo_msg['success'] !== true){
                display_error($msg['message']);
            }else{
                clear_session_variable("ST_SUBCONTRACTOR_INVOICE_no");
                $new_sc_inv_no = $msg['trans_no'];
                meta_forward($_SERVER['PHP_SELF'], "Generated_ID=$new_sc_inv_no"); 
                $Mode = 'RESET'; 
            }
        }else{
            clear_session_variable("ST_SUBCONTRACTOR_INVOICE_no");
            $new_sc_inv_no = $msg['trans_no'];
            meta_forward($_SERVER['PHP_SELF'], "Generated_ID=$new_sc_inv_no"); 
            $Mode = 'RESET';
        }
    }

}


if(isset($_POST['Close_PO'])){
    
    $cscpo_msg = close_subcontractor_po($scpo_no);
    if($cscpo_msg['success'] !== true){
        display_error($msg['message']);
    }else{
        meta_forward($_SERVER['PHP_SELF'], "Closed_PO=$scpo_no");
        $Mode = 'RESET';
    }
}
        
if(isset($_POST['Calculate_SC_Invoice'])){
           
    $cppd_msg = can_process_sci($scpo_no);
    if($cppd_msg['success'] !== true){
        display_error($cppd_msg['message']);
    }
}


//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();

//------------------------------------------------------------------------------------------------------------
              
$total_scpo = display_sc_purchase_order_details($selected_id, $scpo_no);

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

br();

 
if($scpo_no > 0){
    display_tax_edit_controls($scpo_no, $total_scpo);
    
//    submit_center_first('Save_Tax', _("Save Taxes"), '', 'default');
    
}
 
submit_center_first('Calculate_SC_Invoice', _("Calculate"), '', 'default');
submit_center_last('Generate_SC_Invoice', _("Process"), '', 'default');

br(1);

submit_center_first('Generate_SC_Invoice_Close_PO', _("Process and Close PO"), '', 'default');
submit_center_last('Close_PO', _("Close PO"), '', 'default');


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



?>
