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


function can_process_pa_details($line_id, $code, $description)
{
    $error_prefix = "Project BOQ Item "."[".$code."]". " - ".$description;
    
    if(!check_num($line_id.'_previous_qty', 0)){
        $msg = "Previous quantity cannot be negative.";
        $message = $error_prefix." - ".$msg;
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!check_num($line_id.'_cumulative_qty', 0)){
        $msg = "Cumulative quantity cannot be negative.";
        $message = $error_prefix." - ".$msg;
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if(!check_num($line_id.'_cert_cuml_qty', 0)){
        $msg = "Certify Cumulative quantity cannot be negative.";
        $message = $error_prefix." - ".$msg;
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    $cumulative_qty = input_num($line_id.'_cumulative_qty');
    $previous_qty = input_num( $line_id.'_previous_qty');
        
    if($cumulative_qty < $previous_qty){
        $msg = "Cumulative quantity cannot be smaller than previous quantity.";
        $message = $error_prefix." - ".$msg;
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    return array("success" => true, "message" => "");  
}

function display_project_payment_application_details($project_id, $pa_id, $boq_group_id, 
                                                        $site_id, $ord_date)
{
    if(!($boq_group_id > 0)){
        $boq_group_id = 0;
    }
    
    if(!($site_id > 0)){
        $site_id = 0;
    }
    
//    $boq_item_group = get_project_boq_item_group_record($boq_group_id);
//    display_heading2("BOQ Items of group [".$boq_item_group['code']."] ".$boq_item_group['description']);

    hidden('payment_application_id', $pa_id);
    hidden('BOQGroupId', $boq_group_id);
    
    br();
    
    global $Ajax, $project_billing_types; 
    $Ajax->activate('project_payment_application_details');
    
    div_start('project_payment_application_details');
//  display_heading('Expenses');    
        
    start_table(TABLESTYLE, "width=90%");
    $result_a = get_project_payment_application_boq_details($project_id, $pa_id, $boq_group_id);
    
//  $quantity = $result_a['quantity'];
//  $date = $result_a['date'];    

    $th = array(_("Code"), _("Description"), "Type",
                _("Unit"), "Rate", _("Max Qty"), "Max Amount",_("Work Done"), _("Cuml. Qty"),
                _("Pre. Qty"), _("Curr. Qty"), _("Cert. Cuml. Qty"), "");               
   
    table_header($th);

    $j = 1;
    $k=0; //row colour counter
    
    $work_done_total = $previous_total = $current_total = $completed_total = $cert_cuml_total = $max_amount_total = 0;
    while($pa_row = db_fetch($result_a))
    {
        alt_table_row_color($k);
        
//        label_cell($pa_row["id"], "align=right");
//        label_cell($pa_row["pad_id"], "align=right");      
        label_cell($pa_row["code"]);
        label_cell($pa_row["description"]);       
        label_cell($project_billing_types[$pa_row["billing_type"]]);  
        label_cell($pa_row["unit"]); 
        
        $rate = $pa_row["rate"];
        amount_decimal_cell($rate); 
        label_cell($pa_row["max_quantity"], "align=right");  
        $max_amount = $pa_row["rate"] * $pa_row["max_quantity"];
        amount_decimal_cell($max_amount); 
        $max_amount_total += $max_amount;
        
        $total_work_done = get_total_work_done_upto_pa_date($pa_row['id'], $site_id, $ord_date);
        
        if($total_work_done > 0){
            label_cell($total_work_done, "align=right");  
            $work_done_total += $total_work_done * $rate;
        }
        else{
            label_cell('');
        }
        
        if($pa_row['cumulative_qty'] > 0){
            $_POST[$pa_row["id"]."_cumulative_qty"] = $pa_row['cumulative_qty'];
        }
        amount_cells(null, $pa_row["id"]."_cumulative_qty");    
        $completed_total += input_num($pa_row["id"]."_cumulative_qty") * $rate;
                        
        $payment_detail = get_project_payment_application_detail($pa_id, $pa_row["id"]);
        if($payment_detail){           
            $_POST[$pa_row["id"]."_previous_qty"] = $payment_detail["previous_qty"]; 
            $_POST[$pa_row["id"]."_quantity"] = $payment_detail["quantity"];  
           // $_POST[$pa_row["id"]."_total_work_done"] = $pa_row["total_work_done"];                
        }
        else{
            if(!isset($_POST[$pa_row["id"]."_previous_qty"])){
                $_POST[$pa_row["id"]."_previous_qty"] = 0.00; 
            }
            if(!isset($_POST[$pa_row["id"]."_quantity"])){
                $_POST[$pa_row["id"]."_quantity"] = 0.00;     
            }
        }
        
        $previous_total += input_num($pa_row["id"]."_previous_qty") * $rate;
//        $current_total += input_num($pa_row["id"]."_quantity") * $rate;
        
        if($pa_row['previous_qty'] > 0){
            $_POST[$pa_row["id"]."_previous_qty"] = $pa_row['previous_qty']; 
        }
        amount_cells(null, $pa_row["id"]."_previous_qty");  
        
        $curr_qty = $_POST[$pa_row["id"]."_cumulative_qty"] - $_POST[$pa_row["id"]."_previous_qty"];
        $current_total += $curr_qty * $rate;
        
        label_cell(number_format($curr_qty, 2), "align=right");
        
        
        if($pa_row['certi_cuml_qty'] > 0){
            $_POST[$pa_row["id"]."_cert_cuml_qty"] = $pa_row['certi_cuml_qty'];
        }
        amount_cells(null, $pa_row["id"]."_cert_cuml_qty");  
        $cert_cuml_total += input_num($pa_row["id"]."_cert_cuml_qty") * $rate;
        
        hidden($pa_row["id"]."_"."boq_item_id", $pa_row["id"]);

        check_cells(null, $pa_row["id"]."_check_item");       
        
        end_row();
    }
    
    start_row();
    label_cell('Totals: ',"colspan=6 align=right");
    amount_cell($max_amount_total, true);
    amount_cell($work_done_total, true);
    amount_cell($completed_total, true);
    amount_cell($previous_total, true);
    amount_cell($current_total, true);
    amount_cell($cert_cuml_total, true);
    
    
    
    end_row();
    
    hidden('PAId', $pa_id);
    end_table(1);
    div_end();
    
    submit_center_first('Update_project_payment_application_details', _("Update Items"), '', 'default');
    submit_center_last('Delete_project_payment_application_details', _("Delete Items"), '', 'default');

}

function build_pa_boq_groups_array(&$items, $project_id, $pa_no)
{
    $loop_count = 1;
    
    if($pa_no > 0){
        $boq_groups_top_q = get_top_level_boq_groups_from_pa($project_id, $pa_no);
    }
    else{
        $boq_groups_top_q = get_top_level_boq_groups_new_pa($project_id);
    }
    
    
    while ($boq_groups_top = db_fetch($boq_groups_top_q))
    {
        $line = array();
        $line['id'] = $boq_groups_top['id']; 
        $line['code'] = $boq_groups_top['code']; 
        $line['description'] = $boq_groups_top['description']; 

        $line['parent_id'] = $boq_groups_top['parent_id']; 
        $line['group_total'] = $boq_groups_top['group_total']; 
        $line['calculated_on'] = $boq_groups_top['calculated_on']; 

        $line['child_groups_total'] = $boq_groups_top['child_groups_total']; 
        $line['child_groups_taxes_total'] = $boq_groups_top['child_groups_taxes_total']; 
        $line['boq_items_total'] = $boq_groups_top['boq_items_total']; 
        $line['boq_item_taxes_total'] = $boq_groups_top['boq_items_taxes_total']; 
        
        $line['depth'] = $loop_count;
        
        $child_groups_array = add_child_boq_groups_to_array($boq_groups_top['id'], $pa_no, $loop_count);
        if($child_groups_array){
            foreach ($child_groups_array as $child_group){
                $line['child_groups_total'] += $child_group['child_groups_total'];
                $line['child_groups_taxes_total'] += $child_group['child_groups_taxes_total'];
                
                $line['boq_items_total'] += $child_group['boq_items_total'];
                $line['boq_item_taxes_total'] += $child_group['boq_item_taxes_total'];
            }      
            $line['children'] = $child_groups_array;
        }
        else{
            $line['children'] = array();
        }       

        $items[] = $line;
        
//        $boq_groups_array[] = $line;
//        if($child_items_array){
//            $line['children'] = $child_items_array;            
//        }
//        else{
//            $line['children'] = array();
//        }
        
//        if($billing_item_top['type'] == 0){ //Valid billing item
//            $pi_item = get_project_invoice_detail_item($pi_no, $billing_item_top['id'], $billing_item_top['invoice_line_id']);
//            if(isset($pi_item['id']) &&  $pi_item['id'] > 0){
//                $line['pi_line_id'] = $pi_item['id']; 
//                $line['line_total'] = $pi_item['unit_price'] * (1 - $pi_item['discount']/100)* $pi_item['quantity'];
//                $line['unit'] = $pi_item['unit'];
//                $line['discount'] = $pi_item['discount'];
//                $line['tax_group_name'] = $pi_item['tax_group_name'];
//                $line['taxes'] = $pi_item['item_taxes'];
//                $line['unit_price'] = $pi_item['unit_price']; 
//                $line['list_price'] = $pi_item['list_price']; 
//                $line['quantity'] = $pi_item['quantity']; 
//            }
//        }
//        else{
//            if($child_items_array){
//                foreach ($child_items_array as $child_item){
//                    if(isset($child_item['line_total'])){
//                        $line['line_total'] += $child_item['line_total'];
//                        $line['taxes'] += $child_item['taxes'];
//                    }
//                }            
//            }
        }
        
//        if(isset($line)){
//            $items[] = $line;
//        }
        
    
}


function add_child_boq_groups_to_array($parent_id, $pa_no, &$loop_count)
{
    $loop_count++;
    if($loop_count > 20){
        //Stop infinite recursive loop
        return null;
    }
    $boq_groups_array = array();

        
    
    if($pa_no > 0){
        $child_boq_groups_q = get_child_boq_groups_from_pa($parent_id, $pa_no);
    }
    else{
        $child_boq_groups_q = get_child_boq_groups_new_pa($parent_id);
    }
    
    while ($boq_group = db_fetch($child_boq_groups_q))
    {
        $line = array();
        $line['id'] = $boq_group['id']; 
        $line['code'] = $boq_group['code']; 
        $line['description'] = $boq_group['description']; 

        $line['parent_id'] = $boq_group['parent_id']; 
        $line['group_total'] = $boq_group['group_total']; 
        $line['calculated_on'] = $boq_group['calculated_on']; 
        $line['child_groups_total'] = $boq_group['child_groups_total']; 
        $line['child_groups_taxes_total'] = $boq_group['child_groups_taxes_total']; 
        $line['boq_items_total'] = $boq_group['boq_items_total']; 
        $line['boq_item_taxes_total'] = $boq_group['boq_items_taxes_total']; 

        $line['depth'] = $loop_count;
        
//        if($billing_item['type'] == 0){ //Valid billing item
//            $pi_item = get_project_invoice_detail_item($pi_no, $billing_item['id'], $billing_item['invoice_line_id']);
//            if(isset($pi_item['id']) &&  $pi_item['id'] > 0){
//                $line['has_items'] = true;
//                $line['pi_line_id'] = $pi_item['id']; 
//                $line['line_total'] = $pi_item['unit_price'] * (1 - $pi_item['discount']/100)* $pi_item['quantity'];
//                $line['unit'] = $pi_item['unit'];
//                $line['discount'] = $pi_item['discount'];
//                $line['tax_group_name'] = $pi_item['tax_group_name'];
//                $line['taxes'] = $pi_item['item_taxes'];
//                $line['unit_price'] = $pi_item['unit_price']; 
//                $line['list_price'] = $pi_item['list_price']; 
//                $line['quantity'] = $pi_item['quantity']; 
//            }
//        }
        
        $child_groups_array = add_child_boq_groups_to_array($boq_group['id'], $pa_no, $loop_count);
        if($child_groups_array){
            foreach ($child_groups_array as $child_group){
                $line['child_groups_total'] += $child_group['child_groups_total'];
                $line['child_groups_taxes_total'] += $child_group['child_groups_taxes_total'];
                
                $line['boq_items_total'] += $child_group['boq_items_total'];
                $line['boq_item_taxes_total'] += $child_group['boq_item_taxes_total'];
            }      
            $line['children'] = $child_groups_array;
        }
        else{
            $line['children'] = array();
        }       

        $boq_groups_array[] = $line;
    }
    
    $loop_count--;

    return $boq_groups_array;

}


function display_ppa_boq_item_group($boq_groups, $payment_application_id)
{
//    alt_table_row_color($k);
    start_row();
//    label_cell($boq_groups["display_order"]);

    $name = spaces(($boq_groups["depth"]-1) * 10)."[".$boq_groups["code"]."] ".$boq_groups["description"];
    label_cell($name);
//    amount_decimal_cell($boq_groups["child_groups_total"]); 
//    amount_decimal_cell($boq_groups["child_groups_taxes_total"]); 
    amount_decimal_cell($boq_groups["boq_items_total"]); 
    amount_decimal_cell($boq_groups["boq_item_taxes_total"]); 

//    $entry_date = sql2date($_POST['tran_date']);

    $s = get_project_trans_view_str(ST_PROJECT_PAY_APP_BOQ_ITEMS, $payment_application_id."|".$boq_groups['id'], "Details");
    label_cell($s);
//    button_cell("Edit".$boq_groups['id'], "Details");
    end_row();
    
    foreach ($boq_groups['children'] as $myrow) {
        display_ppa_boq_item_group($myrow, $payment_application_id);
    }
}

function recalculate_poject_payment_application($pa_id)
{
    delete_payment_application_boq_groups($pa_id);
    
    $pah = get_project_payment_application_header($pa_id);
    $boq_groups_q = get_project_boq_item_groups($pah['project_id']);
    while($boq_group = db_fetch($boq_groups_q)){          
        recalculate_poject_payment_application_boq_group($pa_id, $boq_group['id']);
    }
    
    recalculate_poject_payment_application_boq_group($pa_id, 0);
    
    $value_total = $tax_total = 0;
    $pa_totals = get_project_pa_boq_groups_total($pa_id);
    
    update_payment_application_totals($pa_id, $pa_totals['boq_items_total'], $pa_totals['boq_items_taxes_total']);
}

function recalculate_poject_payment_application_boq_group($pa_id, $boq_group_id)
{
    $pa_boq_group_items_total = $pa_boq_group_items_taxes_total = 0;
    
    $pa_boq_items_q = get_project_payment_application_details($pa_id, $boq_group_id);
    while($pa_boq_item = db_fetch($pa_boq_items_q)){          
        $boq_item_total = ($pa_boq_item["previous_qty"] + $pa_boq_item["quantity"]) * $pa_boq_item["rate"];
        $pa_boq_group_items_total += $boq_item_total;
        $pa_boq_group_items_taxes_total += $pa_boq_item["taxes"] ;
    }
    
//    update_project_pa_boq_group_item_totals($pa_boq_group_id, $pa_boq_group_items_total, $pa_boq_group_items_taxes_total);
    if($pa_boq_group_items_total > 0){
        create_payment_application_boq_item_group($pa_id, $boq_group_id, $pa_boq_group_items_total, $pa_boq_group_items_taxes_total);
    }
}


function save_project_payment_application($project_id, $pa_id, $boq_group_id, $site_id)
{             
    $spa_msg = save_payment_application($pa_id, get_post('project_id'), get_post('customer_id'), 
                                        get_post('branch_code'), $_POST['reference'], $_POST['tran_date']); 
    
    if($spa_msg['success'] !== true){
        return $spa_msg;
    }
    
    $pa_id = $spa_msg['trans_no'];
    $max_pa_id = get_latest_payment_application_no($project_id);
    $max_order_no = $max_pa_id['max_order_no'];
    
    $update_boq_item = false;
    if($pa_id == $max_order_no){
        $update_boq_item = true;
    }
    
    $pah = get_payment_application_header_record($pa_id);
    $tran_date =  $pah['ord_date'];        

    $count = 0;
    $batch_q = get_project_payment_application_boq_details($project_id, $pa_id, $boq_group_id);

    while ($pa_boq_item = db_fetch($batch_q))
    {               
        if(isset($_POST[$pa_boq_item["id"]."_check_item"]) && $_POST[$pa_boq_item["id"]."_check_item"] == 1){
            
            if($pad_msg = can_process_pa_details($pa_boq_item["id"], $pa_boq_item['code'], $pa_boq_item['description'])){
                if($pad_msg["success"] !== true){
                    return array("success" => false, "focus_to" => $pad_msg['focus_to'], "message" => $pad_msg['message']);        
                }
            }
            
            $previous_qty = input_num($pa_boq_item["id"].'_previous_qty');
            $cumulative_qty = input_num($pa_boq_item["id"]."_cumulative_qty"); 
            $certi_cuml_qty = input_num($pa_boq_item["id"]."_cert_cuml_qty"); 


            $current_qty = $cumulative_qty - $previous_qty;
                    
            $n = write_project_payment_application_detail($pa_id, $pa_boq_item, $site_id,
                                                            $current_qty, $previous_qty,
                                                            $cumulative_qty, $certi_cuml_qty,
                                                            $tran_date, $pah['rate_include_taxes'],
                                                            $update_boq_item);  
            
                                     
            unset($_POST[$pa_boq_item["id"]."_check_item"]);
            
            $count++;
        }
        else{
            continue;
        }        
    }
    if($count > 0){
        return array("success" => true, "trans_no" => $pa_id, "message" => "Selected items have been updated.");  
    }
    else{
        return array("success" => false, "trans_no" => $pa_id, "message" => "No items updated.");  
    }
}
 
function remove_project_payment_application_details($pa_id, $boq_group_id)
{   
    $count = 0;
    $batch_q = get_project_payment_application_details($pa_id, $boq_group_id);

    while ($pa_boq_item = db_fetch($batch_q))
    {
        if(isset($_POST[$pa_boq_item["id"]."_check_item"]) && $_POST[$pa_boq_item["id"]."_check_item"] == 1){                            
            if($pa_boq_item['pad_id']>0){
                $n = delete_project_payment_application_detail($pa_boq_item['pad_id']);   
            }
           
            unset($_POST[$pa_boq_item["id"]."_check_item"]);
            $count++;
        }
        else{
            continue;
        }        
    }        
     
    if($count > 0){
        return array("success" => true, "message" => "Selected items have been deleted.");  
    }
    else{
        return array("success" => false, "message" => "No items deleted.");  
    }  
}

function display_pa_total($pa_id, $boq_groups)
{
    $value_total = $tax_total = 0;
    
    $no_group = get_ppa_no_boq_item_group($pa_id);
    label_cell("BOQ Items with no BOQ Item Group");
//    amount_decimal_cell($boq_groups["child_groups_total"]); 
//    amount_decimal_cell($boq_groups["child_groups_taxes_total"]); 
    amount_decimal_cell($no_group["boq_items_total"]); 
    amount_decimal_cell($no_group["boq_items_taxes_total"]); 
    
    $s = get_project_trans_view_str(ST_PROJECT_PAY_APP_BOQ_ITEMS, $pa_id."|0", "Details");
    label_cell($s);
    
    foreach ($boq_groups as $boq_group) {
        $value_total += $boq_group['boq_items_total'];
        $tax_total += $boq_group['boq_item_taxes_total'];
    }
    
    $value_total += $no_group["boq_items_total"];
    $tax_total += $no_group["boq_items_taxes_total"];
    
    start_row();
    label_cell("Total:", "align=right");
    amount_cell($value_total, true);
    amount_cell($tax_total, true);
    end_row();
}



?>