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

function write_subcontractor_invoice($pi_no, $project_id, $debtor_no, $customer_branch, $reference,
                                    $payment_terms, $order_date, $sales_person,
                                    $total, $taxes, $rate_include_taxes, 
                                    $payment_application_id, $payment_certificate_ref, $payment_certificate_amount,
                                    $due_date, $comments, $tax_group_id, $pi_taxes, $project_sales_order_id)
{

    $pi_no = write_subcontractor_invoice_header($pi_no, $project_id, $debtor_no, $customer_branch, $reference,
                                                $payment_terms, $order_date, $sales_person,
                                                $total, $taxes, $rate_include_taxes, 
                                                $payment_application_id, $payment_certificate_ref, $payment_certificate_amount,
                                                $due_date, $comments, $tax_group_id, $pi_taxes, $project_sales_order_id);
        
    return $pi_no;
}

function write_subcontractor_invoice_header($pi_no, $project_id, $supplier_id, $reference, $supp_inv_ref,
                                                $payment_terms, $order_date, 
                                                $total, $taxes,  
                                                $payment_application_ref, $payment_application_amount,
                                                $payment_certificate_ref, $payment_certificate_amount,
                                                $due_date, $comments, $tax_group_id, $pi_taxes, $po_no, $staxes)
{     
    begin_transaction();
    
    if($pi_no > 0){        
        update_subcontractor_invoice_header($pi_no, $project_id, $supplier_id, $reference, $supp_inv_ref,
                                                $payment_terms, $order_date, 
                                                $total, $taxes,  
                                                $payment_application_ref, $payment_application_amount,
                                                $payment_certificate_ref, $payment_certificate_amount,
                                                $due_date, $comments, $tax_group_id, $staxes);
    }else{
        global $Refs;
        $pi_no = add_subcontractor_invoice_header($project_id, $supplier_id, $reference, $supp_inv_ref,
                                                   $payment_terms, $order_date, 
                                                    $total, $taxes,  
                                                    $payment_application_ref, $payment_application_amount,
                                                    $payment_certificate_ref, $payment_certificate_amount,
                                                    $due_date, $comments, $tax_group_id, $po_no, $staxes);
        
        $Refs->save(ST_SUBCONTRACTOR_INVOICE, $pi_no, $reference);
        
    }
    
    update_subcontractor_invoice_tax_details($pi_no, $pi_taxes);
    
    commit_transaction();
    
    return $pi_no;
}


function write_subcontractor_invoice_detail($pi_no, $pi_detail_row_id, $line_type, $item_type, $po_line_id, 
                                                $sequence, $item_id, $text, $completed_date, $unit, 
                                                $quantity, $rate, $amount, $line_comment,
                                                $task_id, $category_id, $debit_account, $credit_account)
{     
    global $systypes_array;
                        
    if($pi_detail_row_id > 0){         
        update_subcontractor_invoice_details($pi_detail_row_id, $line_type, $item_type,
                                                $sequence, $item_id, $text, $completed_date, $unit, 
                                                $quantity, $rate, $amount, $line_comment,
                                                $task_id, $category_id, $debit_account, $credit_account);  
        return array("success" => true, "message" => "Selected detail line has been updated.");
    }else{

        $pi_detail_row_id = add_subcontractor_invoice_details($pi_no, $line_type, $item_type, $po_line_id,
                                                                $sequence, $item_id, $text, $completed_date, $unit, 
                                                                $quantity, $rate, $amount, $line_comment,
                                                                $task_id, $category_id, $debit_account, $credit_account);
        
        return array("success" => true, "message" => "New detail line has been added to ".$systypes_array[ST_SUBCONTRACTOR_INVOICE]." #".$pi_no);
    }
          
}

function update_subcontractor_invoice_tax_details($pi_no, $pi_taxes)
{   
    delete_subcontractor_invoice_tax_details($pi_no);
    foreach ($pi_taxes as $tax_detail) {
        add_subcontractor_invoice_tax_detail($pi_no, $tax_detail['tax_type_id'], $tax_detail['tax_amount']);
    }
}


function delete_subcontractor_invoice_tax_details($pi_no)
{     
     $sql = "DELETE FROM ".TB_PREF."subcontractor_invoice_taxes  
             WHERE order_no = ".db_escape($pi_no);     
     
    db_query($sql, "Could not delete_subcontractor_invoice_tax_details.");
 
}


function add_subcontractor_invoice_tax_detail($pi_no, $tax_id, $tax_value)
{     
     $sql = "INSERT INTO ".TB_PREF."subcontractor_invoice_taxes 
                   (order_no, tax_type_id, amount)
             VALUES ("
                    .db_escape($pi_no).","
                    .db_escape($tax_id).","
                    .db_escape($tax_value).")";              
     
    db_query($sql, "Could not add_subcontractor_invoice_tax_detail.");
 
}

function update_subcontractor_invoice_header($pi_no, $project_id, $supplier_id, $reference, $supp_inv_ref,
                                                $payment_terms, $order_date, 
                                                $total, $taxes,  
                                                $payment_application_ref, $payment_application_amount,
                                                $payment_certificate_ref, $payment_certificate_amount,
                                                $due_date, $comments, $tax_group_id, $staxes)
{
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
    $sql = "UPDATE ".TB_PREF."subcontractor_invoices
            SET 
                project_id=".db_escape($project_id).",
                supplier_id=".db_escape($supplier_id).",
                reference=".db_escape($reference).",
                supp_inv_ref=".db_escape($supp_inv_ref).",
                payment_terms=".db_escape($payment_terms).",    
                ord_date=".db_escape(date2sql($order_date)).",    
                tax_group_id=".db_escape($tax_group_id).", 
                total=".db_escape($total).", 
                taxes =".db_escape($taxes).",  
                staxes =".db_escape($staxes).",  
                payment_application_ref=".db_escape($payment_application_ref).", 
                payment_application_amount =".db_escape($payment_application_amount).",
                payment_certificate_ref=".db_escape($payment_certificate_ref).", 
                payment_certificate_amount =".db_escape($payment_certificate_amount).",
                comments =".db_escape($comments).",    
                due_date =".db_escape(date2sql($due_date)).", 
                updated_by=".db_escape($updated_by).",
                updated_on=".db_escape($updated_on)."                  
            WHERE order_no=".db_escape($pi_no);
    
    db_query($sql);
    return db_num_affected_rows();  
    
}

function add_subcontractor_invoice_header($project_id, $supplier_id, $reference, $supp_inv_ref,
                                            $payment_terms, $order_date, 
                                            $total, $taxes,  
                                            $payment_application_ref, $payment_application_amount,
                                            $payment_certificate_ref, $payment_certificate_amount,
                                            $due_date, $comments, $tax_group_id, $po_no, $staxes)
{
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
    $next_no = get_next_trans_no(ST_SUBCONTRACTOR_INVOICE);
    
    $sql = "INSERT INTO ".TB_PREF."subcontractor_invoices
                    (order_no, project_id, 
                    supplier_id, po_no,
                    reference, supp_inv_ref,
                    payment_terms, ord_date, 
                    tax_group_id, total, taxes, 
                    payment_application_ref, payment_application_amount,
                    payment_certificate_ref, payment_certificate_amount,
                    due_date, comments, staxes, 
                    created_by, created_on )         
                VALUES 
                (".db_escape($next_no).", ".db_escape($project_id).", 
                    ".db_escape($supplier_id).", ".db_escape($po_no).", 
                    ".db_escape($reference).", ".db_escape($supp_inv_ref).",
                    ".db_escape($payment_terms).", ".db_escape(date2sql($order_date)).",
                    ".db_escape($tax_group_id).", ".db_escape($total).", ".db_escape($taxes).",     
                    ".db_escape($payment_application_ref).",".db_escape($payment_application_amount).",
                    ".db_escape($payment_certificate_ref).",".db_escape($payment_certificate_amount).",
                    ".db_escape(date2sql($due_date)).", ".db_escape($comments).", ".db_escape($staxes).",
                    ".db_escape($created_by).", ".db_escape($created_on).")";
     
    db_query($sql);
    return $next_no;        
}

function add_subcontractor_invoice_details($pi_no, $line_type, $item_type, $po_line_id,
                                            $sequence, $item_id, $text, $completed_date, $unit, 
                                            $quantity, $rate, $amount, $line_comment,
                                            $task_id, $category_id, $debit_account, $credit_account)
{
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
     $sql = "INSERT INTO ".TB_PREF."subcontractor_invoice_details (
                        order_no, line_type, 
                        item_type, po_line_id,
                        sequence, item_id, description, 
                        completed_date, unit, quantity, 
                        rate, amount, line_comment,
                        task_id, category_id, 
                        debit_account, credit_account,
                        created_by, created_on )                
            VALUES (".db_escape($pi_no).", ".db_escape($line_type).","
                        .db_escape($item_type).",".db_escape($po_line_id).","
                        .db_escape($sequence).", ".db_escape($item_id).",".db_escape($text).","
                        .db_escape($completed_date).",".db_escape($unit).", ".db_escape($quantity).","
                        .db_escape($rate).", ".db_escape($amount).",".db_escape($line_comment).","
                        .db_escape($task_id).", ".db_escape($category_id).", "
                        .db_escape($debit_account).",".db_escape($credit_account).","
                        .db_escape($created_by).", ".db_escape($created_on).")";
     
         
    db_query($sql);
    return db_insert_id();    
}

function update_subcontractor_invoice_details($pi_detail_row_id, $line_type, $item_type,
                                                $sequence, $item_id, $text, $completed_date, $unit, 
                                                $quantity, $rate, $amount, $line_comment,
                                                $task_id, $category_id, $debit_account, $credit_account)
{
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
     $sql = "UPDATE ".TB_PREF."subcontractor_invoice_details
                SET 
                    line_type=".db_escape($line_type).",
                    item_type=".db_escape($item_type).",
                    sequence=".db_escape($sequence).",
                    item_id=".db_escape($item_id).", 
                    description=".db_escape($text).", 
                    completed_date=".db_escape($completed_date).", 
                    unit=".db_escape($unit).",
                    quantity=".db_escape($quantity).",
                    rate=".db_escape($rate).",
                    amount=".db_escape($amount).",
                    line_comment=".db_escape($line_comment).",
                    category_id=".db_escape($category_id).",
                    task_id=".db_escape($task_id).",
                    debit_account=".db_escape($debit_account).",
                    credit_account=".db_escape($credit_account).",
                    updated_by=".db_escape($updated_by).",
                    updated_on=".db_escape($updated_on)."                  
                        
                WHERE id=".db_escape($pi_detail_row_id);
     
    db_query($sql);
    return db_num_affected_rows();  
    
}

function get_subcontractor_invoice_header($pi_no)
{
    $sql = "SELECT sci.*,
                    pm.description project_description,
                    sup.supp_name  
            FROM ".TB_PREF."subcontractor_invoices sci 
                JOIN ".TB_PREF."suppliers sup ON 
                    sci.supplier_id = sup.supplier_id 
                LEFT JOIN ".TB_PREF."projects_master pm ON 
                    sci.project_id = pm.project_id 
            WHERE order_no=".db_escape($pi_no);
    
    $result = db_query($sql);
    return db_fetch($result);   
    
}


function get_subcontractor_invoice_details($order_no)
{
    $sql = "SELECT pid.*, 
                    u.name unit_name,
                    cn.value_name category_name,
                    da.account_name debit_account_name,
                    ca.account_name credit_account_name,
                    pt.task_code, 
                    pt.description task_description, 
                    boqi.code boq_item_code,
                    scpod.quantity po_line_qty,
                    scpod.invoiced_qty 
            FROM ".TB_PREF."subcontractor_invoice_details pid 
                    LEFT JOIN ".TB_PREF."item_units u ON 
                            pid.unit = u.abbr 
                    LEFT JOIN ".TB_PREF."list_values cn ON 
                            pid.category_id = cn.id 
                    LEFT JOIN ".TB_PREF."chart_master da ON 
                            pid.debit_account = da.account_code  
                    LEFT JOIN ".TB_PREF."chart_master ca ON 
                            pid.credit_account = ca.account_code  
                    LEFT JOIN ".TB_PREF."project_tasks pt ON 
                            pid.task_id = pt.task_id  
                    LEFT JOIN ".TB_PREF."project_boq_items boqi ON 
                            pid.item_id = boqi.id  
                    LEFT JOIN ".TB_PREF."subcontractor_purchase_order_details scpod ON 
                            pid.po_line_id = scpod.id  
                    
            WHERE order_no=".db_escape($order_no)." 
            ORDER BY sequence";
    
    return db_query($sql, "Could not get manual project invoices");
    
}


function get_subcontractor_invoice_detail_records($order_no)
{
    $sql = "SELECT * 
            FROM ".TB_PREF."subcontractor_invoice_details  
                    
            WHERE order_no=".db_escape($order_no)." 
            ORDER BY sequence";
    
    return db_query($sql, "Could not get_subcontractor_invoice_detail_records");
    
}

function get_subcontractor_invoice_line($selected_id)
{
     $sql = "SELECT sid.*,
                    iu.name unit_name 
         
             FROM ".TB_PREF."subcontractor_invoice_details sid 
                 LEFT JOIN ".TB_PREF."item_units iu ON 
                     sid.unit = iu.abbr 
                      
             WHERE sid.id=".db_escape($selected_id);
     
     $result = db_query($sql);
     return db_fetch($result);
    
}

function delete_subcontractor_invoice_item($selected_id)
{
   $sql = "DELETE FROM ".TB_PREF."subcontractor_invoice_details WHERE id=".db_escape($selected_id);
   
   db_query($sql);
   return db_num_affected_rows();
    
}

function get_subcontractor_invoice_tax_type_amount($pi_no, $tax_type_id)
{
    $sql = "SELECT amount 
            FROM ".TB_PREF."subcontractor_invoice_taxes 
            WHERE order_no=".db_escape($pi_no)." AND 
                tax_type_id = ".db_escape($tax_type_id);
    
    $result = db_query($sql);
    $amt =  db_fetch($result);   
    $amount = 0;
    if(isset($amt['amount']) && $amt['amount'] > 0){
        $amount = $amt['amount'];
    }
    
    return $amount;
}


function get_subcontractor_invoice_header_record($sci_no)
{
    $sql = "SELECT sci.* 
            FROM ".TB_PREF."subcontractor_invoices sci                     
            WHERE sci.order_no=".db_escape($sci_no);
    
    $result = db_query($sql, "Could not get_subcontractor_invoice_header_record");
    return db_fetch($result);   
    
}

function release_subcontractor_invoice($sci_no)
{
    $approve_task_costs = array();
    $charging_task_costs = array();
    
    $other_gl_accounts = array();
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    $trans_type = ST_SUBCONTRACTOR_INVOICE;
    
    $sci = get_subcontractor_invoice_header_record($sci_no);
    $date_ = sql2date($sci['ord_date']);
    
    $result = get_subcontractor_invoice_details($sci_no);
    while ($sci_detail = db_fetch($result)){  
        if($sci_detail['task_id'] > 0){
            if($sci_detail['amount'] != 0){// Consider returning values (negative values) to the budegts too
                if($sci_detail['po_line_id'] > 0){
                    $sc_po_line = get_sc_purchase_order_line_record($sci_detail['po_line_id']);
                    $sc_po_line_alloc_amount = ($sc_po_line['quantity'] - $sc_po_line['invoiced_qty']) * $sc_po_line['rate'];
                    if($sc_po_line_alloc_amount > $sci_detail['amount']){
                        $sti_line_approve_amount = 0; // Already allocated by the SC PO. No need to validate again
                    }
                    else{
                        $sti_line_approve_amount = $sci_detail['amount'];  
                    }
                }
                else{
                    $sti_line_approve_amount = $sci_detail['amount'];  
                }
                
                add_to_task_cost($approve_task_costs, $sci_detail['task_id'], $sti_line_approve_amount, $sti_line_approve_amount, $sti_line_approve_amount);
                
                $sti_line_charging_amount = $sci_detail['amount']; 
                add_to_task_cost($charging_task_costs, $sci_detail['task_id'], $sti_line_charging_amount, $sti_line_charging_amount, $sti_line_charging_amount);
            }
        }
        else{
            if($sci_detail['amount'] != 0){
                if(strlen($_POST['debit_account']) > 0 && strlen($_POST['credit_account']) > 0){
                    $gl_info['amount'] = $sci_detail['amount'];  
                    if($sci_detail['amount'] > 0){
                        $gl_info['debit_account'] = $sci_detail['debit_account'];  
                        $gl_info['credit_account'] = $sci_detail['credit_account'];  
                    }
                    else{
                        $gl_info['debit_account'] = $sci_detail['credit_account'];  
                        $gl_info['credit_account'] = $sci_detail['debit_account'];  
                    }
                    $gl_info['memo'] = $sci_detail['category_name']; 
                    
                    $other_gl_accounts[] = $gl_info;
                }
            }
        }
    }
    
    $document_total = $sci['total'] + $sci['taxes'];
    
    $info = approve_document($trans_type, $sci_no, $sci['project_id'], $approve_task_costs, 
                                $sci['next_approval_group_id'], $current_user_id, $sci['row_state'], 
                                $sci['created_by'], $document_total);

    if($info['success'] !== true){
        return array("success" => $info['success'],"trans_no" => $sci_no, "message" => $info['message']);
    }

    if($info['approval_status'] != AS_APPROVED){
        return array("success" => $info['success'], "trans_no" => $sci_no, "message" => $info['message']);
    }
    
    $result2 = get_subcontractor_invoice_details($sci_no);
    while ($sci_detail = db_fetch($result2)){  
        if($sci_detail['po_line_id'] > 0){
            $total_invoiced_qty = get_sc_po_line_invoiced_qty($sci_detail['po_line_id']);
            update_sc_po_line_inviced_qty($sci_detail['po_line_id'], $total_invoiced_qty);
        }
    }
    
    $scpo_no = $sci['po_no'];
    if($scpo_no > 0){
        $sc_po_tasks_summary = calculate_sc_po_task_remaining_totals($scpo_no); 
        $apc_msg = allocate_to_tasks(ST_SUBCONTRACTOR_PURCH_ORDER, $scpo_no, $sc_po_tasks_summary, $current_user_id);
        if($apc_msg['success'] !== true)
        {
            cancel_transaction();
            return array("success" => $apc_msg['success'], "tran_no" => $scpo_no, "message" => $info['message']);
        }
    }
    
    get_task_cost_details($charging_task_costs);
    $cct_msg = charge_cost_to_tasks($trans_type, $sci_no, $charging_task_costs, $current_user_id);
    if($cct_msg['success'] !== true)
    {
        return array("success" => $cct_msg['success'], "tran_no" => $sci_no, "message" => $cct_msg['message']);
    }
    
    
    /* Financial entries */
    
    if(exists_supp_trans($trans_type, $sci_no)){
        return array("success" => false, "message" => "Subcontractor Invoice $sci_no is already in the Supplier's transactions list.");
    }
    
    $total = 0;
    $supplier = get_supplier($sci['supplier_id']);
    $ex_rate = get_exchange_rate_from_home_currency($supplier['curr_code'], $date_);
    
    write_supp_trans($trans_type, $sci_no, $sci['supplier_id'], $date_, sql2date($sci['due_date']), $sci['reference'], $sci['supp_inv_ref'],
                     $sci['total'], $sci['taxes'], 0, "", 0, $sci['rate_include_taxes'], 0, 0, $sci['tax_group_id'], $sci['staxes']);
    
    $taxes = get_subcontractor_invoice_tax_details($sci_no);
    foreach ($taxes as $taxitem)
    {
		if ($taxitem['amount'] != 0)
		{
			add_trans_tax_details($trans_type, $sci_no, $taxitem['tax_type_id'], $taxitem['rate'], $sci['rate_include_taxes'], 
                                    $taxitem['amount'], $sci['total'], $ex_rate, $date_, $sci['supp_inv_ref']);

//			$total += add_gl_trans_supplier($trans_type, $sci_no, $date_,
//                                            $taxitem['purchasing_gl_code'], 0, 0, $taxitem['amount'],
//                                            $sci['supplier_id'],
//                                            "A general ledger transaction for the tax amount could not be added");
		}
    }
    
//    add_gl_trans_supplier($trans_type, $sci_no, $date_, $supplier["payable_account"], 0, 0,
//                                    -($sci['total'] + $sci['taxes']), $sci['supplier_id'],
//                                    "The general ledger transaction for the control total could not be added");
    
    $subcontract_exp_act = get_sys_prefs_parameter_value('subcontract_exp_act');
    if(!(isset($subcontract_exp_act) && strlen($subcontract_exp_act) > 0)){
        $message = "Subcontract Expenses Account not entered in the system.";
        return array("success" => false, "tran_no" => $sci_no, "message" => $message);
    }
                
//    $memo_ = "";
//    $total += add_gl_trans_supplier($trans_type, $sci_no, $date_, $subcontract_exp_act,
//        0, 0, $sci['total'] , $sci['supplier_id'], "", 0, $memo_);
    
    // Other GL transactions
    
//    $err_msg = "Other GL transaction of Subcontractor invoice could not be inserted";	
//    $supp_curr = get_supplier_currency($sci['supplier_id']);
//    foreach ($other_gl_accounts as $gl_info)
//    {
//        $gl_info_memo = "";
//        if(strlen($gl_info['memo']) > 0){
//            $gl_info_memo = $gl_info['memo'];
//        }
//        add_gl_trans($trans_type, $sci_no, $date_, $gl_info['debit_account'], 0, 0, $gl_info_memo, 
//                        $gl_info['amount'], $supp_curr, 
//                        PT_SUPPLIER, $sci['supplier_id'], $err_msg, 0);
//        
//        add_gl_trans($trans_type, $sci_no, $date_, $gl_info['credit_account'], 0, 0, $gl_info_memo, 
//                        -$gl_info['amount'], $supp_curr, 
//                        PT_SUPPLIER, $sci['supplier_id'], $err_msg, 0);
//    }
        
//  add_gl_balance($trans_type, $sti_no, $date_, -$sti_total_excl, PT_SUPPLIER, $sti['supplier_id']); // ??

//	add_comments(ST_SUPPLIER_TRANSPORT_INVOICES, $invoice_id, $date_, $sti['comments']);
//
//	$Refs->save(ST_SUPPLIER_TRANSPORT_INVOICES, $invoice_id, $sti['supp_inv_ref']);
    
    return array("success" => true, "tran_no" => $sci_no, "message" => $info['message']);
}



function get_subcontractor_invoice_tax_details($inv_no)
{     
    $ret_tax_array = array();
    
    $sql = "SELECT si_taxes.*, tax_types.purchasing_gl_code   
            FROM ".TB_PREF."subcontractor_invoice_taxes si_taxes 
                    JOIN ".TB_PREF."tax_types tax_types 
            WHERE order_no = ".db_escape($inv_no)." AND 
                    si_taxes.tax_type_id = tax_types.id ";
     
    $result = db_query($sql, "Could not get_subcontractor_invoice_tax_details.");
    
//    	$active_taxes = $ret_tax_array = array();
//
//	$tax_group_items = get_tax_group_rates($id);

	while ($tax_group_item = db_fetch_assoc($result)) 
	{
		$tax_group_item['Value'] = $tax_group_item['amount'];
		$ret_tax_array[$tax_group_item['tax_type_id']] = $tax_group_item;
	}

	return $ret_tax_array;
    
 
}

function can_change_subcontractor_invoice_project($inv_no)
{    
    $sql = "SELECT id   
            FROM ".TB_PREF."subcontractor_invoice_details  
            WHERE order_no = ".db_escape($inv_no)." AND 
                    (item_id > 0 OR task_id > 0)";
     
    $result = db_query($sql, "Could not check can_change_subcontractor_invoice_project.");

    if(db_num_rows($result) > 0){
        return false;
    }  
    else{
        return true;
    }
}


function get_sc_po_line_invoiced_qty($po_line_id)
{
    $sql = "SELECT SUM(invd.quantity) total_invoiced_qty       
             FROM ".TB_PREF."subcontractor_invoice_details invd 
                 JOIN ".TB_PREF."subcontractor_invoices inv ON 
                     invd.order_no = inv.order_no 
             WHERE inv.approval_status NOT IN (".AS_NEW.",".AS_AWAITING_APPROVAL.",".AS_WITH_THE_APPROVER.","
                                                .AS_BACK_TO_ORIGINATOR.",".AS_REJECTED.") AND 
                 invd.po_line_id=".db_escape($po_line_id);

    $result = db_query($sql);

    $t =  db_fetch($result);
    if(isset($t['total_invoiced_qty']) && $t['total_invoiced_qty'] > 0){
        return $t['total_invoiced_qty'];
    }
    else{
        return 0;
    }
}


function get_sc_po_line_unapproved_invoices_qty($po_line_id, $inv_line_id = 0)
{
    $sql = "SELECT SUM(invd.quantity) total_invoiced_qty       
             FROM ".TB_PREF."subcontractor_invoice_details invd 
                 JOIN ".TB_PREF."subcontractor_invoices inv ON 
                     invd.order_no = inv.order_no 
             WHERE inv.approval_status IN (".AS_NEW.",".AS_AWAITING_APPROVAL.",".AS_WITH_THE_APPROVER.",".AS_BACK_TO_ORIGINATOR.") AND 
                 invd.po_line_id=".db_escape($po_line_id);
    
    if($inv_line_id > 0){
        $sql .= " AND invd.id <> ".db_escape($inv_line_id);
    }
     
    $result = db_query($sql);

    $t =  db_fetch($result);
    if(isset($t['total_invoiced_qty']) && $t['total_invoiced_qty'] > 0){
        return $t['total_invoiced_qty'];
    }
    else{
        return 0;
    }
}



function copy_and_save_subcontractor_invoice_details($new_pi_no, $old_pi_no) {

    global $systypes_array;
    
    $old_result = get_subcontractor_invoice_detail_records($old_pi_no);
        while ($row = db_fetch($old_result)) {
            
            add_subcontractor_invoice_details($new_pi_no, $row['line_type'], $row['item_type'], $row['po_line_id'], $row['sequence'], $row['item_id'], 
                                              $row['description'], $row['completed_date'], $row['unit'], $row['quantity'], $row['rate'], $row['amount'], 
                                              $row['line_comment'], $row['task_id'], $row['category_id'], $row['debit_account'], $row['credit_account']);
                    
            if (db_num_affected_rows() != 1) {
                cancel_transaction();
                
                return array('success' => false, 'message' => "Could not copy ".$systypes_array[ST_SUBCONTRACTOR_INVOICE]." #$old_pi_no.");
            }
        }
        
        return array('success' => true, 'message' => $systypes_array[ST_SUBCONTRACTOR_INVOICE]." #$old_pi_no has been copied to new ".$systypes_array[ST_SUBCONTRACTOR_INVOICE]." #$new_pi_no.");
}

?>