<?php

function cs_get_outstanding_prs(){
    
    $sql = "SELECT DISTINCT pr.pr_no, 
                    pr.approval_status 
            FROM ".TB_PREF."purchase_requisitions pr 
                JOIN ".TB_PREF."purchase_requisition_details prd 
                    ON pr.pr_no = prd.requisition_id 
            WHERE prd.quantity > (prd.issued_qty - prd.returned_qty)  
                AND pr.pr_complete = 0 
                AND (pr.approval_status = ".db_escape(AS_APPROVED)." OR pr.approval_status = ".db_escape(AS_ISSUED).") 
                AND pr.pr_no NOT IN (SELECT DISTINCT ut.tran_no FROM ".TB_PREF."updated_tasks ut WHERE ut.tran_type = ".db_escape(ST_PURCH_REQ).") 
            LIMIT 1000 ";
    
    
//    $sql = "SELECT DISTINCT tran_no pr_no 
//            FROM ".TB_PREF."task_cost_allocations   
//            WHERE tran_type = ".db_escape(ST_PURCH_REQ)." 
//                AND task_id NOT IN (SELECT DISTINCT task_id FROM ".TB_PREF."updated_tasks)
//            LIMIT 100 ";
    
    return db_query($sql, "cs_get_pr_lines");
    
}


function cs_update_pr_allocations(){
    $message = "==================Script Sarted==========================";
    write_custom_script_log("cs_update_pr_allocations", $message);
    
    $opr_result = cs_get_outstanding_prs();
    $recs = db_num_rows($opr_result);
    write_custom_script_log("cs_update_pr_allocations", $recs." PRs selected");
    
    while($row = db_fetch($opr_result)){
        if(in_array($row['pr_no'], array(2)) ){
            continue;
        }
        cs_update_pr_allocation($row['pr_no']);
        
    }
        
    $message = "------------------Script Completed----------------------------";
    write_custom_script_log("cs_update_pr_allocations", $message);
}


function cs_update_pr_allocation($pr_no){
    
    $message = "PR No: ".$pr_no;
    write_custom_script_log("cs_update_pr_allocations", $message);
        
    $pr_details = get_pr_details($pr_no);
    
    while ($myrow = db_fetch($pr_details))
    {
        $a['row_id'] = $myrow['id'];
        $a['stock_id'] = $myrow['item_code'];
        $a['task_id'] = $myrow['task_id'];
        $a['requested_qty'] = $myrow['requested_unit_qty'] * $myrow['req_unit_conv_factor'] ;
        $a['high_value_item'] = 0;
        
//        $item_cost = $myrow['standard_cost'];
        $item_cost = $myrow['estimate_price'] / $myrow['req_unit_conv_factor'] ;
        $a['reference_cost'] = $item_cost;
        $a['standard_cost'] = $item_cost;
        $a['total_issued_qty'] = $myrow['issued_qty'];
        $a['qty'] = 0;
        $a['charging_cost'] = 0;
        $pr_details_array[] = $a;
        
    }

    begin_transaction();
    
    $tasks_summary = calculate_task_remaining_totals($pr_details_array);
    
    $created_by = $_SESSION['wa_current_user']->user;
    
    $apc_msg = cs_allocate_to_tasks(ST_PURCH_REQ, $pr_no, 
                                $tasks_summary, $created_by);
    if($apc_msg['success'] !== true)
    {
        cancel_transaction();
        $message = "PR No: ".$pr_no." ".$apc_msg['message'];
        write_custom_script_log("cs_update_pr_allocations", $message);
        return array("success" => $apc_msg['success'], "tran_no" => $pr_no, "message" => $message);
        
    }
    
    commit_transaction();
    
    return array("success" => $apc_msg['success'], "message" => "");
}

function cs_allocate_to_tasks($tran_type, $tran_no, 
                        &$tasks_summary, $current_user_id)
{
    $in_string = "";
    
    foreach ($tasks_summary as &$task) {
        if(!(isset($task['task_id']) && $task['task_id'] > 0)){
            array("success" => false, "message" => "No task selected for one or more items.");
        }
        $atet_msg = cs_allocate_to_each_task($tran_type, $tran_no, $task, $current_user_id);
        if($atet_msg['success'] !== true){
            return $atet_msg;
        }
        
        if($in_string == ""){
            $in_string .= $task['task_id'];
        }
        else{
            $in_string .= ",".$task['task_id'];
        }
    }

    return $atet_msg;
}

function cs_allocate_to_each_task($tran_type, $tran_no, 
                        &$task, $current_user_id)
{
        //$new_allocation_amount = number_format($task['cost'], 2);
        $new_allocation_amount = $task['remaining_cost'];
                
        //$task = get_task_record($task_id);
        $task_id = $task['task_id'];
        
        if(!$task){
            $msg['success'] = false;
            $msg['message'] = "Could not find details of the project task [".$task_id."]. "
                                        . "Please contact your system administrator";
            return $msg;
        }

        $task_cost_allocation_detail = get_task_allocation_record($tran_type, $tran_no, $task_id);    
        if(!$task_cost_allocation_detail){
            $exisiting_total_cost_allocation = get_task_total_budget_allocated($task_id);
            $new_total_cost_allocation = $exisiting_total_cost_allocation + $new_allocation_amount;
//            $uptca_msg = update_task_total_allocation($tran_type, $tran_no, 
//                                        $task_id, $new_total_cost_allocation, 
//                                        $current_user_id, $task['row_state']);
//            
//            $task['row_state'] = db_new_row_state($task['row_state']);
//            
//            if($uptca_msg['success'] !== true){
//                return $uptca_msg;
//            }

            $atad_msg = add_task_allocation_detail($task_id, $tran_type, $tran_no, 
                                    $new_allocation_amount, $new_total_cost_allocation, $current_user_id);
            
            if($atad_msg['success'] !== true){
                return $atad_msg;
            }
            
            cs_add_updated_task_allocation_detail($task_id, $tran_type, $tran_no, $new_allocation_amount);

            return $atad_msg;
            
        }
        else{
            $allocation_adjustment = $new_allocation_amount - $task_cost_allocation_detail['amount'];

            $exisiting_total_cost_allocation = get_task_total_budget_allocated($task_id);
            $new_total_cost_allocation = $exisiting_total_cost_allocation + $allocation_adjustment;
            if($new_total_cost_allocation < 0){
                $new_total_cost_allocation = 0;
            }
//            $uptca_msg = update_task_total_allocation($tran_type, $tran_no, 
//                                        $task_id, $new_total_cost_allocation, 
//                                        $current_user_id, $task['row_state']);
//            
//            $task['row_state'] = db_new_row_state($task['row_state']);
//            if($uptca_msg['success'] !== true){
//                return $uptca_msg;
//            }
            
            cs_add_updated_task_allocation_detail($task_id, $tran_type, $tran_no, $new_allocation_amount);
            
            if($task_cost_allocation_detail['amount'] == $new_allocation_amount){
                return array('success' => true, 'message' => 1);
            }

            $upc_msg = update_task_allocation_detail($task_cost_allocation_detail['id'], $task_id, $tran_type, 
                                        $tran_no, $new_allocation_amount, $new_total_cost_allocation, 
                                        $current_user_id);   
            if($upc_msg['success'] !== true){
                return $upc_msg;
            }
            
            

            return $upc_msg;
             
        }
}

function cs_add_updated_task_allocation_detail($task_id, $tran_type, $tran_no, $amount)
{
        
    	$sql = "INSERT INTO ".TB_PREF."updated_tasks(
                        task_id, tran_type, 
                        tran_no, amount)
    		VALUES (".db_escape($task_id).", ".db_escape($tran_type).", "
                        .db_escape($tran_no).", ".db_escape($amount).")";
        
        $text = "could not add task cost allocation";
    	db_query($sql, $text);

}

