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


function get_local_purchase_order_header($po_no)
{
    $sql = "SELECT po.*, 
                    po.delivery_address saved_delivery_address,
                    supp.supp_name, 
                    po.tax_group_id,
                    supp.curr_code, 
                    loc.location_name, 
                    pm.description project_description 
                   
            FROM ".TB_PREF."purch_orders po, 
                    ".TB_PREF."suppliers supp, 
                    ".TB_PREF."locations loc, 
                    ".TB_PREF."projects_master pm 

            WHERE po.supplier_id = supp.supplier_id
            AND loc.loc_code = into_stock_location
            AND pm.project_id = po.project_id  
            AND po.order_no = ".db_escape($po_no);

   	$result = db_query($sql, "The order cannot be retrieved");
 
    return db_fetch($result);   
    
}

function get_import_purchase_order_header($po_no)
{
    $sql = "SELECT * 
            FROM ".TB_PREF."import_purch_orders 
            WHERE order_no = ".db_escape($po_no);

   	$result = db_query($sql, "get_import_purchase_order_header cannot be retrieved");
 
    return db_fetch($result);   
}


function get_purchase_order_details($order_no, $pr_no=0)
{

if($pr_no > 0){
        $sql = "SELECT pod.*, 
                    pod.order_unit_qty * (pod.order_unit_price * (1 - order_unit_price_discount/100)) line_total,
                    sm.units, sm.stock_control_method, sm.editable editable_description,
                    u.name tran_unit_name,
                    ps.description project_site_name,
                    prd.quantity pr_qty,
                    prd.issued_qty pr_issued_qty,
                    prd.id pr_line_id,
                    prd.requisition_id,
                    pr_po.id pr_po_line_id,
                    prd.task_id,
                    sm.description item_description 
                FROM ".TB_PREF."purch_order_details pod 
                    INNER JOIN ".TB_PREF."pr_po_details pr_po ON 
                        pod.po_detail_item = pr_po.po_line_id 
                    INNER JOIN ".TB_PREF."purchase_requisition_details prd ON 
                        pr_po.pr_line_id = prd.id 
                    INNER JOIN ".TB_PREF."stock_master sm ON 
                        pod.item_code= sm.stock_id 
                    LEFT JOIN ".TB_PREF."item_units u ON 
                        pod.order_unit= u.abbr   
                    LEFT JOIN ".TB_PREF."project_sites ps ON 
                        pod.project_site_id = ps.id   
                WHERE pod.order_no =".db_escape($order_no)." AND 
                        prd.requisition_id = ".db_escape($pr_no);
    }
    else{
        $sql = "SELECT pod.*, 
                    pod.order_unit_qty * (pod.order_unit_price * (1 - order_unit_price_discount/100)) line_total,
                    sm.units, sm.stock_control_method, sm.editable editable_description,
                    u.name tran_unit_name,
                    ps.description project_site_name,
                    0 pr_qty,
                    0 pr_issued_qty,
                    0 pr_line_id,
                    0 requisition_id,
                    0 pr_po_line_id,
                    0 task_id,
                    sm.description item_description 
                FROM ".TB_PREF."purch_order_details pod 
                    INNER JOIN ".TB_PREF."stock_master sm ON 
                        pod.item_code= sm.stock_id 
                    LEFT JOIN ".TB_PREF."item_units u ON 
                        pod.order_unit= u.abbr   
                    LEFT JOIN ".TB_PREF."project_sites ps ON 
                        pod.project_site_id = ps.id   
                WHERE pod.order_no =".db_escape($order_no);
    }
    
//    if ($open_items_only){
// 		$sql .= " AND (pod.quantity_ordered > pod.quantity_received) ";
//    }

	$sql .= " ORDER BY pod.po_detail_item";

	return db_query($sql, "The lines on the purchase order cannot be retrieved");

}



function write_purchase_order_header($type, $po_no, $reference, $project_id, $supplier_id,
                                     $date, $rate_include_taxes, $tax_group_id,
                                     $comment, $terms_indicator,
                                     $supp_ref, $location, $delivery_address,
                                     $total_scpo, $taxes_total, $generated_po,
                                     $next_approval_group_id, $row_state, $curr_code, $curr_rate)                          
{
    global $Refs;
    
    if($po_no > 0){   
        update_purchase_order_header($po_no, $comment, $supp_ref, $terms_indicator, $location, 
                                     $date, $delivery_address, $total_scpo, $project_id, 
                                     $rate_include_taxes, $tax_group_id, $taxes_total, $row_state, 
                                     $supplier_id);
    }else{
        
        $po_no = add_purchase_order_header($type, $reference, $project_id, $supplier_id,
                                           $date, $rate_include_taxes, $tax_group_id,
                                           $comment, $terms_indicator,
                                           $supp_ref, $location, $delivery_address,
                                           $total_scpo, $taxes_total, $generated_po,
                                           $next_approval_group_id, $curr_code, $curr_rate);
        
        $Refs->save(ST_PURCHORDER, $po_no, $reference);
    }

    if(!($po_no > 0)){
        return;
    }    
    
    return $po_no;
}



function write_import_purchase_order_header($po_no, $sub_total_name, $freight_name, $freight_value, 
                                            $insurance_name, $insurance_value, $total_name,
                                            $payment_term_details)
{
    global $Refs;
    
    $poh = get_import_purchase_order_header($po_no);
    
    if($poh['order_no'] > 0){   
        update_import_purchase_order_header($po_no, $sub_total_name, $freight_name, $freight_value, 
                                            $insurance_name, $insurance_value, $total_name,
                                            $payment_term_details);
    }else{
        add_import_purchase_order_header($po_no, $sub_total_name, $freight_name, $freight_value, 
                                                $insurance_name, $insurance_value, $total_name,
                                                $payment_term_details);
    }

}


function write_purchase_order_detail($po_no, $item_code, $item_description, $req_del_date, 
                                     $unit_price , $quantity, $convertion_factor,
                                     $tran_unit, $tran_qty, $order_unit_price, 
                                     $order_unit_price_discount,
                                     $minimum_price, $minimum_price_discount,
                                     $min_price_sup_id, $project_site_id, $selected_id)
{            
    if($selected_id > 0){   
        
        $n = update_purchase_order_detail($po_no, $item_description,
                                          $req_del_date, $order_unit_price, $tran_unit,
                                          $tran_qty, $convertion_factor, $quantity, 
                                          $unit_price, $order_unit_price_discount,
                                          $minimum_price, $minimum_price_discount,
                                          $min_price_sup_id, $project_site_id, $selected_id);    
        if($n != 1){
           return array("success" => false, "message" => "Updated import purchase order detail $selected_id.");  
        }
    }
    else{
        add_purchase_order_detail($po_no, $item_code, $item_description,
                                  $req_del_date, $order_unit_price, $quantity, $tran_unit,
                                  $tran_qty, $convertion_factor, 
                                  $unit_price, $order_unit_price_discount,
                                  $minimum_price, $minimum_price_discount,
                                  $min_price_sup_id, $project_site_id); 
    }
    
    $tax_group_id = 0;
    $rate_include_taxes = 0;
    //update_purchase_order_taxes($po_no, $tax_group_id, $rate_include_taxes);
    
    return array("success" => true, "message" =>"Subcontractor purchase order $po_no has been updated.");
    
}


function update_purchase_order_taxes($po_no, $tax_group_id, $rate_include_taxes)
{
//    $po_lines_total = get_purchase_order_lines_total($po_no);
    
//    $taxes_array = calculate_common_item_taxes($po_lines_total, $tax_group_id, $rate_include_taxes);
    
//    $po_tax_total = update_sc_purchase_order_header_taxes($scpo_no, $taxes_array);
    
    $po_tax_total = 0;
    update_purchase_order_header_totals($po_no, $po_tax_total, $rate_include_taxes);
    
}


function update_sc_purchase_order_taxes_manual($po_no, $taxes_array)
{
    $poh = get_sc_purchase_orders_header($po_no);
    
    $po_tax_total = update_sc_purchase_order_header_taxes($po_no, $taxes_array);
    
    update_sc_purchase_order_header_totals($po_no, $po_tax_total, $poh['rate_include_taxes']);
          
}


function update_purchase_order_header_totals($po_no, $po_tax_total, $rate_include_taxes)
{
    $po_line_total = get_purchase_order_lines_total($po_no);
    if($rate_include_taxes){
        $tax_free_total = $po_line_total - $po_tax_total;
    }
    else{
        $tax_free_total = $po_line_total;
    }

    $sql =  "UPDATE ".TB_PREF."purch_orders 
                SET total =".db_escape($tax_free_total).",
                    taxes =".db_escape($po_tax_total)." 
                WHERE order_no =".db_escape($po_no);
        
    db_query($sql, "Could not update_purchase_order_header_totals");   
}

function get_purchase_order_lines_total($po_no)
{
    $sql = "SELECT SUM(order_unit_qty * order_unit_price) lines_amount_total
            FROM ".TB_PREF."purch_order_details 
            WHERE order_no =".db_escape($po_no);
    
    $result = db_query($sql, "Could not get_purchase_order_lines_total");
    
    $po_detail = db_fetch($result);
        
    if(isset($po_detail['lines_amount_total']) && $po_detail['lines_amount_total'] > 0){
        return $po_detail['lines_amount_total'];    
    }else{
        return 0;
    }
  
}


//function update_utility_bills_line_taxes($scpo_no, $ubd_line_id, $line_total, $tax_group_id, $rate_include_taxes)
//{     
//    delete_utility_bills_line_tax_details($ubd_line_id);
//    
//    $item_taxes_array = calculate_common_item_taxes($line_total, $tax_group_id, $rate_include_taxes);
//    $item_tax_total = 0;
//        
//    foreach ($item_taxes_array as $tax_detail) {
//        if($tax_detail['rate'] > 0){
//            add_utility_bills_tax_detail($scpo_no, $ubd_line_id, $tax_detail['tax_type_id'], $tax_detail['Value']);
//            $item_tax_total += $tax_detail['Value'];
//        }
//    }
//    
//    return $item_tax_total;
//}



function add_sc_purchase_order_tax_detail($scpo_no, $tax_type_id, $rate, $tax_value)
{    
    $sql = "INSERT INTO ".TB_PREF."subcontractor_purchase_order_taxes 
                   (sc_po_id, tax_type_id, rate, amount)
            VALUES 
            (".db_escape($scpo_no).","
                .db_escape($tax_type_id).","
                .db_escape($rate).","
                .db_escape($tax_value).")";              
     
    db_query($sql, "Could not add_sc_purchase_order_tax_detail.");
 
}

//function update_utility_bills_line_tax_total($ubd_line_id, $ub_line_tax_total)
//{
//    $sql =  "UPDATE ".TB_PREF."utility_bill_details 
//                SET taxes=".db_escape($ub_line_tax_total)." 
//                WHERE id=".db_escape($ubd_line_id);
//        
//        db_query($sql, "Could not update_utility_bills_line_tax_total");   
//}

function update_sc_purchase_order_header_taxes($scpo_no, $taxes_array)
{
    delete_sc_purchase_order_header_taxes($scpo_no);    
     
    $po_tax_total = 0;
//    $result = get_utility_bill_line_tax_totals($scpo_no);
    foreach ($taxes_array as $tax_detail) {
        if($tax_detail['Value'] > 0){
            add_sc_purchase_order_tax_detail($scpo_no, $tax_detail['tax_type_id'], $tax_detail['rate'], $tax_detail['Value']);
            $po_tax_total += $tax_detail['Value'];  
        }
            
    }
    
//    $po_tax_total = get_project_sales_order_tax_total($scpo_no);   
//    return $item_tax_total;
//    
//    $sql =  "UPDATE ".TB_PREF."utility_bills 
//                SET taxes =".db_escape($po_tax_total)." 
//                WHERE id=".db_escape($scpo_no);
//        
//    db_query($sql, "Could not update_utility_bills_header_taxs");  
    
    return $po_tax_total;
}


//function get_utility_bill_line_tax_totals($scpo_no)
//{
//    $sql = "SELECT tax_type_id, SUM(ubt.amount) tax_total 
//            FROM ".TB_PREF."utility_bill_taxes ubt 
//            WHERE ubt.ub_id=".db_escape($scpo_no)."                   
//            GROUP BY ubt.tax_type_id";
//    
//    return db_query($sql, "Could not get_utility_bills_line_tax_totals");  

//}


function delete_sc_purchase_order_header_taxes($scpo_no)
{     
    $sql = "DELETE FROM ".TB_PREF."subcontractor_purchase_order_taxes  
            WHERE sc_po_id = ".db_escape($scpo_no);
     
    db_query($sql, "Could not delete_sc_purchase_order_header_taxes.");
 
}


function update_purchase_order_header($po_no, $comments, $supp_ref, $terms_indicator, $location, 
                                      $order_date, $delivery_address, $trans_total, $project_id, 
                                      $tax_included, $tax_group_id, $taxes_total, $row_state,
                                      $supplier_id)
{
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
    $sql = "UPDATE ".TB_PREF."purch_orders 
            SET comments=" . db_escape($comments) . ",
                requisition_no= ". db_escape( $supp_ref). ",
                supplier_id= ". db_escape( $supplier_id). ",
                terms_indicator= ". db_escape( $terms_indicator). ",
                into_stock_location=" . db_escape($location). ",
                ord_date='" . date2sql($order_date) . "',
                delivery_address=" . db_escape($delivery_address).",
                total=". db_escape($trans_total).",
                project_id=". db_escape($project_id).",
                tax_included=". db_escape($tax_included).", 
                tax_group_id=". db_escape($tax_group_id).", 
                taxes=". db_escape($taxes_total).", 
                updated_by =". db_escape($updated_by).",
                updated_on =". db_escape($updated_on).",
                row_state = ". db_new_row_state($row_state);
        
    $sql .= " WHERE order_no = " . db_escape($po_no). " 
                AND row_state = ".db_escape($row_state);
    
    db_query($sql, "The purchase order could not be updated");
  
    return db_num_affected_rows();  
}

function update_import_purchase_order_header($po_no, $sub_total_name, $freight_name,$freight_value, 
                                                $insurance_name, $insurance_value, $total_name,
                                                $payment_term_details)
{
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
    $sql = "UPDATE ".TB_PREF."import_purch_orders  
            SET sub_total_name = ".db_escape($sub_total_name).",
                freight_name = ".db_escape( $freight_name).",
                freight_value = ".db_escape( $freight_value).",
                insurance_name = ".db_escape( $insurance_name).",
                insurance_value = ".db_escape($insurance_value).",
                total_name = ".db_escape($total_name).", 
                payment_term_details = ".db_escape($payment_term_details)." 
        
            WHERE order_no = ".db_escape($po_no)."";
               
    
    db_query($sql, "The purchase order could not be updated");
  
    return db_num_affected_rows();  
}


function add_purchase_order_header($type, $reference, $project_id, $supplier_id,
                                   $date, $rate_include_taxes, $tax_group_id,
                                   $comment, $terms_indicator,
                                   $supp_ref, $location, $delivery_address,
                                   $total_scpo, $taxes_total, $generated_po,
                                   $next_approval_group_id, $curr_code, $curr_rate)
{
    $id_user = $_SESSION['wa_current_user']->user;
    $datetime = date('Y-m-d H:i:s');
    
     $sql = "INSERT INTO ".TB_PREF."purch_orders (
                type,
                supplier_id, 
                Comments, 
                ord_date, 
                reference, 
                terms_indicator,
                requisition_no, 
                into_stock_location, 
                delivery_address, 
                total, 
                tax_included,  
                tax_group_id,
                taxes,
                created_by, 
                created_on,
                project_id,
                generated_po,
                next_approval_group_id,
                curr_code,
                curr_rate) 
            VALUES(";
     $sql .= db_escape($type) . "," .
                db_escape($supplier_id) . "," .
                db_escape($comment) . ",'" .
                date2sql($date) . "', " .
                db_escape($reference) . ", " .
                db_escape($terms_indicator) . ", " .
                db_escape($supp_ref) . ", " .
                db_escape($location) . ", " .
                db_escape($delivery_address) . ", " .
                db_escape($total_scpo). ", " .
                db_escape($rate_include_taxes). ", " .
                db_escape($tax_group_id). ", " .
                db_escape($taxes_total). ", " .
                db_escape($id_user). ", " .
                db_escape($datetime). ", ".
                db_escape($project_id). ", ".
                db_escape($generated_po). ", ".
                db_escape($next_approval_group_id). ", ".
                db_escape($curr_code). ", ".
                db_escape($curr_rate). " )";
     
    db_query($sql);
    return db_insert_id();        
}

function add_import_purchase_order_header($po_no, $sub_total_name, $freight_name, $freight_value, 
                                            $insurance_name, $insurance_value, $total_name,
                                            $payment_term_details)
{
    $id_user = $_SESSION['wa_current_user']->user;
    $datetime = date('Y-m-d H:i:s');
    
     $sql = "INSERT INTO ".TB_PREF."import_purch_orders (
                order_no, 
                sub_total_name, 
                freight_name, 
                freight_value, 
                insurance_name,
                insurance_value,
                total_name,
                payment_term_details) 
            VALUES(
                ".db_escape($po_no).",
                ".db_escape($sub_total_name).", 
                ".db_escape($freight_name).", 
                ".db_escape($freight_value).", 
                ".db_escape($insurance_name).", 
                ".db_escape($insurance_value).", 
                ".db_escape($total_name).", 
                ".db_escape($payment_term_details).")";
     
    db_query($sql);
    return db_insert_id();        
}


function add_purchase_order_detail($scpo_no, $stock_id, $item_description,
                                    $req_del_date, $order_unit_price, $quantity, $tran_unit,
                                    $tran_qty, $convertion_factor, 
                                    $unit_price, $order_unit_price_discount,
                                    $minimum_price, $minimum_price_discount,
                                    $min_price_sup_id, $project_site_id)
{
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
    
    
    $sql = "INSERT INTO ".TB_PREF."purch_order_details (
                            order_no, item_code, 
                            description, delivery_date, 
                            order_unit_price, quantity_ordered, 
                            original_order_qty, order_unit, 
                            order_unit_qty, order_unit_conv_factor, 
                            unit_price, order_unit_price_discount,
                            minimum_price, minimum_price_discount,
                            min_price_sup_id, project_site_id,
                            created_by, created_on) 
            VALUES (";
            $sql .= $scpo_no . ", " . db_escape($stock_id). "," .
            db_escape($item_description). ",'" .date2sql($req_del_date) . "'," .
            db_escape($order_unit_price) . ", " .db_escape($quantity) . ", " .
            db_escape($quantity). " , " .db_escape($tran_unit). " , " .
            db_escape($tran_qty). " , " .db_escape($convertion_factor). ", " .
            db_escape($unit_price). ", " .db_escape($order_unit_price_discount). ", " .
            db_escape($minimum_price). ", " .db_escape($minimum_price_discount). ", " .
            db_escape($min_price_sup_id). ",".db_escape($project_site_id). ",".
            db_escape($created_by). ", " .db_escape($created_on). ")";

            db_query($sql, "One of the purchase order detail records could not be inserted");
            return db_insert_id();
                
            
}


function update_purchase_order_detail($po_no, $item_description,
                                      $req_del_date, $order_unit_price, $tran_unit,
                                      $tran_qty, $convertion_factor, $quantity, 
                                      $unit_price, $order_unit_price_discount,
                                      $minimum_price, $minimum_price_discount,
                                      $min_price_sup_id, $project_site_id, $selected_id)
{
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
    
    $sql = "UPDATE ".TB_PREF."purch_order_details  
            SET description = ". db_escape($item_description). ",
                delivery_date = ". db_escape(date2sql($req_del_date)). ",
                order_unit_price =" . db_escape($order_unit_price). ",
                order_unit =" . db_escape($tran_unit).",
                order_unit_qty =". db_escape($tran_qty).",
                order_unit_conv_factor =". db_escape($convertion_factor).",
                unit_price =". db_escape($unit_price).",
                order_unit_price_discount =". db_escape($order_unit_price_discount).",
                quantity_ordered =". db_escape($quantity).",
                minimum_price =". db_escape($minimum_price).",
                minimum_price_discount =". db_escape($minimum_price_discount).",
                min_price_sup_id =". db_escape($min_price_sup_id).",
                project_site_id =". db_escape($project_site_id).", 
                updated_by =". db_escape($updated_by).", 
                updated_on =". db_escape($updated_on)." 

            WHERE po_detail_item = ". db_escape($selected_id)." 
                AND order_no = ". db_escape($po_no)."";
 
    db_query($sql, "One of the purchase order detail records could not be updated");
    return db_num_affected_rows();                   
}




function get_purchase_order_header_record($po_no)
{
    $sql = "SELECT * 
            FROM ".TB_PREF."purch_orders  
            WHERE order_no =".db_escape($po_no);
    
    $result = db_query($sql);
    return db_fetch($result);   
    
}

function get_sc_purchase_order_details($order_no)
{
    $sql = "SELECT spod.*,
                    pt.description budget_description,
                    pt.task_code budget_code,
                    pbi.description boq_item_description,
                    pbi.code boq_item_code,
                    iu.name unit_name
        
            FROM ".TB_PREF."subcontractor_purchase_order_details spod
                    LEFT JOIN ".TB_PREF."project_tasks pt ON 
                            spod.task_id = pt.task_id
                            
                    LEFT JOIN ".TB_PREF."project_boq_items pbi ON
                            spod.boq_item_id = pbi.id
                            
                    LEFT JOIN ".TB_PREF."item_units iu ON
                            spod.unit = iu.abbr
                                              
            WHERE spod.sc_po_id=".db_escape($order_no)." 
            ORDER BY id";
    
    return db_query($sql, "Could not get_sc_purchase_order_details.");
    
}



function get_sc_purchase_orders_line($selected_id)
{
     $sql = "SELECT spod.*,
                    pbi.group_id item_boq_group_id,
                    ptg.boq_group_id task_boq_group_id 
         
            FROM ".TB_PREF."subcontractor_purchase_order_details spod 
                LEFT JOIN ".TB_PREF."project_boq_items pbi ON
                    spod.boq_item_id = pbi.id 
                LEFT JOIN ".TB_PREF."project_tasks pt ON
                    spod.task_id = pt.task_id 
                LEFT JOIN ".TB_PREF."project_task_groups ptg ON
                    pt.task_group_id = ptg.id 
                    


                      
             WHERE spod.id=".db_escape($selected_id);
     
     $result = db_query($sql);
     return db_fetch($result);
    
}

//function get_po_line_record($selected_id)
//{
//     $sql = "SELECT * 
//            FROM ".TB_PREF."purch_order_details   
//            WHERE id=".db_escape($selected_id);
//     
//     $result = db_query($sql);
//     return db_fetch($result);
//    
//}

function delete_purchase_order_details($po_detail_id)
{  
    $sql = "DELETE FROM ".TB_PREF."purch_order_details WHERE po_detail_item=".db_escape($po_detail_id);
    db_query($sql);

    return db_num_affected_rows();
    
}


function get_sc_purchase_orders_tax_type_amount($scpo_no, $tax_type_id)
{
    $sql = "SELECT amount 
            FROM ".TB_PREF."subcontractor_purchase_order_taxes 
            WHERE sc_po_id=".db_escape($scpo_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_purchase_orders_line_count($p_order_no)
{
    $sql = "SELECT COUNT(po_detail_item) line_count 
            FROM ".TB_PREF."purch_order_details  
            WHERE po_detail_item = ".db_escape($p_order_no)." 
                AND quantity_received > 0 ";
    
        $result = db_query($sql);
        $count =  db_fetch($result);   
        if(isset($count['line_count']) && $count['line_count'] > 0){
            return $count['line_count'];
        }
        return 0;
}


function release_sc_purchase_order111($scpo_no)
{
    $task_costs = array();
    $current_user_id = $_SESSION['wa_current_user']->user;
    $trans_type = ST_SUBCONTRACTOR_PURCH_ORDER;
    
    $scpoh = get_sc_purchase_orders_header($scpo_no);
    $date_ = sql2date($scpoh['date']);
    
    $scpoh_total_with_taxes = $scpoh['total'] + $scpoh['taxes'];
    $scpoh_total_no_taxes = $scpoh['total'];
    $tax_factor = $scpoh_total_no_taxes/$scpoh_total_with_taxes;
    
    $ub_details = get_sc_purchase_order_details($scpo_no);
    
    while ($myrow = db_fetch($ub_details))
    {
        $a['row_id'] = $myrow['id'];
        $a['task_id'] = $myrow['task_id'];
        $a['requested_qty'] = 1;
        $a['high_value_item'] = 0;
        
        if($scpoh['rate_include_taxes']){
            $line_tax_free_amount = $myrow['amount'] * $tax_factor;
        }
        else{
            $line_tax_free_amount = $myrow['amount'];
        }
        $a['reference_cost'] = $line_tax_free_amount;
        $a['standard_cost'] = $line_tax_free_amount;
        $a['total_issued_qty'] = 0;
        $a['qty'] = 1;
        
        $ub_details_array[] = $a;
        
    }
    
    $task_costs = calculate_task_remaining_totals($ub_details_array);

    $info = approve_document($trans_type, $scpo_no, $ubh['project_id'], $task_costs, 
                                    $ubh['next_approval_group_id'], $current_user_id, $ubh['row_state'], $ubh['created_by']);
        
    if($info['success'] !== true){
        return array("success" => $info['success'],"trans_no" => $scpo_no, "message" => $info['message']);
    }
    
    if($info['approval_status'] != AS_APPROVED){
        return array("success" => $info['success'], "trans_no" => $scpo_no, "message" => $info['message']);
    }
    
    $cct_msg = charge_cost_to_tasks($trans_type, $scpo_no, $task_costs, $current_user_id);
    
    if($cct_msg['success'] !== true)
    {
        return array("success" => $cct_msg['success'], "tran_no" => $scpo_no, "message" => $cct_msg['message']);
    }
    
    
    /* Financial entries */
    
    if(exists_supp_trans($trans_type, $scpo_no)){
        return array("success" => false, "message" => "Utility Bill $scpo_no is already in the Supplier's transactions list.");
    }
    
    $total = 0;
    $supplier = get_supplier($ubh['supplier_id']);
    $ex_rate = get_exchange_rate_from_home_currency($supplier['curr_code'], $date_);
    
    write_supp_trans($trans_type, $scpo_no, $ubh['supplier_id'], $date_, sql2date($ubh['date']),
                                    $ubh['reference'], '',
                                    $ubh_total_excl, $ubh['taxes'], 0, "", 0, $ubh['rate_include_taxes']);

    /**********
    $taxes = get_utility_bill_tax_details($scpo_no);
    foreach ($taxes as $taxitem)
    {
		if ($taxitem['amount'] != 0)
		{
			add_trans_tax_details($trans_type, $scpo_no, $taxitem['tax_type_id'], $taxitem['rate'], $ubh['rate_include_taxes'], 
                                    $taxitem['amount'], $ubh_total_excl, $ex_rate, $date_, $ubh['reference']);

			$total += add_gl_trans_supplier($trans_type, $scpo_no, $date_,
                                            $taxitem['purchasing_gl_code'], 0, 0, $taxitem['amount'],
                                            $ubh['supplier_id'],
                                            "A general ledger transaction for the tax amount could not be added");
		}
    }
    
    add_gl_trans_supplier($trans_type, $scpo_no, $date_, $supplier["payable_account"], 0, 0,
                                    -($ubh_total_incl), $ubh['supplier_id'],
                                    "The general ledger transaction for the control total could not be added");
    
    $ub_details2 = get_utility_bill_details($scpo_no);
    
    while ($ub_detail = db_fetch($ub_details2))
    {
        $ub_line_expense_type = get_utility_expense_type($ub_detail['expense_type_id']);
        $ub_exp_act = $ub_line_expense_type['debit_account'];
        if(!(isset($ub_exp_act) && strlen($ub_exp_act) > 0)){
            $message = "Debit account not defined for Utility bill expense type ".$ub_detail['name'];
            return array("success" => false, "tran_no" => $scpo_no, "message" => $message);
        }

        $memo_ = $ub_detail['description'];
        $line_tax_free_amount = $ub_detail['amount'] * $tax_factor;
        $total += add_gl_trans_supplier($trans_type, $scpo_no, $date_, $ub_exp_act,
            0, 0, $line_tax_free_amount , $ubh['supplier_id'], "", 0, $memo_);
    }
     * 
     */
    return array("success" => true, "tran_no" => $scpo_no, "message" => $info['message']);
}



function release_purchase_order($po_no)
{
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $scpoh = get_purchase_order_header_record($po_no);
    
//    $scpoh_total_with_taxes = $scpoh['total'] + $scpoh['taxes'];
    
//    $tasks_summary = calculate_task_remaining_total($po_no); 
    $tasks_summary = $scpoh['total'] + $scpoh['taxes'];
    
    $info = approve_document(ST_PURCHORDER, $po_no, $scpoh['project_id'], $tasks_summary, 
                             $scpoh['next_approval_group_id'], $current_user_id, $scpoh['row_state']);

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

//    if($info['approval_status'] == AS_APPROVED)
//    {            
//        $apc_msg = allocate_to_tasks(ST_PURCHORDER, $po_no, $tasks_summary, $current_user_id);
//        if($apc_msg['success'] !== true)
//        {
//            cancel_transaction();
//            return array("success" => $apc_msg['success'], "tran_no" => $po_no, "message" => $info['message']);
//        }
//    }
    commit_transaction();
    return array("success" => true, "tran_no" => $po_no, "message" => $info['message']);
        
}

function calculate_task_remaining_total($po_id)
{
        $task_costs = array();
        
        $result = get_po_task_remaining_totals($po_id);
        
        while($row = db_fetch($result))
        {            
            if($row['task_cost'] >= 0){
                add_to_task_cost($task_costs, $row['task_id'], $row['task_cost'], $row['task_cost'], $row['task_cost']);
            }
        }
        
        get_task_cost_details($task_costs);
        
        return $task_costs;
}

function get_po_task_remaining_totals($po_id)
{
    $sql = "SELECT task_id, SUM((order_unit_qty - qty_invoiced) * rate) task_cost 
            FROM ".TB_PREF."purch_order_details 
            WHERE order_no = ".db_escape($po_id)." 
            GROUP BY task_id";
    
    return db_query($sql);
}

function update_sc_po_line_inviced_qty($po_line_id, $total_invoiced_qty)
{
    $sql = "UPDATE ".TB_PREF."subcontractor_purchase_order_details
                SET invoiced_qty = ".db_escape($total_invoiced_qty)."                  
                        
                WHERE id=".db_escape($po_line_id);
     
    db_query($sql);
}


function update_sc_po_closed($scpo_no)
{
    $sql = "UPDATE ".TB_PREF."subcontractor_purchase_orders
                SET approval_status = ".db_escape(AS_CLOSED)."                  
                        
                WHERE id=".db_escape($scpo_no)." AND 
                        approval_status = ".db_escape(AS_APPROVED);     
    
    db_query($sql);
}


function get_purchase_orders_line_counts($order_no)
{
    $sql = "SELECT COUNT(po_detail_item) line_count 
            FROM ".TB_PREF."purch_order_details  
            WHERE order_no = ".db_escape($order_no);
    
    $result = db_query($sql);
    $count =  db_fetch($result);   
    if(isset($count['line_count']) && $count['line_count'] > 0){
        return $count['line_count'];
    }
    
    return 0;
}

function get_item_base_unit($item_code)
{
    $sql = "SELECT convertion_factor,
                   base_unit 
            FROM ".TB_PREF."alternate_units 
            WHERE stock_id=".db_escape($item_code)." 
            LIMIT 1 ";
	
	$result = db_query($sql,"get_item_base_unit could not be retreived");
	
	return db_fetch($result);
}


?>





























































































































































































































































































































































































































