<?php
$page_security =  'SA_MONTHLY_PROJECT_COSTS';
$path_to_root = "../..";
include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/ui/ui_input.inc");

include_once($path_to_root . "/gl/includes/db/monthly_project_costs_db.inc");

include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/projects/includes/db/projects_db.inc");
include_once($path_to_root . "/admin/db/list_values_db.inc");
include_once($path_to_root . "/admin/db/months_db.inc");

include_once($path_to_root . "/dashboard/includes/db/summary_projects_db.inc");
include_once($path_to_root . "/dashboard/includes/db/summary_payrolls_db.inc");
include_once($path_to_root . "/dashboard/includes/db/summary_employee_work_db.inc");

include_once($path_to_root . "/includes/approval_functions.inc");



$js = "";
if ($SysPrefs->use_popup_windows)
    $js .= get_js_open_window(900, 500);
if (user_use_date_picker())
    $js .= get_js_date_picker();

simple_page_mode(true);

include_once($path_to_root . "/projects/includes/project_boq_item_costs.inc");



page(_($help_context = "Project BOQ Item Components"), true, false, false, $js);



global $selected_id, $Ajax;

if (isset($_GET["trans_no"]))
{
	$_POST["trans_no"] = $_GET["trans_no"];
}

if (isset($_POST["trans_no"]))
{
	$trans_no = $_POST["trans_no"];
}

$sep_pos = strpos($trans_no, "|");
$mpc_no = substr($trans_no, 0, $sep_pos);
$department_id = substr($trans_no, $sep_pos+1);


function get_mpc_calculated_base_total($mpch, $department_id)
{
    $month_id = $mpch['month_id'];    
    $department = get_listvalue_by_id($department_id);
    $department_codes_in = db_escape($department['value_code']);
    
    switch ($mpch['base_total_type']) {
        case MPCBT_MANUAL_COST:
            return 0;
            
        case MPCBT_DEPARTMENT_SALARY_COST:
            $company_codes_in = "'SAW','SAWC','LPS','VEE','VEEC'";        
            $salary_components_in = "'TAKEHOME_BASIC', 'TAKEHOME_INCENTIVE'";
            $salary_components_in = SCVT_TOTAL_SALARY_COST;
            return get_summary_payrolls_value_total($month_id, $company_codes_in, $department_codes_in, $salary_components_in);
            
        case MPCBT_EMPLOYEE_COST:
            return get_summary_employee_work_departmet_total($month_id, $department_id);
            
//        case MPCBT_PROJECT_RECEIPTS:
//            $receipts_types_in = "'PROJECT_INVOICES', 'PROJECT_CREDIT_NOTES', 'PROJECT_INVOICES_PENDING', 'PROJECT_CREDIT_NOTES_PENDING'";
//            return get_summary_projects_departmets_total($month_id, $department_codes_in, $receipts_types_in);
//            
//        case MPCBT_PROJECT_COLLECTION:
//            return get_summary_projects_departmets_total($month_id, $department_codes_in, $receipts_types_in);
//            return 0 ;
            
        

        default:
            return "Unknown base total type";
    }
}

function get_monthly_project_cost_project_calculation_value($mpch, $line_project_id)
{   
    $month_id = $mpch['month_id'];
    $project_ids_in = db_escape($line_project_id);
    
    switch ($mpch['base_total_type']){
        case MPCBT_MANUAL_COST:
            return 0;
            
        case MPCBT_DEPARTMENT_SALARY_COST:
            return 0 ;
                
//        case MPCBT_PROJECT_EXPENSES:
//            $expenses_types_in = "'MATERIAL_ISSUES', 'MATERIAL_RETURNS', 'SUPPLIER_INVOICES', 'SUPPLIER_CREDIT_NOTES', 'SUBCONTRACTOR_INVOICES', 
//                          'SUBCONTRACTOR_CREDIT_NOTES', 'VEHICLE_RUNNING_CHART', 'I_OWE_YOU_PAYMENTS', 'I_OWE_YOU_ADVANCES', 'UTILITY_BILLS',
//                          'UTILITY_BILL_CREDIT_NOTE', 'MISCELLANEOUS_PROJECT_COSTS'";
//            return get_summary_projects_total($month_id, $project_ids_in, $expenses_types_in); 
//            
//        case MPCBT_PROJECT_RECEIPTS:
//            $receipts_types_in = "'PROJECT_INVOICES', 'PROJECT_CREDIT_NOTES', 'PROJECT_INVOICES_PENDING', 'PROJECT_CREDIT_NOTES_PENDING'";
//            return get_summary_projects_total($month_id, $project_ids_in, $receipts_types_in);
//            
//        case MPCBT_PROJECT_COLLECTION:
//            return get_summary_projects_departmets_total($month_id, $department_codes_in, $receipts_types_in);
//            return 0 ;
            
        

        default:
            return "Unknown base total type";
    }
}

function get_monthly_project_cost_project_distribution_value($mpch, $line_project_id)
{   
    $month_id = $mpch['month_id'];
    $project_ids_in = db_escape($line_project_id);
    
    switch ($mpch['distribution_type']){
        case MPCDT_MANUAL:
            return 0;
        case MPCDT_PROJECT_EXPENSES:
            $expenses_types_in = "'MATERIAL_ISSUES', 'MATERIAL_RETURNS', 'SUPPLIER_INVOICES', 'SUPPLIER_CREDIT_NOTES', 'SUBCONTRACTOR_INVOICES', 
                          'SUBCONTRACTOR_CREDIT_NOTES', 'VEHICLE_RUNNING_CHART', 'I_OWE_YOU_PAYMENTS', 'I_OWE_YOU_ADVANCES', 'UTILITY_BILLS',
                          'UTILITY_BILL_CREDIT_NOTE', 'MISCELLANEOUS_PROJECT_COSTS'";
            return get_summary_projects_total($month_id, $project_ids_in, $expenses_types_in); 
            
        case MPCDT_PROJECT_RECEIPTS:
            $receipts_types_in = "'PROJECT_INVOICES', 'PROJECT_CREDIT_NOTES', 'PROJECT_INVOICES_PENDING', 'PROJECT_CREDIT_NOTES_PENDING'";
            return get_summary_projects_total($month_id, $project_ids_in, $receipts_types_in);
            
        case MPCDT_PROJECT_COLLECTION:
//            return get_summary_projects_departmets_total($month_id, $department_codes_in, $receipts_types_in);
            return 0 ;
            
        case MPCDT_PROJECT_TOTAL_COST:
            $project = get_project_record($line_project_id);
            return $project['approved_cost_budgets_total'] + $project['approved_overhead_budgets_total'];
            
        case MPCDT_EQUALLY:
            return input_num('applying_total') ;
            
        case MPCDT_SAME_VALUE:
            return input_num('applying_total') ;
            
        case MPCDT_EMPLOYEE_COST:
            return get_summary_employee_work_project_total($month_id, $line_project_id);

        default:
            return "Unknown base total type";
    }
}

function fill_monthly_project_costs_array(&$mpc_array, $mpch, $department_id)
{
    $result = get_department_projects($department_id);
    while ($project = db_fetch($result)) {  
        $calculation_value = get_monthly_project_cost_project_calculation_value($mpch, $project['project_id']); 
        $distribution_value = get_monthly_project_cost_project_distribution_value($mpch, $project['project_id']); 
                
        $id = 0;
        $mpcd = get_monthly_project_cost_detail($mpch['id'], $project['project_id']);
        if(isset($mpcd['id']) && $mpcd['id'] > 0){
            $id = $mpcd['id'];
            $mpcd_value = $mpcd['value'];
            $task_id = $mpcd['task_id'];
            $comment = $mpcd['comment'];
        }
        else {
            $mpcd_value = $task_id = 0;
            $comment = '';
        }
        
        $line = array(
            "id" =>  $id,
            "project_id" =>  $project['project_id'],
            "project_description" =>  $project['description'],
            "department_id" =>  $project['department_id'],
            "task_id" =>  $task_id,
            "calculation_value" =>  $calculation_value,
            "distribution_value" =>  $distribution_value,
            "value" =>  $mpcd_value,
            "comment" =>  $comment 
        );
        
        $mpc_array[] = $line;
    }
}

function calculate_monthly_project_cost_distribution(&$mpc_array, $mpch)
{
    $total = $count = 0;
    $mpc_no = $mpch['id'];
    
    foreach ($mpc_array as $line) {
        $suffix = $mpc_no."_".$line['project_id'];
        if(isset($_POST['select_'.$suffix]) && $_POST['select_'.$suffix] == 1){
            $total += $line['distribution_value'];
            $count++;
        }
    }
    
    $applying_total = input_num('applying_total');
    
    foreach ($mpc_array as &$line) {
        $suffix = $mpc_no."_".$line['project_id'];
        if(isset($_POST['select_'.$suffix]) && $_POST['select_'.$suffix] == 1){
            
            
            switch ($mpch['distribution_type']){
                case MPCDT_MANUAL:
                    $line['value'] = 0;
                    break;
                
                case MPCDT_PROJECT_EXPENSES:
                case MPCDT_PROJECT_RECEIPTS:
                case MPCDT_PROJECT_COLLECTION:
                case MPCDT_PROJECT_TOTAL_COST:
                case MPCDT_EMPLOYEE_COST:
                    $value = $applying_total/$total*$line['distribution_value'];
                    $line['value'] = number_format($value,2);
                    break;

                case MPCDT_EQUALLY:
                    $value = $applying_total/$count;
                    $line['value'] = number_format($value,2);
                    break;

                case MPCDT_SAME_VALUE:
                    $value = $applying_total;
                    $line['value'] = number_format($value,2);
                    break;

                default:
                    return "Unknown base total type";
            }
        }
    }
    
    
}



function display_monthly_project_cost_details($mpc_array, $mpch, $department_id, $distribute=0, $select_all=0, $deselect_all=0)
{

    $mpc_no = $mpch['id'];
            
    start_table(TABLESTYLE, "width=90%");

    $th = array(_("Id"), _("Project"), "Distribution Value", _("Cost"), "Budget", _("Comment"), "");

    table_header($th);
    $k = 0;
    
    foreach ($mpc_array as $line) {
        $suffix = $mpc_no."_".$line['project_id'];
        
        alt_table_row_color($k);
        
        $line_id_text = "";
        if($line['id'] > 0){
            $line_id_text = $line['id'];
        }
        label_cell($line_id_text);
        
        $project_name = get_project_formatted_name($line['project_id']);
        label_cell($project_name);
//        label_cell(number_format($line['calculation_value'], 2), "align=right");
        label_cell(number_format($line['distribution_value'], 2), "align=right");

        if($distribute){
            $mpcd_value = $line['value'];
        }
        else{
            if(isset($_POST['cost_'.$suffix])){
                $mpcd_value = input_num('cost_'.$suffix);
            }
            else{              
                $mpcd = get_monthly_project_cost_detail($mpc_no, $line['project_id']);
                if(isset($mpcd['id']) && $mpcd['id'] > 0){
                    $mpcd_value = $mpcd['value'] ;
                }
                else {
                    $mpcd_value = 0;
                }
            }
        }
        
        
        $_POST['cost_'.$suffix] = $mpcd_value;
        amount_cells(null, 'cost_'.$suffix);

        if(!(isset($_POST['task_'.$suffix]))){
            $_POST['task_'.$suffix] = $line['task_id'] ;
        }        
        tasks_list_cells(null, 'task_'.$suffix, $line['project_id']);
        
        if(!(isset($_POST['comment_'.$suffix]))){
            $_POST['comment_'.$suffix] = $line['comment'] ;
        } 
        text_cells(null, 'comment_'.$suffix, null, 30, 500);
        
        if($line['id'] > 0){
            $_POST['select_'.$suffix] = true;
        }
        
        if($select_all){
            $_POST['select_'.$suffix] = true;
        }
        elseif($deselect_all){
            $_POST['select_'.$suffix] = false;
            unset($_POST['select_'.$suffix] );
        }        
        
        check_cells(null, 'select_'.$suffix);
        end_row();
    }

    end_table();
    
    
    
}


function build_monthly_project_costs_saving_array(&$mpc_array, $mpch, $department_id)
{
    $mpc_no = $mpch['id'];
    $count = 0;
    
    $result = get_department_projects($department_id);
    while ($project = db_fetch($result)) {  
        $suffix = $mpc_no."_".$project['project_id'];
        
        if(isset($_POST['select_'.$suffix]) && $_POST['select_'.$suffix] == 1){
            $selected = true;
            $count++;
        }
        else{
            $selected = false;
        }
        
        $cost = input_num('cost_'.$suffix);
        $task_id = $_POST['task_'.$suffix];
        $comment = $_POST['comment_'.$suffix];
        
        $line = array(
            "project_id" =>  $project['project_id'],
            "project_description" =>  $project['description'],
            "department_id" =>  $project['department_id'],
            "task_id" =>  $task_id,
            "cost" =>  $cost,
            "comment" =>  $comment,
            "selected" =>  $selected  
        );
        
        
        $mpc_array[] = $line;
    }
    
    if(!($count > 0)){
        return array("success" => false, "set_focus" => "", "message" => "No lines selected.");
    }
    else{
        return array("success" => true, "set_focus" => "", "message" => "");
    }
}

function can_process_monthly_project_cost_details($mpc_array, $mpch)
{

    $mpc_no = $mpch['id'];
    
//    $mpc = get_monthly_project_costs_header($mpc_no);
    if(!($mpch['approval_status'] == AS_NEW || $mpch['approval_status'] == AS_WITH_THE_APPROVER || 
            $mpch['approval_status'] == AS_AWAITING_APPROVAL || $mpch['approval_status'] == AS_BACK_TO_ORIGINATOR)){
        $message = ("This document status does not allow further updating.");
        $set_focus = '';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }

    $current_user_id = $_SESSION['wa_current_user']->user;
    $ced_msg = can_edit_document(ST_MONTHLY_PROJECT_COSTS, $mpch['project_id'], $mpch['next_approval_group_id'] , $current_user_id, $mpch['created_by'], $mpc_no);
    if($ced_msg['success'] !== true){
        return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
    }

    foreach ($mpc_array as $line) {
        if($line['selected'] == false){
            continue;
        }
        
        $suffix = $mpc_no."_".$line['project_id'];
        
        $error_prefix = "Project - ".$line['project_description']." : ";
        
        if(!($line['task_id'] > 0)){
            $message = $error_prefix."Please select a budget.";
            $set_focus = "task_id_".$suffix;
            return array("success" => false, "set_focus" => $set_focus, "message" => $message);
        }
        
        if(!(check_num2($line['cost'], 0.00001))){
            $message = $error_prefix."Cost should be numeric and greater than zero.";
            $set_focus = "cost_".$suffix;
            return array("success" => false, "set_focus" => $set_focus, "message" => $message);
        }
    }
    
    return array("success" => true, "set_focus" => "", "message" => "");
}

function save_monthly_project_costs_details($mpc_no, $department_id, $base_total_type, $distribution_type, 
                                            $calculated_value, $applied_value)
{
    $mpc_array = array();
    
    $mpch = get_monthly_project_costs_header_record($mpc_no);
    $old_row_state = $mpch['row_state'];
    
    $ba_msg = build_monthly_project_costs_saving_array($mpc_array, $mpch, $department_id);
    if($ba_msg["success"] !== true){
        return $ba_msg;
    }
    
    $cp_msg = can_process_monthly_project_cost_details($mpc_array, $mpch);
    if($cp_msg["success"] !== true){
        return $cp_msg;
    }
    
    
    
    foreach ($mpc_array as $line) {
        
        delete_monthly_project_costs_detail($mpc_no, $line['project_id']);
        
        if($line['selected'] == true){
            add_monthly_project_costs_detail($mpc_no, $line['project_id'],
                                        $line['cost'], $line['task_id'], $line['comment']);
        }
    }
    
    $mpcd_total = get_monthly_project_costs_details_total($mpc_no, $department_id);
    
    $department = get_monthly_project_costs_department($mpc_no, $department_id);
    if(isset($department['id']) && $department['id'] > 0){
        update_monthly_project_costs_department($department['id'], $base_total_type, $distribution_type, 
                                        $calculated_value, $applied_value, $mpcd_total);
    }
    else{
        add_monthly_project_costs_department($mpc_no, $department_id, $base_total_type, $distribution_type, 
                                        $calculated_value, $applied_value, $mpcd_total);
    }
    
    $mpc_total = get_monthly_project_costs_departments_total($mpc_no);
    
    $n = update_monthly_project_costs_header_total($mpc_no, $mpc_total, $old_row_state);
    if($n != 1){
        cancel_transaction();
        return array("success" => false, "set_focus" => "", "message" => "Another user has updated this monthly project costs."); 
    }

    commit_transaction();
    return array("success" => true, "set_focus" => "", "message" => "");
}


if(isset($_POST['Save_MPC_Details'])){
    $smpc_msg = save_monthly_project_costs_details($mpc_no, $department_id, $_POST['base_total_type'], $_POST['distribution_type'], 
                                                input_num('calculated_value'), input_num('applying_total'));
    if($smpc_msg["success"] !== true){
        display_error($smpc_msg["message"]);
        set_focus($smpc_msg["set_focus"]);
    }
    else{
        display_notification("Monthly project costs details have been saved.");
    }
    
}

$distribute = 0;
if(isset($_POST['distribute_values'])){
    $distribute = 1;
}

$select_all = 0;
if(isset($_POST['Select_All'])){
    $select_all = 1;
}

$deselect_all = 0;
if(isset($_POST['DeSelect_All'])){
    $deselect_all = 1;
}


start_form();



hidden('trans_no', $trans_no);

global $monthly_project_costs_base_totals, $monthly_project_costs_distribution_types;

$mpch = get_monthly_project_costs_header($trans_no);
$base_total = get_mpc_calculated_base_total($mpch, $department_id);

$month = get_month($mpch['month_id']);
$department = get_listvalue_by_id($department_id);
$mpc_department = get_monthly_project_costs_department($mpc_no, $department_id);
if (! (isset($_POST['applying_total']) && $_POST['applying_total'] > 0) && isset($mpc_department['id']) && $mpc_department['id'] > 0) {
    $_POST['applying_total'] = $mpc_department['applied_value'];
}
start_outer_table(TABLESTYLE2, "width=50%"); // outer table
//start_table(TABLESTYLE, "width=00%");
//$th = array(_("Lot Reference"), _("Available Qty"),_("Qty"));
//table_header($th);

table_section(1, "0%");
table_section_title("Details");
label_row("Month: ", $month['description']);
label_row("Department", $department['value_name']);

table_section(2, "0%");
table_section_title("Calculation");
label_row("Total Of: ", $monthly_project_costs_base_totals[$mpch['base_total_type']]);
hidden('base_total_type', $mpch['base_total_type']);
label_row("Calculated Value", number_format($base_total,2));
hidden('calculated_value', $base_total);

table_section(3, "0%");
table_section_title("Distribution");
label_row("Distribute On: ", $monthly_project_costs_distribution_types[$mpch['distribution_type']]);
hidden('distribution_type', $mpch['distribution_type']);
amount_row("Distribution Value", "applying_total");

//end_table();
end_outer_table(1); // outer table


submit_center_first('distribute_values', "Distribute", '', 'default', '');
    submit('Select_All', 'Select All', true, '', 'default', '');
    submit_center_last('DeSelect_All', "Deselect All", '', 'default', '');

br();
//        global $Ajax;
        
$Ajax->activate('mpc_dep_details');
div_start('mpc_dep_details');

$mpc_array = array();
fill_monthly_project_costs_array($mpc_array, $mpch, $department_id);
calculate_monthly_project_cost_distribution($mpc_array, $mpch);
display_monthly_project_cost_details($mpc_array, $mpch, $department_id, $distribute, $select_all, $deselect_all);
div_end();
        
//inactive_control_row($th);

br();

submit_center_first('Save_MPC_Details', "Save", '', 'default', '');

br(2);

echo "<center>";
//submit("Submit", "submit");
echo "<input type='button' name='cancel' class='inputsubmit' onclick='goBack()' value='Close'/>";
echo "</center>";

br();

end_form();

//js_get_data_in_parent("guid","parent_guid");
//js_get_data_in_parent($parent,"parent_item_qty");
//js_get_data_in_parent($parent_unit,"parent_unit");
//show_quantity("parent_item_qty");
end_page();
