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

function update_boq_item_site_balances($boq_item_id, $site_id, $item_site_total_qty, $last_entry_date)
{
    $existing_record = get_boq_item_site_record($boq_item_id, $site_id);
    if($existing_record){
        
        update_boq_item_site_total_work_done($existing_record['id'], $item_site_total_qty, $last_entry_date);
    }
    else{      
        
        add_boq_item_site_record($boq_item_id, $site_id, $item_site_total_qty, $last_entry_date);
    }  
}

function add_boq_item_site_record($boq_item_id, $site_id, $total_qty, $last_entry_date)
{
    $id_user = $_SESSION['wa_current_user']->user;
    $datetime = date('Y-m-d H:i:s');
                
    $sql = "INSERT INTO ".TB_PREF."project_boq_item_sites  
                        (boq_item_id, site_id,  
                        completed_qty, last_entry_date, 
                        created_by, created_on) 

            VALUES (".db_escape($boq_item_id).", ".db_escape($site_id).", "
                    .db_escape($total_qty).", ".db_escape($last_entry_date).", "
                    .db_escape($id_user).", ".db_escape($datetime).")";

        db_query($sql,"Could not add_boq_item_site_record");	
}

function update_boq_item_site_total_work_done($id, $total_qty, $last_entry_date)
{
    $sql = "UPDATE ".TB_PREF."project_boq_item_sites 
                SET                      
                    completed_qty = ".db_escape($total_qty).", 
                    last_entry_date=".db_escape($last_entry_date)." 
                WHERE id=".db_escape($id);

        db_query($sql,"Could not update_boq_item_site_total_work_done");		
}



function get_boq_item_site_record($boq_group_id, $project_site_id)
{
   $sql = "SELECT * 
            FROM ".TB_PREF."project_boq_item_sites 
            WHERE boq_item_id = ".db_escape($boq_group_id)." 
                    AND site_id =".db_escape($project_site_id);
                 

   $result = db_query($sql, "Could not get_boq_item_site_record");
   return db_fetch($result);     
}



function get_boq_item_total_work_done($boq_item_id)
{
    $sql = "SELECT SUM(completed_qty) total_work_done  
            FROM ".TB_PREF."project_boq_item_sites 
            WHERE boq_item_id=".db_escape($boq_item_id); //." AND 
                  //tran_date <=".db_escape($tran_date);
    
    $result = db_query($sql);
    $twd = db_fetch($result);
    
    $total_work_done = 0;
    if(isset($twd['total_work_done']) &&  $twd['total_work_done'] > 0){
        $total_work_done =  $twd['total_work_done'];
    }    
    return $total_work_done;
}


?>