<?php

function pri_get_pr_issues_total(){
    $sql = "SELECT prid.pri_no, SUM(prid.unit_cost * prid.qty_issued) total 
            FROM ".TB_PREF."purchase_requistion_issue_details prid   
                JOIN ".TB_PREF."purchase_requisition_issues pri   
                    ON pri.pri_no = prid.pri_no 
            WHERE pri.total = 0  
            GROUP BY pri.pri_no 
            LIMIT 4000 ";
    
    return db_query($sql, "Could not pri_get_pr_issues_total");
}

function cs_update_pri_pr_issues_header_total($pri_no, $total){    
    $sql = "UPDATE ".TB_PREF."purchase_requisition_issues   
                SET total = ".db_escape($total)."   
            WHERE pri_no = ".db_escape($pri_no);
    
    db_query($sql, "could not cs_update_pri_pr_issues_header_total");
}

function cs_update_custom_script_update_pr_issues_header_total(){
    $message = "==================Script Sarted==========================";
    write_custom_script_log("custom_script_update_pr_issues_header_total", $message);
    
    $pr_issue_total_result = pri_get_pr_issues_total();
    $recs = db_num_rows($pr_issue_total_result);
    write_custom_script_log("custom_script_update_pr_issues_header_total", $recs." Records selected");
    
    while($row = db_fetch($pr_issue_total_result)){
        cs_update_pri_pr_issues_header_total($row['pri_no'], $row['total']);
        
        $n = db_num_affected_rows();
        if($n==1){
            $message = "Purchase Requisition Issue #".$row['pri_no']." total updated.";
        }else{
            $message = "Could not update Purchase Requisition Issue #".$row['pri_no']." total.";
        }
        write_custom_script_log("custom_script_update_pr_issues_header_total", $message);
    }
    
    $message = "------------------Script Completed----------------------------";
    write_custom_script_log("custom_script_update_pr_issues_header_total", $message);
}

?>