<?php

function sc_calculate_department_project_summary($calculation_type, $group_code, 
                                        $month_id, $from_date, $to_date, $continue_calculation)
{
    $started_on = date('Y-m-d H:i:s');
    $last_completed_project_id = $parent_calculation_id = 0;
    
    
    if(strlen($group_code) > 0 && $group_code != '-1'){
        if($continue_calculation){
            $last_completed_project_id = get_last_completed_value($month_id, $group_code, $calculation_type);
            if(!($last_completed_project_id > 0)){
                $last_completed_project_id = 0;
            }
//            $lc_project = get_project_record($last_completed_project_id);
//            $last_processing_department_id = $lc_project['department_id'];
//            $department = get_list_value($last_processing_department_id); 
        }
        else{
            $department = get_listvalue_by_code("DEPARTMENTS", $group_code);
        }
        $msg = sc_calculate_project_summary($parent_calculation_id, $started_on, $calculation_type, $group_code, 
                                            $month_id, $from_date, $to_date, $continue_calculation, $last_completed_project_id);
        if($msg['success'] !== true){
            display_error($msg['message']);
            return;
        }
    }
    else{
        $parent_calculation_id = add_monthly_summary_calculation_run($month_id, $calculation_type, $group_code, $started_on);
        
        if($continue_calculation){
            $last_completed_project_id = get_last_completed_value($month_id, $group_code, $calculation_type);
            if($last_completed_project_id > 0){
                $lc_project = get_project_record($last_completed_project_id);
                $last_processing_department_id = $lc_project['department_id'];
                $last_processing_department = get_listvalue_by_id($lc_project['department_id']);
                $result = get_list_values_range_on_value_name("DEPARTMENTS", $last_processing_department['value_name']); 
                
                $continue_msg = "Continue All Department Calculation started. Department: "
                        .$last_processing_department['value_name']
                        .", Project: ".$lc_project['project_id']." - ".$lc_project['description'];
                write_summary_calculation_log($parent_calculation_id, $continue_msg);
            }
            else{
                $last_completed_project_id = 0;
                $last_processing_department_id = 0;
                $result = get_all_list_values("DEPARTMENTS");   
                
                $all_dep_msg = "Continue All Department Calculation started for all the departments";
                write_summary_calculation_log($parent_calculation_id, $all_dep_msg);
            }
        }
        else{
            $result = get_all_list_values("DEPARTMENTS");  
            $new_all_dep_msg = "New All Department Calculation started.";
            write_summary_calculation_log($parent_calculation_id, $new_all_dep_msg);
        }
    }
    
    
    while ($department = db_fetch($result)) {    
        $msg = sc_calculate_project_summary($parent_calculation_id, $started_on, $calculation_type, $department['value_code'], 
                                        $month_id, $from_date, $to_date, $continue_calculation, $last_completed_project_id);
        if($msg['success'] !== true){
            display_error($msg['message']);
            return;
        }
    }

    if($parent_calculation_id > 0){
        if($continue_calculation){
            $parent_completion_msg = "Continued All Department Calculation completed.";
        }
        else{
            $parent_completion_msg = "New All Department Calculation completed.";
        }
        complete_monthly_summary_calculation_run($parent_calculation_id, get_summary_calculation_elapsed_time($started_on), $parent_completion_msg);
        write_summary_calculation_log($parent_calculation_id, "All department caculation completed.");
    }

}

function sc_calculate_project_summary($parent_calculation_id, $parent_calculation_started_on, $calculation_type, $group_code, 
                                        $month_id, $from_date, $to_date, $continue_calculation, $last_completed_project_id)
{
    $department_calculation_started_on = date('Y-m-d H:i:s');
    $calculation_id = add_monthly_summary_calculation_run($month_id, $calculation_type, $group_code, $department_calculation_started_on);    
    
    $department = get_listvalue_by_code("DEPARTMENTS", $group_code);
    
    if($parent_calculation_id > 0){
        $start_msg = "Department ".$group_code." - ".$department['value_name']." Started. Parent run: ".$parent_calculation_id.". Department run: ".$calculation_id;
        write_summary_calculation_log($parent_calculation_id,$start_msg);
    }
    else{
        $start_msg = "Department ".$group_code." - ".$department['value_name']." Started";
    }
    
    write_summary_calculation_log($calculation_id,$start_msg);
    write_summary_calculation_log($calculation_id,"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
    
    
    //$calculation_run = get_monthly_summary_calculation_run($calculation_id);
    
    $project_id = 0;
    $project_description = "No project selected";
    
    if($continue_calculation){
        $last_project_id = $last_completed_project_id;
    }
    else{
        $last_project_id = 0;        
    }
    
    
    
    $project = get_monthly_summary_projects_next_project($department['id'], $last_project_id);
    if(isset($project['project_id']) && $project['project_id'] > 0){
        $project_id = $project['project_id'];
        $project_description = $project['description'];
    }
    
    delete_monthly_summary_projects($month_id, $department['id'], $calculation_type, $last_project_id);
    
    while ($project_id > 0)
    {
        write_summary_calculation_log($calculation_id, "================ Project ".$project_id." : ".$project_description." Started");
        $project_calculation_started_on = date('Y-m-d H:i:s');
//        $total = get_material_issues_summary($project_id, $from_date, $to_date);
//        add_to_monthly_summary_projects($month_id, $project['department_id'], $project_id, 
//                                        $calculation_type, "MATERIAL_ISSUES", $total, 
//                                        $calculation_id);
        calculate_monthly_project_expenses_summary($month_id, $project['department_id'], $project_id, 
                                        $calculation_type, $calculation_id, $from_date, $to_date);
        
        calculate_monthly_project_sales_expenses_summary($month_id, $project['department_id'], $project_id, 
                                        $calculation_type, $calculation_id, $from_date, $to_date);
        
        calculate_monthly_project_invoices_summary($month_id, $project['department_id'], $project_id, 
                                        $calculation_type, $calculation_id, $from_date, $to_date);
        
        calculate_monthly_project_collections_summary($month_id, $project['department_id'], $project_id,                                         
                                        $calculation_type, $calculation_id, $from_date, $to_date);
        
        calculate_monthly_project_payments_summary($month_id, $project['department_id'], $project_id,                                         
                                        $calculation_type, $calculation_id, $from_date, $to_date);

        
        if($parent_calculation_id > 0){
            update_monthly_summary_calculation_calculated_value($parent_calculation_id, $project_id);
        }
        update_monthly_summary_calculation_calculated_value($calculation_id, $project_id);
        
        write_summary_calculation_log($calculation_id, "================ Seconds: ".get_summary_calculation_elapsed_time($project_calculation_started_on)
                                                        ." Project ".$project_id." : ".$project_description." Complteted");
        
        $next_project = get_monthly_summary_projects_next_project($department['id'], $project_id);
        if(isset($next_project['project_id']) && $next_project['project_id'] > 0){
            $project_id = $next_project['project_id'];
            $project_description = $next_project['description'];
        }
        else{
            $project_id = -1;
            $project_description = "Project id -1";
            if($parent_calculation_id > 0){
                update_monthly_summary_calculation_calculated_value($parent_calculation_id, $project_id);
            }
            update_monthly_summary_calculation_calculated_value($calculation_id, $project_id);        
        }
        
        $timeout_limit = 300;
        
        if($parent_calculation_id > 0){
            $parent_seconds = get_summary_calculation_elapsed_time($parent_calculation_started_on);
//            $parent_seconds *= 100;
            if($parent_seconds > $timeout_limit){ // took too long. Exit.                
                write_summary_calculation_log($parent_calculation_id,"????????????????????????????????");
                $parent_message = "Department ".$group_code." - ".$department['value_name']
                                                ." Timed out. (".$parent_seconds." seconds)."
                                                ." Department run ".$calculation_id."."
                                                ." Project: ".$project_id." - ".$project_description;
                write_summary_calculation_log($parent_calculation_id, $parent_message);
                complete_monthly_summary_calculation_run($parent_calculation_id, $parent_seconds, $parent_message);

                $dep_seconds = get_summary_calculation_elapsed_time($department_calculation_started_on);
                $dep_message = "Department ".$group_code." - ".$department['value_name']."."
                                            ." Parent calculation run of this (".$parent_calculation_id.") timed out. (".$dep_seconds." seconds)."
                                                ." Department run ".$calculation_id."."
                                                ." Project: ".$project_id." - ".$project_description;
                write_summary_calculation_log($calculation_id,"????????????????????????????????");
                write_summary_calculation_log($calculation_id,$dep_message);
                complete_monthly_summary_calculation_run($calculation_id, $dep_seconds, $dep_message);
                
                return array("success"=>false, "message"=>$dep_message);
            }
        }
        else{
            $dep_seconds = get_summary_calculation_elapsed_time($department_calculation_started_on);
            if($dep_seconds > $timeout_limit){ // took too long. Exit.
                write_summary_calculation_log($calculation_id,"????????????????????????????????");
                $message = "Department ".$group_code." - ".$department['value_name']." Timed out. (".$dep_seconds." seconds)";
                write_summary_calculation_log($calculation_id,$message);
                complete_monthly_summary_calculation_run($calculation_id, get_summary_calculation_elapsed_time($department_calculation_started_on), $message);
                
                return array("success"=>false, "message"=>$message);
            }
        }
    }
    
    write_summary_calculation_log($calculation_id,"&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
    if($parent_calculation_id > 0){
        $msg = "Department ".$group_code." - ".$department['value_name']." Completed. Parent run : ".$parent_calculation_id.". Department run: ".$calculation_id;
        write_summary_calculation_log($parent_calculation_id,$msg);
    }
    else{
        $msg = "Department ".$group_code." - ".$department['value_name']." Completed";
    }
    write_summary_calculation_log($calculation_id, $msg);
    complete_monthly_summary_calculation_run($calculation_id, get_summary_calculation_elapsed_time($department_calculation_started_on), "Completed");
    
    return array("success"=>true, "message"=>"Calculation completed");

}

       
function calculate_monthly_project_sales_expenses_summary($month_id, $department_id, $project_id, 
                                        $calculation_type, $calculation_id, $from_date, $to_date)
{
    $total = get_sales_despatches_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SALES_DESPATCHES, $total, $calculation_id);
    
    $total = get_sales_despatch_returns_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SALES_DESPATCH_RETURNS, $total, $calculation_id);
    
}

function calculate_monthly_project_payments_summary($month_id, $department_id, $project_id, 
                                        $calculation_type, $calculation_id, $from_date, $to_date)
{
//    $total = get_project_collections_summary($project_id, $from_date, $to_date);
//    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, "PROJECT_COLLECTIONS", $total, $calculation_id);

//    $total = get_project_invoice_receipts_summary($project_id, $from_date, $to_date);
//    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, "PROJECT_INVOICE_RECEIPTS", $total, $calculation_id);
//    
//    $total = get_project_credit_note_payments_summary($project_id, $from_date, $to_date);
//    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, "PROJECT_CREDIT_NOTE_PAYMENTS", $total, $calculation_id);    
//    
    $total = get_project_subcontractor_invoice_payments_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SUBCONTRACTOR_INVOICE_PAYMENTS, $total, $calculation_id);
    
    $total = get_project_subcontractor_credit_note_returns_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SUBCONTRACTOR_CREDIT_NOTE_RETURNS, $total, $calculation_id);
    
//    $total = get_project_cf_iou_payments($project['project_id'], $month_b['month_begin_date'], $month_e['month_end_date']);
//    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, "SUBCONTRACTOR_CREDIT_NOTE_RETURNS", $total, $calculation_id);
    
//    $total = get_project_cf_iou_advance_payments($project['project_id'], $month_b['month_begin_date'], $month_e['month_end_date']);
//    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, "SUBCONTRACTOR_CREDIT_NOTE_RETURNS", $total, $calculation_id);    
        
    $total = get_project_utility_bill_payments_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_UTILITY_BILL_PAYMENTS, $total, $calculation_id);
    
    $total = get_project_utility_bill_credit_note_returns_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_UTILITY_BILL_CREDIT_NOTE_RETURNS, $total, $calculation_id);
    
    $transport = get_project_transport_payments_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_TRANSPORT_PAYMENTS, $total, $calculation_id);    
    
    $total = get_project_direct_purchase_payments_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SUPPLIER_INVOICE_PAYMENTS, $total, $calculation_id);
    
    $total = get_project_direct_purchase_credit_note_returns_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SUBCONTRACTOR_CREDIT_NOTE_RETURNS, $total, $calculation_id);   
}


function calculate_monthly_project_collections_summary($month_id, $department_id, $project_id, 
                                        $calculation_type, $calculation_id, $from_date, $to_date)
{
//    $total = get_project_collections_summary($project_id, $from_date, $to_date);
//    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, "PROJECT_COLLECTIONS", $total, $calculation_id);

    $total = get_project_invoice_receipts_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_PROJECT_INVOICE_RECEIPTS, $total, $calculation_id);
    
    $total = get_project_credit_note_payments_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_PROJECT_CREDIT_NOTE_PAYMENTS, $total, $calculation_id);    
    
    
}

function calculate_monthly_project_invoices_summary($month_id, $department_id, $project_id, 
                                        $calculation_type, $calculation_id, $from_date, $to_date)
{
    
    $total = get_project_invoices_certified_summary(ST_PROJECT_INVOICE, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_PROJECT_INVOICES_CERTIFIED, $total, $calculation_id);

    $total = get_project_credit_notes_certified_summary(ST_PROJECT_CREDIT_NOTE, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_PROJECT_CREDIT_NOTES_CERTIFIED, $total, $calculation_id);

    
//    $total = get_project_invoices_pending_summary(ST_PROJECT_INVOICE, $project_id, $from_date, $to_date);
//    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_PROJECT_INVOICES_PENDING, $total, $calculation_id);

    $total = get_project_credit_notes_pending_summary(ST_PROJECT_CREDIT_NOTE, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_PROJECT_CREDIT_NOTES_PENDING, $total, $calculation_id);
    
}


function calculate_monthly_project_expenses_summary($month_id, $department_id, $project_id, 
                                        $calculation_type, $calculation_id, $from_date, $to_date){
    
    $total = get_material_issues_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_MATERIAL_ISSUES, $total, $calculation_id);

    $total = -get_material_returns_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_MATERIAL_RETURNS, $total, $calculation_id);

    
    $total = get_purchase_requisition_issues_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_PR_ISSUES, $total, $calculation_id);
    
    $total = -get_site_material_return_summary(ST_SUPPCREDIT, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SITE_MATERIAL_RETURNS, $total, $calculation_id);


    
    $total = get_subcontractor_invoices_summary(ST_SUBCONTRACTOR_INVOICE, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SUBCONTRACTOR_INVOICES, $total, $calculation_id);

    $total = get_subcontractor_credit_notes_summary(ST_SUBCONTRACTOR_CREDIT_NOTE, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SUBCONTRACTOR_CREDIT_NOTES, $total, $calculation_id);

    

    $total = get_vehicle_running_chart_entries_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_VEHICLE_RUNNING_CHART, $total, $calculation_id);

    
    
    $total = 0;
    $result = get_petty_cash_payments($project_id, $from_date, $to_date);
    while($inv = db_fetch($result))
    {
         $total += $inv["payment_amount"];
    }
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_I_OWE_YOU_PAYMENTS, $total, $calculation_id);
    
    $total = get_iou_advances_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_I_OWE_YOU_ADVANCES, $total, $calculation_id);

    
    
    $total = get_utility_bills_summary(ST_UTILITY_BILLS, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_UTILITY_BILLS, $total, $calculation_id);

    $total = -get_utility_bill_credit_notes_summary(ST_UTILITY_BILL_CREDIT_NOTE, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_UTILITY_BILL_CREDIT_NOTES, $total, $calculation_id);

    

    $total = get_miscellaneous_project_costs_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_UTILITY_BILL_CREDIT_NOTES, $total, $calculation_id);

    
    
    $total = get_tool_usage_charges_summary($project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_TOOL_USAGE_CHARGES, $total, $calculation_id);

    
//    if($project_id =='107'){
//        $rr=77;
//    }
    $total = get_material_purchased_invoices(ST_SUPPINVOICE, $project_id, $from_date, $to_date);    
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SUPPLIER_INVOICES, $total, $calculation_id);
        
    $total = get_material_purchased_credit_notes(ST_SUPPCREDIT, $project_id, $from_date, $to_date);
    add_to_monthly_summary_projects($month_id, $department_id, $project_id, $calculation_type, SCVT_SUPPLIER_CREDIT_NOTES, $total, $calculation_id);
    //display_wip_costs_summary($project_id, $from_date, $to_date, $project_total_commitment);  
    
}


