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

function can_release_subcontractor_invoice($sci_no)
{    
    if(!($sci_no > 0)){
        $message = "This Subcontractor Invoice is not saved. Please save it before releasing";
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
        
    $sci = get_subcontractor_invoice_header_record($sci_no);
    $sc_invoice_tax_free_total = $sci['total'];
    
    if(!($sc_invoice_tax_free_total > 0)){
        $message = "This Subcontractor Invoice tax free total is zero. It can not be released.";
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
        
    $budget_lines_total = $non_budget_lines_total = 0;
    $sci_result = get_subcontractor_invoice_detail_records($sci_no);
    while ($row = db_fetch($sci_result)) {
        if(!(isset($row['category_id']) && $row['category_id'] > 0)){
            $message = "Sequence No ".$row['sequence']." : no category selected. Can not release this document";
            $set_focus = 'category_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
            
        $category = get_subcontractor_invoice_line_category_by_category_id($row['category_id']);
        if($category['budget_required'] == 1){
            if(!($row['task_id'] > 0)){
                $message = "Sequence No ".$row['sequence']." : Selected line category requires a budget to be selected. Can not release this document";
                $set_focus = 'category_id';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
            }
            else{
                $budget_lines_total += $row['amount'];
            }
        }
        else{
            $non_budget_lines_total += $row['amount'];
        }
    }
    
    //Temporory fix for ($budget_lines_total + $non_budget_lines_total) < $sc_invoice_tax_free_total issue sometimes when both values appear to be same
    $ve = 0.000000001;
    
//    if($task_lines_total < $sc_invoice_tax_free_total){
//        $message = "Total value of lines in the detail section (".number_format($task_lines_total,2)
//                .") can not be less than the tax free total (".number_format($sc_invoice_tax_free_total,2).")";
//        $set_focus = '';
//        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
//    }
    if(($budget_lines_total + $non_budget_lines_total + $ve) < $sc_invoice_tax_free_total){
        $message = "Budget validation requirs current total value of budget required lines in the detail section "
                    .number_format($budget_lines_total,2).", to be minimum ".number_format($sc_invoice_tax_free_total - $non_budget_lines_total,2)." at least."
                    ." (= tax free total (".number_format($sc_invoice_tax_free_total,2).") - budget NOT required lines total (".number_format($non_budget_lines_total,2)."))";
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }

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


function check_sc_po_invoiced_quantities($order_no)
{
    $result = get_subcontractor_invoice_details($order_no);
    
    while($row = db_fetch($result)){
        if($row['item_type'] == SCIIT_PO_LINE)
        {
            $inv_line_id = $row['id'];
            $po_line_id = $row['po_line_id'];
            $new_qty = $row['quantity'];
            $seq_no = $row['sequence'];
            $msg = check_sc_po_line_invoiced_quantity($inv_line_id, $po_line_id, $new_qty, $seq_no);
            if($msg['success'] !== true){
                return $msg;
            }
        }
    }
    
    return array("success" => true, "message" => "");    
    
}

function check_sc_po_line_invoiced_quantity($inv_line_id, $po_line_id, $new_qty, $seq_no)
{

    $sc_po_line = get_sc_purchase_order_line_record($po_line_id);

    $po_line_qty = $sc_po_line['quantity'];

    $invoiced_qty = get_sc_po_line_invoiced_qty($po_line_id);    
    $unapproved_invoices_qty = get_sc_po_line_unapproved_invoices_qty($po_line_id, $inv_line_id);    
    $total_qty = $new_qty + $invoiced_qty + $unapproved_invoices_qty;
    if($total_qty > $po_line_qty){
        $message = "Sequence No $seq_no : 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_'.$inv_line_id;
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);   
    }
    return array("success" => true, "message" => "");    
}

function can_process_sci_detail($selected_id)
{    

    if($_POST['item_type'] == SCIIT_PO_LINE)
    {
        if(!($_POST['po_line_id'] > 0)){
            $message = "No associated Po Line found. Can not save this line.";
            $set_focus = 'item_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }        
            
    if($_POST['item_type'] == SCIIT_BOQ_ITEM)
    {
        if(!($_POST['item_id'] > 0)){
            $message = "When Item Type is BOQ Item, a BOQ Item has be selected.";
            $set_focus = 'item_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }
    
    if(!is_date($_POST['completed_date']))
    {
        $message = "Line date entered is not a valid date.";
        $set_focus = 'completed_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if(!check_num('quantity', 0))
    {
        $message = "Quantity entered has to be zero or positive.";
        $set_focus = 'quantity';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
    
    if($_POST['item_type'] == SCIIT_PO_LINE)
    {
        $inv_line_id = $selected_id;
        $po_line_id = $_POST['po_line_id'];
        $new_qty = input_num('quantity');
        $seq_no = $_POST['sequence'];
        
        $msg = check_sc_po_line_invoiced_quantity($inv_line_id, $po_line_id, $new_qty, $seq_no);
        if($msg['success'] !== true){
            return $msg;
        }
    
    }

    if(!($_POST['category_id'] > 0)){
        $message = "Please select a line category.";
        $set_focus = 'category_id';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
    }
    
    $category = get_subcontractor_invoice_line_category_by_category_id($_POST['category_id']);
    if($category['budget_required'] == 1){
        if(!($_POST['task_id'] > 0)){
            $message = "Selected line category requires a budget to be selected.";
            $set_focus = 'task_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message); 
        }
    }
         
    return array("success" => true, "message" => "");    
}




function _get_completed_date()
{    
    switch ($_POST['line_type']){
            case PILT_MAIN_HEADER:
            case PILT_MAIN_SUMMARY:
            case PILT_SUB_HEADER:
            case PILT_SUB_SUMMARY:
            case PILT_FINAL_TOTAL:
                $_POST['completed_date'] = '';
                break;
    }  
    
    if(is_date($_POST['completed_date'])){
        return date2sql($_POST['completed_date']);      
    }
    else{  
        return '';    
    }
}


function save_subcontractor_invoice_header(&$sci_no)
{
    $validate = can_process_sci_header($sci_no);   
    
    if($validate["success"] !== true) 
    {          
        if(isset($validate["focus_to"])){
            set_focus($validate["focus_to"]);
        }
        return array("success" => false, "message" => $validate["message"]);
    }
    
    $due_date = get_invoice_duedate($_POST['payment_terms'], $_POST['ord_date']);

    $sci_taxes = array();
    $taxes_total = $staxes_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;
            
            if ($tax_type['suspended'] == 1) {
                $staxes_total += $tax_amount;
            } else {
                $taxes_total += $tax_amount;
            }
        }
    }
    
    $project_sales_order_id = 0;
    if(get_post('project_sales_order_id') > 0){
        $project_sales_order_id = get_post('project_sales_order_id');
    }
    
    $sci_no = write_subcontractor_invoice_header($sci_no, $_POST['project_id'], $_POST['supplier_id'], $_POST['reference'], $_POST['supp_inv_ref'], 
                                        $_POST['payment_terms'], $_POST['ord_date'], 
                                        input_num('total'), $taxes_total,                              
                                        get_post('payment_application_ref'), input_num('payment_application_amount'),
                                        get_post('payment_certificate_ref'),input_num('payment_certificate_amount'),
                                        $due_date, '', get_post('tax_group_id'), $sci_taxes, 0, $staxes_total);   
            
    
    if($sci_no > 0){
        return array("success" => true, 'trans_no' => $sci_no, "message" => "Project Invoice $sci_no has been saved.");
    }
    else{
        return array("success" => false, 'trans_no' => '', "message" => "Could not save Project Invoice.");
    }
}


function save_subcontractor_invoice_detail(&$sci_no, $selected_id)
{
    $msg = can_process_sci_detail($selected_id);
    if($msg["success"] !== true){
        return $msg;
    }
    
    switch ($_POST['line_type']) {
            case PILT_MAIN_HEADER:
                $amount = 0;
                break;
            case PILT_MAIN_SUMMARY:
                $amount = input_num('amount');
                break;
            case PILT_MAIN_ITEM:
                if($_POST["unit"] == '' || $_POST["unit"] == '0'){
                    $amount = input_num('amount');
                }
                else{                    
                    $amount = input_num('quantity') * input_num('rate');
                }                
                break;
            case PILT_SUB_HEADER:
                $amount = 0;
                break;
            case PILT_SUB_SUMMARY:
                $amount = input_num('amount');
                break;
            case PILT_SUB_ITEM:
                if($_POST["unit"] == '' || $_POST["unit"] == '0'){
                    $amount = input_num('amount');
                }
                else{                    
                    $amount = input_num('quantity') * input_num('rate');
                }    
                break;
            case PILT_FINAL_TOTAL:
                $amount = input_num('amount');
                break;
            case PILT_DETAIL:
            default:
                if($_POST["unit"] == '' || $_POST["unit"] == '0'){
                    $amount = input_num('amount');
                }
                else{                    
                    $amount = input_num('quantity') * input_num('rate');
                }    
                break;            
        }  
    
    $write_msg = write_subcontractor_invoice_detail($sci_no, $selected_id, $_POST['line_type'], $_POST['item_type'], 0,
                                        input_num('sequence'), $_POST['item_id'], $_POST['description'], _get_completed_date(), $_POST['unit'], 
                                        input_num('quantity'), input_num('rate'), $amount, $_POST['line_comment'],
                                        $_POST['task_id'], $_POST['category_id'], $_POST['debit_account'], $_POST['credit_account']);
    
    return $write_msg;
    
}

function save_subcontractor_invoice(&$sci_no, $selected_id)
{
    $approval_status = 0;
    
    $new = true;
    if($sci_no > 0){
        $new = false;
    }
    
    begin_transaction();
    
    if($sci_no>0){
        $sub_inv_h = get_subcontractor_invoice_header_record($sci_no);
        if(is_array($sub_inv_h)){
            $approval_status = $sub_inv_h['approval_status'];
        }
    }
    
    if(in_array($approval_status, array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR))){
        $msg = save_subcontractor_invoice_header($sci_no);
        if($msg["success"] !== true){
            if($new){
                $sci_no = -1; 
            }  
            cancel_transaction();
            return $msg;
        }
    }

    $msg = save_subcontractor_invoice_detail($sci_no, $selected_id);
    if($msg["success"] !== true){
        if($new){
            $sci_no = -1; 
        }
        cancel_transaction();
        return $msg;
    }

    commit_transaction();
    
    return array("success" => true, 'trans_no' => $sci_no, "message" => $msg["message"]);

}

function display_subcontractor_invoice_header($sci_no)
{
    global $approval_statuses, $Refs;
    
    $msci_header =  array();
    
    if($sci_no>0){
        $msci_header = get_subcontractor_invoice_header($sci_no);
        $_POST['project_id'] = $msci_header['project_id'];
        $_POST['supplier_id'] = $msci_header['supplier_id'];
        
        $project_id = $msci_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(!in_array($msci_header['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))){
            if(!$_SESSION["wa_current_user"]->can_access('SA_EDIT_APPROVED_PROJECT_INVOICES')){
                display_error("This is an approved transaction. You do not have permission to edit it.");
                set_focus('project_id');
                display_footer_exit();
                exit;
            }
        }

        if(!isset($_POST['reference'])){
            $_POST['reference'] = $msci_header['reference'];
        }
        if(!isset($_POST['payment_terms'])){
            $_POST['payment_terms'] = $msci_header['payment_terms'];
        }
        if(!isset($_POST['ord_date'])){
            $_POST['ord_date'] = sql2date($msci_header['ord_date']);
        }
        if(!isset($_POST['total'])){
            $_POST['total'] = $msci_header['total'];
        }
        if(!isset($_POST['taxes'])){
            $_POST['taxes'] = $msci_header['taxes'];
        }
        if(!isset($_POST['payment_application_ref'])){
            $_POST['payment_application_ref'] = $msci_header['payment_application_ref'];
        }
        if(!isset($_POST['payment_application_amount'])){
            $_POST['payment_application_amount'] = $msci_header['payment_application_amount'];
        }
        if(!isset($_POST['payment_certificate_ref'])){
            $_POST['payment_certificate_ref'] = $msci_header['payment_certificate_ref'];
        }
        if(!isset($_POST['payment_certificate_amount'])){
            $_POST['payment_certificate_amount'] = $msci_header['payment_certificate_amount'];
        }
        if(!isset($_POST['tax_group_id'])){
            $_POST['tax_group_id'] = $msci_header['tax_group_id'];
        }
        if(!isset($_POST['supp_inv_ref'])){
            $_POST['supp_inv_ref'] = $msci_header['supp_inv_ref'];
        }
        if(!isset($_POST['project_description'])){
            $_POST['project_description'] = $msci_header['project_description'];
        }
        
        $_POST['approval_status'] = $msci_header['approval_status'];
        $_POST['po_no'] = $msci_header['po_no'];
        $_POST['supp_name'] = $msci_header['supp_name'];
    }
    else{
        $_POST['reference'] = $Refs->get_next(ST_SUBCONTRACTOR_INVOICE);
        $_POST['approval_status'] = 0;
        $_POST['po_no'] = 0;
        $_POST['supp_name'] = '';
    }
        
    start_outer_table(TABLESTYLE2, "width=80%"); // outer table
//    start_table(TABLESTYLE2);  
        table_section(1, "35%");
            text_row("Reference:", 'reference', null, null, null);      
            
            if($_POST['po_no'] > 0){
                label_row("Supplier:", $_POST['supp_name']);
                hidden('supplier_id', $_POST['supplier_id']);
            }
            else{
                supplier_list_row("Supplier:", 'supplier_id', null, "Select a Supplier");
            }
            
            if($_POST['po_no'] > 0){
                $s = get_project_trans_view_str(ST_SUBCONTRACTOR_PURCH_ORDER, $_POST['po_no']);
                label_row("PO No:", $s);
            }
            else{
                label_row("PO No:", "(Manual Invoice)");
            }
            
            date_row("Order Date:", 'ord_date');
            start_row();
            sale_payment_list_cells("Payment Terms:", 'payment_terms', null, null);  
            end_row();    
            
            if(can_change_subcontractor_invoice_project($sci_no)){
                project_list_row(_("Project:"), 'project_id', null, _('Select a project'), true); 
//                $project = get_project($_POST['project_id']);
            }
            else{
                label_row("Project :",$_POST['project_description']);
                hidden('project_id', $_POST['project_id']);
            }

            text_row("Supp. Inv. Ref :", 'supp_inv_ref', null, null, null); 
        
        table_section(2, "35%");
            
            text_row("Payment Application Reference:", 'payment_application_ref', null, null, null); 
            amount_row("Payment Application Amount:", 'payment_application_amount'); 
            
            text_row("Payment Certificate Reference:", 'payment_certificate_ref', null, null, null); 
            amount_row("Payment Certificate Amount:", 'payment_certificate_amount');   
            
            global $approval_statuses;
            $s = get_project_trans_view_str(ST_APPROVAL_LOG, $sci_no."&source_type_id=".ST_SUBCONTRACTOR_INVOICE, "Approval Status");
            label_row($s,$approval_statuses[$_POST['approval_status']]);
            
        table_section(3, "35%");
            table_section_title("Supplier Payable (Accounts Payable) Values");
            amount_row("Total Amount (without taxes):", 'total');   

//            label_row("Price Include Taxes:", get_yes_no_name($project['rate_include_taxes']));
//            hidden('rate_include_taxes', $project['rate_include_taxes']);
            
            if(!(isset($_POST['tax_group_id']) && $_POST['tax_group_id'] > 0)){
                $supplier = get_supplier($_POST['supplier_id']);
                $_POST['tax_group_id'] = $supplier['tax_group_id'];
            }
            
            tax_groups_list_row("Tax Group:", 'tax_group_id', null, "Select a Tax Group", true);
            
            
            $taxes_total = display_selected_tax_types($sci_no, get_post('tax_group_id'));   
            
            $inv_total = input_num('total') + $taxes_total;
            label_row(text_bold("Total"), text_bold(number_format($inv_total, 2)));


//    end_table(1);

    end_outer_table(1); // outer table
    hidden('SCI_No', $sci_no);
    
    

//    start_table(TABLESTYLE2);  
//    table_section_title("Supplier Payable (Accounts Payable) Values");
//            amount_row("Total Amount (without taxes):", 'total');   
//
////            label_row("Price Include Taxes:", get_yes_no_name($project['rate_include_taxes']));
////            hidden('rate_include_taxes', $project['rate_include_taxes']);
//            
//            if(!(isset($_POST['tax_group_id']) && $_POST['tax_group_id'] > 0)){
//                $supplier = get_supplier($_POST['supplier_id']);
//                $_POST['tax_group_id'] = $supplier['tax_group_id'];
//            }
//            
//            tax_groups_list_row("Tax Group:", 'tax_group_id', null, "Select a Tax Group", true);
//            
//            
//            display_selected_tax_types($sci_no, get_post('tax_group_id'));          
//    end_table(1);
    
    if($sci_no>0){
        $approval_status = $msci_header['approval_status'];
        if(!in_array($approval_status, array(AS_NEW, AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER, AS_BACK_TO_ORIGINATOR))){
            br(2);
            $m = "This is details editing mode only. Header details will not be updated.";
            display_note("<font color='red'>".text_bold($m)."</font>");
            br(2);
        }
    }
    
    return $msci_header;

}

function display_selected_tax_types($sci_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_subcontractor_invoice_tax_type_amount($sci_no, $tax_type['tax_type_id']);
            $_POST[$tax_type['tax_type_id'].'_msci_tax'] = $tax_amount;
            amount_row($tax_type['tax_type_name'], $tax_type['tax_type_id'].'_msci_tax');   
            
            if ($tax_type['suspended'] == 0) {
                $taxes_total += $tax_amount;
            }
        }
    }
    
    return $taxes_total;
}

function display_subcontractor_invoice_details($sci_no)
{  
    global $project_invoice_line_types;    
          
    $result = get_subcontractor_invoice_details($sci_no);  
    
                              
    start_table(TABLESTYLE, "width=98%");
    $th = array(_('Seq.'),_('Details'), _('Date'),
                _('Unit'), _('PO Qty'), _('Inved Qty'),_('Quantity'),_('Rate'), _('Amount'), _('Category'), "", "");              

    table_header($th);
    $k = 0; //row colour counter
   // $total = 0;
    
    while ($myrow = db_fetch($result))
    {
        alt_table_row_color($k);


        label_cell($myrow["sequence"], "align=right");
        
//***********************************
//           Details
//***********************************        
        switch ($myrow['line_type']) {
            case PILT_MAIN_HEADER:
            case PILT_MAIN_SUMMARY:
                label_cell("<b>".$myrow["description"]."</b>");
                break;
            case PILT_MAIN_ITEM:
                if($myrow["item_id"] > 0){
                    label_cell(spaces(10).$myrow["boq_item_code"]." - ".$myrow["description"]);
                }
                else{
                    label_cell(spaces(10).$myrow["description"]);
                }
                break;
            case PILT_SUB_HEADER:
            case PILT_SUB_SUMMARY:
                label_cell(spaces(10)."<b>".$myrow["description"]."</b>");
                break;
            case PILT_SUB_ITEM:
                if($myrow["item_id"] > 0){
                    label_cell(spaces(20).$myrow["boq_item_code"]." - ".$myrow["description"]);
                }
                else{
                    label_cell(spaces(20).$myrow["description"]);
                }
                break;
            case PILT_DETAIL:
            default:
                if($myrow["item_id"] > 0){
                    label_cell(spaces(30).$myrow["boq_item_code"]." - ".$myrow["description"]);
                }
                else{
                    label_cell(spaces(30).$myrow["description"]);
                }
                break;
            case PILT_FINAL_TOTAL:
                label_cell("<b>".$myrow["description"]."</b>");
                break;
        }

//***********************************
//           Unit, 
//           Quantity, 
//           Rate, 
//           Amount
//***********************************
        
        switch ($myrow['line_type']) {
            case PILT_MAIN_HEADER:
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                break;
            case PILT_MAIN_SUMMARY:
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                amount_cell($myrow["amount"], true);
                break;
            case PILT_MAIN_ITEM:
                if(is_date(sql2date($myrow["completed_date"]))){
                    label_cell(sql2date($myrow["completed_date"]), "align=center");
                }
                else{
                    label_cell('');
                }
                label_cell($myrow["unit_name"]);
                if($myrow["unit"] == '' || $myrow["unit"] == '0'){
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                }
                else{ 
                    label_cell(number_format($myrow["po_line_qty"],3), "align=right");
                    label_cell(number_format($myrow["invoiced_qty"],3), "align=right");
                    label_cell(number_format($myrow["quantity"],3), "align=right");
                    label_cell(number_format($myrow["rate"],2), "align=right");
                }
                label_cell($myrow["amount"]. spaces(10), "align=right");
                break;
            case PILT_SUB_HEADER:
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                break;
            case PILT_SUB_SUMMARY:
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("<b>".$myrow["amount"]."</b>". spaces(10), "align=right");
                break;
            case PILT_SUB_ITEM:
                if(is_date(sql2date($myrow["completed_date"]))){
                    label_cell(sql2date($myrow["completed_date"]), "align=center");
                }
                else{
                    label_cell('');
                }
                label_cell($myrow["unit_name"]);
                label_cell(number_format($myrow["po_line_qty"],3), "align=right");
                label_cell(number_format($myrow["invoiced_qty"],3), "align=right");
                label_cell(number_format($myrow["quantity"],3), "align=right");
                label_cell(number_format($myrow["rate"],2), "align=right");
                label_cell($myrow["amount"]. spaces(10), "align=right");
                break;
            case PILT_DETAIL:
            default:
                if(is_date(sql2date($myrow["completed_date"]))){
                    label_cell(sql2date($myrow["completed_date"]), "align=center");
                }
                else{
                    label_cell('');
                }
                label_cell($myrow["unit_name"]);
                if($myrow["unit"] == '' || $myrow["unit"] == '0'){
                    label_cell("");
                    label_cell("");
                    label_cell("");
                    label_cell("");
                }
                else{ 
                    label_cell(number_format($myrow["po_line_qty"],3), "align=right");
                    label_cell(number_format($myrow["invoiced_qty"],3), "align=right");
                    label_cell(number_format($myrow["quantity"],3), "align=right");
                    label_cell(number_format($myrow["rate"],2), "align=right");
                }
                label_cell($myrow["amount"]. spaces(10), "align=right");
                break;
            case PILT_FINAL_TOTAL:
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                label_cell("");
                amount_cell($myrow["amount"], true);
                break;
        }  

        label_cell($myrow["category_name"]);
//        label_cell($myrow["task_description"]);
//        
//        if(strlen($myrow["debit_account"]) > 0){
//            label_cell($myrow["debit_account"]." - ".$myrow["debit_account_name"]);
//        }
//        else{
//            label_cell('');
//        }
//        
//        if(strlen($myrow["credit_account"]) > 0){
//            label_cell($myrow["credit_account"]." - ".$myrow["credit_account_name"]);    
//        }
//        else{
//            label_cell('');
//        }
        
        edit_button_cell("Edit".$myrow["id"], _("Edit"));    
        delete_button_cell("Delete".$myrow["id"], _("Delete"));  
        
        
        if($myrow['task_id'] > 0){
            $details = "<b>Budget:</b> ".$myrow["task_code"]." - ".$myrow["task_description"];
        }
        else{
            if(strlen($myrow["debit_account"]) > 0 || strlen($myrow["credit_account"]) > 0){
                $details = "<b>Debit A/C:</b> ".$myrow["debit_account"]." - ".$myrow["debit_account_name"];
                $details .= spaces(5)."<b>Credit A/C:</b> ".$myrow["credit_account"]." - ".$myrow["credit_account_name"];
            }
            else{
                $details = "";
            }
        }
        
        if(strlen($details) > 0){
            alt_table_row_color($k);
            label_cell('');
            label_cell($details, "colspan=8 align=right");
            label_cell('');
            label_cell('');
            label_cell('');
            end_row();
        }
        
//        label_cell("[".$subcontractor_invoice_line_types[$myrow['line_type']]."]"); 
        
        end_row();  
        
        if(strlen($myrow["line_comment"]) > 0){
            alt_table_row_color($k);
            label_cell('');
            label_cell("<b>Comment:</b> ".$myrow["line_comment"], 'colspan=6 align=right');
            label_cell('');
            label_cell('');
            label_cell('');
            end_row();
        }
      
    }       
      
    }

function display_subcontractor_invoice_edit_controls($selected_id, &$Mode)
{
    global $project_invoice_line_types;
    
    if(isset($_POST["Edit".$selected_id])){
        $refersh_line = true;
    }
    else{
        $refersh_line =  false;
    }
    
    if ($selected_id > 0){
        $myrow = get_subcontractor_invoice_line($selected_id); 
        if($myrow['line_type'] == SCIIT_PO_LINE){
            $_POST['line_type'] = $myrow['line_type'];
        }
        if($refersh_line){     
            $_POST['line_type'] = $myrow['line_type'];
            $_POST['unit'] = $myrow["unit"];    
            $_POST['sequence'] = $myrow["sequence"];
            $_POST['description'] = $myrow["description"];    
            $_POST['unit'] = $myrow["unit"];  
            $_POST['quantity'] = $myrow["quantity"]; 
            $_POST['rate'] = $myrow["rate"]; 
            $_POST['amount'] = $myrow["amount"]; 
            if(!is_date(sql2date($myrow["completed_date"]))){
                $_POST['completed_date'] = Today();
            }
            else{
                $_POST['completed_date'] = sql2date($myrow["completed_date"]); 
            }
            $_POST['line_comment'] = $myrow["line_comment"]; 
            $_POST['category_id'] = $myrow["category_id"];
            $_POST['debit_account'] = $myrow["debit_account"];
            $_POST['credit_account'] = $myrow["credit_account"];

            if($refersh_line){
                $_POST['task_id'] = $myrow["task_id"];
                $_POST['item_id'] = $myrow["item_id"];
                $_POST['item_type'] = $myrow["item_type"];
            }

            if(!isset($_POST['task_id'])){
                $_POST['task_id'] = $myrow["task_id"];
            }
            if(!isset($_POST['item_id'])){
                $_POST['item_id'] = $myrow["item_id"];
            }
            if(!isset($_POST['item_type'])){
                $_POST['item_type'] = $myrow["item_type"];
            }
        }
    }
    else{
        if(!isset($_POST['task_id'])){
            $_POST['task_id'] = 0;
        }
        if(!isset($_POST['item_id'])){
            $_POST['item_id'] = 0;
        }
        if(!isset($_POST['item_type'])){
            $_POST['item_type'] = 0;
        }
    }

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

    div_start('billing_items');
    start_outer_table(TABLESTYLE2);
    
    table_section(1);
    
    qty_row("Display Sequence:", 'sequence', null, null, null, 0);   

    if(list_updated('boq_group_id')){
        $_POST['task_id'] = 0;
    }
    
    if ($selected_id > 0){
        if($myrow['po_line_id'] > 0){
            label_row("Line Type:", $project_invoice_line_types[$_POST['line_type']]);
            hidden('line_type', $_POST['line_type']);
        }else{
            label_row("Line Type:", $project_invoice_line_types[$_POST['line_type']]);
            hidden('line_type', $_POST['line_type']);
        }
    }else{
        project_invoice_line_types_list_row("Line Type:", 'line_type',null,null,true);    
    }
    
    switch ($_POST['line_type']) {
        case PILT_MAIN_HEADER:
        case PILT_SUB_HEADER:
            hidden('task_id', 0);
            hidden('boq_group_id', 0);
            text_row("Details:", 'description', null, 50, 500);
            hidden('completed_date', Today());
            hidden('unit', '');
            hidden('quantity', 0.000);
            hidden('rate', 0.00);
            hidden('item_id', 0);
            hidden('amount', 0.000); 
            hidden('item_type', 0);
            break;
        
        case PILT_MAIN_SUMMARY:       
        case PILT_SUB_SUMMARY:
        case PILT_FINAL_TOTAL:
            project_boq_item_groups_list_row("BOQ Group :", "boq_group_id", $_POST['project_id'], $_POST['boq_group_id'], "No BOQ Item Group", true);        
            if($selected_id > 0 && (!isset($_POST['item_id']))){         
                $scid = get_subcontractor_invoice_line($selected_id);            
                $_POST['item_id'] = $scid['item_id'];         
            }else{   
                if(!isset($_POST['item_id'])){
                    $_POST['item_id'] = 0; 
                }            
            }  
            
            group_tasks_list_row("Budget :", 'task_id', $_POST['project_id'], $_POST['boq_group_id'], null, _('Select a budget'));  
            
            text_row("Details:", 'description', null, 50, 500);
            hidden('completed_date', Today());
            hidden('unit', '');
            hidden('quantity', 0.000);
            hidden('rate', 0.00);
            hidden('item_id', 0);
            hidden('item_type', 0);
            amount_row("Amount:", 'amount', null, null, null, 2); 
            break;
            
        default:      
//            yesno_list_row("Item Type:", "item_type", null, "BOQ Item", "Description", true);
            global $subconractor_invoice_item_types;
            
            if($_POST['item_type'] == SCIIT_PO_LINE){
                label_row("Item Type:", $subconractor_invoice_item_types[SCIIT_PO_LINE]);
                hidden("item_type", $_POST['item_type']);
            }
            else{
                subcontractor_invoice_item_types_list_row("Item Type:", 'item_type', null, false, true);
            }
 
            switch ($_POST['item_type']) {
                case SCIIT_BOQ_ITEM:            
                    if($selected_id > 0 && (!isset($_POST['item_id']))){         
                        $scid = get_subcontractor_invoice_line($selected_id);            
                        $_POST['item_id'] = $scid['item_id']; 
                        $boq_item = get_project_boq_item_record($scid['item_id']);
                        $_POST['item_boq_group_id'] = $boq_item['group_id'];
                    }else{   
                        if(!isset($_POST['item_id'])){
                            $_POST['item_boq_group_id'] = 0;
                            $_POST['item_id'] = 0; 
                        }       
                        else{
                            $boq_item = get_project_boq_item_record($_POST['item_id']);
                            $_POST['item_boq_group_id'] = $boq_item['group_id'];
                        }
                    } 
            
                    project_boq_item_groups_list_row("BOQ Group (BOQ Item):", "item_boq_group_id", $_POST['project_id'], $_POST['item_boq_group_id'], "No BOQ Item Group", true);


                    group_boq_items_list_row("BOQ Item :", "item_id", $_POST['project_id'], $_POST['item_boq_group_id'], $_POST['item_id'], false, true);
                    $boq_item = get_project_boq_item_details($_POST['item_id']);

                    label_row("Units:", $boq_item['unit_name']);
                    hidden("unit", $boq_item['unit']);

                    if(list_updated('item_id')){
                        $_POST['rate'] = $boq_item['rate'];
                    }

                    hidden("description", $boq_item['description']);
                    break;
                    
                case SCIIT_PO_LINE:            
                    $scid = get_subcontractor_invoice_line($selected_id);  
                    if(isset($scid['po_line_id']) && $scid['po_line_id'] > 0){ 
                        if(isset($scid['item_id']) && $scid['item_id'] > 0){ 
                            $_POST['item_id'] = $scid['item_id']; 
                            $boq_item = get_project_boq_item_record($scid['item_id']);
                            $_POST['item_boq_group_id'] = $boq_item['group_id'];         
                            $boq_item_name = $boq_item["code"]." - ".$boq_item["description"];
                                    
                            $boq_item_group = get_project_boq_item_group_record($_POST['item_boq_group_id']);
                            $boq_item_group_name = $boq_item_group["code"]." - ".$boq_item_group["description"];  
                            
                            label_row("BOQ Group (BOQ Item):", $boq_item_group_name);
                            label_row("BOQ Item :", $boq_item_name);
                            
                            hidden("item_id", $scid['item_id']);
                            hidden("description", '');
                        }else{   
                            $_POST['item_boq_group_id'] = 0;
                            $_POST['item_id'] = 0;    

                            hidden("item_id", 0);
                            
                            label_row("Description:", $scid['description']);
                            hidden("description", $scid['description']);
                        } 

                        
                        label_row("Units:", $scid['unit_name']);
                        hidden("unit", $scid['unit']);
                        hidden("po_line_id", $scid['po_line_id']);
                        
                        $sc_po_line = get_sc_purchase_orders_line($scid['po_line_id']);
                        label_row("PO Quantity:", number_format($sc_po_line['quantity'],3));
                        label_row("Invoiced Quantity:", number_format($sc_po_line['invoiced_qty'], 3));
                    }
                    else{
                        // Exit if PO Line is manually selected
                        hidden('quantity', 0.000);
                        hidden('rate', 0.00);
                        hidden('amount', 0.00);
                        hidden('completed_date', Today());
                        hidden("po_line_id", 0);

                        end_outer_table(1);
                        div_end();
                        return;
                    }
            
                    $_POST['rate'] = $scid['rate'];
                    
                    break;
                default :
                    text_row("Description:", 'description', null, 50, 500);
                    hidden('item_id', 0);
                    stock_units_list_row(_("Units:"), 'unit', null, true, '', true);
                    break;
            }
            
            
            

            if($_POST['unit'] == ''){
                hidden('quantity', 0.000);
                hidden('rate', 0.00);
                amount_row("Amount:", 'amount', null, null, null, 2);    
            }
            else{
                amount_row("Quantity:", 'quantity', null, null, null, 3);   
                if($_POST['item_type'] == SCIIT_PO_LINE){
                    $sc_pod = get_sc_purchase_order_line_record($myrow['po_line_id']); 
                    $_POST['rate'] = $sc_pod['rate'];
                    label_row("Rate:", number_format(is_numeric($sc_pod['rate'])?$sc_pod['rate']:0, 2));
                    hidden('rate', $_POST['rate']);
                }
                else{
                    amount_row("Rate:", 'rate', null, null, null, 2); 
                }

                $amount = input_num('quantity') * input_num('rate');
                hidden('amount', $amount);
            }
            
            date_row("Date", 'completed_date');  
            
            break;
    }
    
    
    table_section(2);
      
    if($refersh_line){
        if($_POST['task_id'] > 0){
            $task = get_task_record($_POST['task_id']);
            if(isset($task['task_group_id']) && $task['task_group_id'] > 0){
                $task_group = get_task_group_details($task['task_group_id']);
                $_POST['task_boq_group_id'] = $task_group['boq_group_id'];
            }    
        }  
    }
    else{
        if(!isset($_POST['task_boq_group_id'])){
            $_POST['task_boq_group_id'] = 0;
        }
    }
    
    value_list_row("Line Category", 'category_id', "PROJ_INV_LINE_CATEGORIES", null, "Select a line category");  
    
    project_boq_item_groups_list_row("BOQ Group (Budget):", "task_boq_group_id", $_POST['project_id'], $_POST['task_boq_group_id'], "No BOQ Item Group", true);        
            if($selected_id > 0 && (!isset($_POST['item_id']))){         
                $scid = get_subcontractor_invoice_line($selected_id);            
                $_POST['item_id'] = $scid['item_id'];         
            }else{   
                if(!isset($_POST['item_id'])){
                    $_POST['item_id'] = 0; 
                }            
            } 
    
    group_tasks_list_row("Budget :", 'task_id', $_POST['project_id'], $_POST['task_boq_group_id'], null, _('Select a budget'));  
            
            
     

//    gl_all_accounts_list_row(_("Debit Account:"), 'debit_account', null, false, false, "");
//    gl_all_accounts_list_row(_("Creadit account:"), 'credit_account', null, false, false, "");
    
    $_POST['debit_account'] = '';
    hidden('debit_account', $_POST['debit_account']);
    $_POST['credit_account'] = '';
    hidden('credit_account', $_POST['credit_account']);

    textarea_row("Line Comment:", 'line_comment', null, 30, 4);

       
     

    end_outer_table(1);
    div_end();

}


function release_for_approval($sci_no)
{
    $cp_msg = can_process_sci_header($sci_no);
    if($cp_msg['success'] !== true){
        return $cp_msg;
    }
    
    $cq_msg = check_sc_po_invoiced_quantities($sci_no);
    if($cq_msg['success'] !== true){
        return $cq_msg;
    }

    begin_transaction();
    
    $msg = save_subcontractor_invoice_header($sci_no);
    if($msg['success'] !== true){
        cancel_transaction();
        return $msg;
    }    
    
    $cp_msg = can_release_subcontractor_invoice($sci_no);
    if($cp_msg['success'] !== true){
        cancel_transaction();
        return $cp_msg;
    }
    
    $msg = release_subcontractor_invoice($sci_no);
    if($msg['success'] !== true){
        cancel_transaction();
        return $msg;
    }
    

    
    commit_transaction();
    
    return array("success" => true, "message" => $msg['message']);
            
        
}

function send_sci_back_to_originator($sci_no)
{
   $msg = can_process_sci_header($sci_no);
    if($msg['success'] !== true){
        return $msg;
    }
    
    begin_transaction();
    $scih = get_subcontractor_invoice_header($sci_no);

    $sci_total = $scih['total'] + $scih['taxes'];    
    
    $current_user_id = $_SESSION['wa_current_user']->user;

    $sbdo_msg = send_back_to_document_originator(ST_SUBCONTRACTOR_INVOICE, $sci_no, $scih['project_id'],
                                    $scih['next_approval_group_id'], $current_user_id, $scih['row_state'], 
                                    $scih['created_by']);
    
    if($sbdo_msg['success'] !== true){
        cancel_transaction();
        return $sbdo_msg;
    }
    else{
        commit_transaction();
        return $sbdo_msg;
    }
}

function reject_sci($sci_no)
{
    $msg = can_process_sci_header($sci_no);
    if($msg['success'] !== true){
        return $msg;
    }

    begin_transaction();
    $scih = get_subcontractor_invoice_header($sci_no);

    $sci_total = $scih['total'] + $scih['taxes'];
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document(ST_SUBCONTRACTOR_INVOICE, $sci_no, $scih['project_id'],
                    $scih['next_approval_group_id'], $current_user_id, $scih['row_state']);
    
    if($rj_msg['success'] !== true){
        cancel_transaction();
        return $rj_msg;
    }
    else{
        commit_transaction();
        return $rj_msg;
    }

}

function can_process_sci_header($sci_no)
{    
    global $Refs;
    
    if($sci_no > 0){
        $sci = get_subcontractor_invoice_header_record($sci_no);
        if(!$_SESSION["wa_current_user"]->can_access('SA_EDIT_APPROVED_PROJECT_INVOICES')){  
            if(!($sci['approval_status'] == AS_NEW || $sci['approval_status'] == AS_WITH_THE_APPROVER || $sci['approval_status'] == AS_AWAITING_APPROVAL)){
                $message = ("This Subcontrctor Invoice status does not allow further updating.");
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
        }
        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document(ST_SUBCONTRACTOR_INVOICE, $sci['project_id'], $sci['next_approval_group_id'] , $current_user_id, $sci['created_by'], $sci_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_INVOICE, $sci_no);
    if($ref_msg){
        commit_transaction();
        $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 (!($_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);        
    }
    
    if (!is_date_in_fiscalyear($_POST['ord_date'])) 
    {
        $message = (_("The entered date is not in fiscal year.")); 
        $set_focus = 'ord_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    } 
    
    $msg = is_accounting_period_open($_POST['ord_date']);
    if ($msg['success'] !== true)
    {
        $message = ($msg['message']); 
        $set_focus = 'ord_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }
      
    
    if(!check_num('total',0))
    {
        $message = "Total amount has to be numeric and can not be negative.";
        $set_focus = 'total';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
      
    $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'])){
            if(!check_num($tax_type['tax_type_id'].'_msci_tax',0))
            {
                $message = "Tax type ".$tax_type['tax_type_name'].": Amount has to be numeric and can not be negative.";
                $set_focus = $tax_type['tax_type_id'].'_msci_tax';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
            }
        }
    }
    
    return array("success" => true, "message" => "");    
}
