<?php

function cs_get_pr_lines(){
    $sql = "SELECT SUM(prid.qty_issued) total_qty_issued, prid.pr_line_id , prd.issued_qty 
            FROM ".TB_PREF."purchase_requistion_issue_details prid   
                JOIN ".TB_PREF."purchase_requisition_details prd 
                    ON prd.id = prid.pr_line_id 
            WHERE  prid.pr_line_id > 0 
            GROUP BY prid.pr_line_id 
            HAVING total_qty_issued <> prd.issued_qty
            ORDER BY prid.pr_line_id 
            LIMIT 100";
    
    return db_query($sql, "cs_get_pr_lines");
}

function cs_update_pr_line_issued_qty($pr_line_id, $issued_qty)
{    
    $sql = "UPDATE ".TB_PREF."purchase_requisition_details     
                SET issued_qty = ".db_escape($issued_qty)."   
            WHERE id = ".db_escape($pr_line_id);
    
    db_query($sql, "cs_update_pr_line_issued_qty");
}

function cs_update_pr_line_total_issued_qty(){
    $message = "==================Script Sarted==========================";
    write_custom_script_log("cs_update_pr_line_total_issued_qty", $message);
    
    $ious_result = cs_get_pr_lines();
    $recs = db_num_rows($ious_result);
    write_custom_script_log("cs_update_pr_line_total_issued_qty", $recs." Records selected");
    
    while($row = db_fetch($ious_result)){
        
//        $prd = get_pr_detail_record($row['pr_line_id']);
        $total_issued_qty = get_pr_item_total_issued_qty($row['pr_line_id']);
        
        if($row['issued_qty'] == $total_issued_qty){
            $message = "Total issued quantity (".$row['issued_qty'].") equal. No need to update PR line #".$row['pr_line_id']." issued quantity.";
            write_custom_script_log("cs_update_pr_line_total_issued_qty", $message);
            continue;
        }
        
        cs_update_pr_line_issued_qty($row['pr_line_id'], $total_issued_qty);
        
        $n = db_num_affected_rows();
        if($n==1){
            $message = "PR line #".$row['pr_line_id']." issued qty updated to ".$total_issued_qty;
        }else{
            $message = "Could not update PR line #".$row['pr_line_id']." issued qty.";
        }
        write_custom_script_log("cs_update_pr_line_total_issued_qty", $message);
    }
    
    $message = "------------------Script Completed----------------------------";
    write_custom_script_log("cs_update_pr_line_total_issued_qty", $message);
}

?>