<?php

function display_job_cost_inquiry_selecting_parameters() {
    global $Ajax;
    
    if (! isset($_POST['stock_id'])) {
        $_POST['stock_id'] = get_global_stock_item();
    }

    $Ajax->activate('sm_filter');
    div_start('sm_filter');

        start_table(TABLESTYLE_NOBORDER);
            start_row();
                project_list_cells(_("Project:"), 'project_id', null, _('Select a project'), true);   
                $project_jobs_array = build_project_jobs_array($_POST['project_id']);
                custom_values_list_cells('Job:', 'job_id', $project_jobs_array, null, '', true);
            end_row();
        end_table();

        start_table(TABLESTYLE_NOBORDER);
            start_row();
                $tran_types_array = build_job_cost_tran_types_array();
                custom_values_list_cells('Trans Type:', 'type', $tran_types_array, null, 'All transaction types', true);
                
                stock_costable_items_list_cells(_("Item:"), 'stock_id', null, 'Select an item', true);
                    if (strlen($_POST['stock_id']) > 0) {
                        set_global_stock_item($_POST['stock_id']);
                    }
                locations_list_cells(_("Location:"), 'location', null, true, true);

                submit_cells('SearchItemTrans', _("Display"),'', _('Refresh Inquiry'), 'default');
            end_row();
        end_table(2);

    div_end();
}

function build_project_jobs_array($project_id) {
    $project_jobs_array = array();
    
        $result = get_project_sites($project_id);
            while ($row = db_fetch($result)) {
                $project_jobs_array[$row['id']] = $row['description'];
            }
    
        return $project_jobs_array;
}

function build_job_cost_tran_types_array() {
    global $systypes_array;
    
    $tran_types_array = array();
    
        $tran_types_array[ST_MATERIAL_ISSUE] = $systypes_array[ST_MATERIAL_ISSUE];
        $tran_types_array[ST_MATERIAL_RETURN] = $systypes_array[ST_MATERIAL_RETURN];
        $tran_types_array[ST_INVENTORY_RECEIPT] = $systypes_array[ST_INVENTORY_RECEIPT];
        $tran_types_array[ST_INVENTORY_ISSUE] = $systypes_array[ST_INVENTORY_ISSUE];
        $tran_types_array[ST_PR_ISSUE] = $systypes_array[ST_PR_ISSUE];
        $tran_types_array[ST_PR_RETURN] = $systypes_array[ST_PR_RETURN];
        $tran_types_array[ST_DAILY_ITEM_ISSUE] = $systypes_array[ST_DAILY_ITEM_ISSUE];
        $tran_types_array[ST_DAILY_ITEM_RETURN] = $systypes_array[ST_DAILY_ITEM_RETURN];
        $tran_types_array[ST_RAW_MATERIAL_ISSUE] = $systypes_array[ST_RAW_MATERIAL_ISSUE];
        $tran_types_array[ST_RAW_MATERIAL_RETURN] = $systypes_array[ST_RAW_MATERIAL_RETURN];
        $tran_types_array[ST_JOB_COST_ADDITION] = $systypes_array[ST_JOB_COST_ADDITION];
        $tran_types_array[ST_JOB_COST_DEDUCTION] = $systypes_array[ST_JOB_COST_DEDUCTION];
        $tran_types_array[ST_DAILY_TOOL_RETURN] = $systypes_array[ST_DAILY_TOOL_RETURN];
        $tran_types_array[ST_TOOL_USAGE_CHARGE] = $systypes_array[ST_TOOL_USAGE_CHARGE];
        
        return $tran_types_array;
}

function display_job_cost_inquiry_details($project_id, $job_id, $type, $stock_id, $location) {
    $item = get_item($stock_id);
        if (is_array($item)) {
            $item_unit = get_item_unit($item['units']);

            start_table(TABLESTYLE2);
                echo '<h3>Cost unit (Base Unit) of this item is "'.text_bold($item_unit['name']).'"</h3>';
            end_table(1);
        }
        
        start_table(TABLESTYLE, "width=95%");
            $th = array(_("ID"), _("Type"), _("#"), _("Date"), _("Location"), _("Item"), _("Unit"), _("Qty"), ("Unit Cost"), _("Total Cost"));
            table_header($th);
            
                $total_cost = 0;
                        
                display_material_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_material_return_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_inventory_receipt_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_inventory_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_pr_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_pr_return_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_daily_item_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_daily_item_return_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_raw_material_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                display_raw_material_return_cost_details($project_id, $job_id, $type, $stock_id, $location, $total_cost);
                
                display_utility_bill_cost_details($project_id, $job_id, $type, $total_cost);
                display_utility_bill_cn_cost_details($project_id, $job_id, $type, $total_cost);
                
                display_i_owe_you_cost_details($project_id, $job_id, $type, $total_cost);
                
                display_daily_tool_return_cost_details($project_id, $job_id, $type, $total_cost); 
                display_tool_usage_charges_details($project_id, $job_id, $type, $total_cost); 
                
//                if(!(($type > 0) || (strlen($stock_id) > 0) || (strlen($location) > 0))) {
                    display_job_cost_addition_details($project_id, $job_id, $type, $total_cost);
                    display_job_cost_deduction_details($project_id, $job_id, $type, $total_cost);
//                }
                                
                start_row();
                    label_cell(text_bold('Total Value of Transactions'), "align=right colspan=9");
                    label_cell(text_bold(number_format2($total_cost, 2)), "align=right");
                end_row();
                    
                if(!(($type > 0) || (strlen($stock_id) > 0) || (strlen($location) > 0))) {
                    
                    display_job_cost_inquiry_summary($total_cost, $job_id);
                }

                
                
            end_table(1);
}

function display_job_cost_inquiry_summary($total_cost, $job_id) {
    
    $site = get_project_site_details($job_id);
    
    $percent_completed = $site['percent_completed'];
    
    start_row();
        label_cell(text_bold('Completed'), "align=right colspan=9");
        label_cell(text_bold(number_format2($percent_completed, 2))."%", "align=right");
    end_row();
    
    if($site['cost_1_active'] == true){
        start_row();
            $cost_1_name = $site['cost_1_name']." (".number_format2($site['cost_1'], 2).")";
            label_cell(text_bold($cost_1_name), "align=right colspan=9"); 
            $cost_1 = $site['cost_1'] * $percent_completed / 100;
            label_cell(text_bold(number_format2($cost_1, 2)), "align=right");
            $total_cost += $cost_1;
        end_row();
        
    }
    if($site['cost_2_active'] == true){
        start_row();
            $cost_2_name = $site['cost_2_name']." (".number_format2($site['cost_2'], 2)."%)";
            label_cell(text_bold($cost_2_name), "align=right colspan=9"); 
            $cost2 = $total_cost * ($site['cost_2']/100);
            label_cell(text_bold(number_format2($cost2, 2)), "align=right");
            $total_cost += $cost2;
        end_row();
        
    }
    if($site['cost_3_active'] == true){
        start_row();
            $cost_3_name = $site['cost_3_name']." (".number_format2($site['cost_3'], 2).")";
            label_cell(text_bold($cost_3_name), "align=right colspan=9"); 
            $cost_3 = $site['cost_3'] * $percent_completed / 100;
            label_cell(text_bold(number_format2($cost_3, 2)), "align=right");
            $total_cost += $cost_3;
        end_row();
        
    }
    
    start_row();
        label_cell(text_bold('Total Cost'), "align=right colspan=9");
        label_cell(text_bold(number_format2($total_cost, 2)), "align=right");
    end_row();
    
    start_row();
        $estimated_cost = 'Prorated Estimated Cost'." (".number_format2($site['estimated_cost'], 2).")";
        label_cell(text_bold($estimated_cost), "align=right colspan=9");
        $estimated_cost = $site['estimated_cost'] * $percent_completed / 100;
        label_cell(text_bold(number_format2($estimated_cost, 2)), "align=right");
    end_row();
    
    start_row();        
        label_cell(text_bold('Saving / Over Spent'), "align=right colspan=9");
        $profit_loss = $estimated_cost - $total_cost;
        if($percent_completed == 0){
            $profit_loss_text = "Can not calculate. Completed percentage is 0";
        }elseif($site['estimated_cost'] == 0){
            $profit_loss_text = "Can not calculate. Estimated cost is 0";
        }else{        
            $profit_loss_percentage = ($estimated_cost - $total_cost) / $estimated_cost * 100;
            $profit_loss_text = number_format($profit_loss,2)." (".number_format(abs($profit_loss_percentage), 2)."%)";
        }
//        label_cell(text_bold($profit_loss_text), "align=right style=foreground-color:#8cd4be"); 
        if($profit_loss > 0){
            label_cell(text_bold($profit_loss_text), "align=right");
        }else{
            label_cell(text_bold('<font color="red">'.$profit_loss_text.'</red>'), "align=right");
        }
    end_row();
                    
}


function display_job_cost_transaction_type_details($type, $result, &$total_cost) {
    global $systypes_array;
    
        if(db_num_rows($result) == 0){
            return;
        }
        start_row();
            label_cell(text_bold($systypes_array[$type].'s'), "align=center colspan=10 style=background-color:#8cd4be");
        end_row();

        $dec = 2;
        $k = $trans_type_total_cost = $previous_trans_no = 0;
            while($row = db_fetch($result)) {
                alt_table_row_color($k);
                    $trandate = sql2date($row["tran_date"]);
                    $type = $row["type"];
                    $type_name = $systypes_array[$type];
                    $tran_qty = abs($row["tran_qty"]);
                    $conversion_factor = $row["convertion_factor"];
                    $standard_cost = $row["standard_cost"];
                    $tran_unit_cost = $standard_cost * $conversion_factor;
                    
                    $trans_no = $row["trans_no"];

                    label_cell($row["trans_id"], "align=center");
                    label_cell($type_name);
                    label_cell(get_trans_view_str($type, $row["trans_no"]), "align=center");
                    label_cell($trandate, "align=center");
                    label_cell($row["location_name"]);
                    
                    if ($type == ST_DAILY_TOOL_RETURN) {
                        $item_description = $row["asset_code"].' - '.$row["description"];
                        
                        if ($previous_trans_no != $trans_no) {
                            $header = get_daily_tool_return_header_with_issue_header_record_by_return_trans_no($trans_no);
                            $issued_date = sql2date($header['iss_tran_date']);
                            $returned_date = sql2date($header['tran_date']);
                                $num_dates_ = date_diff2($returned_date, $issued_date, 'd');
                                $num_dates = ($num_dates_ > 0) ? $num_dates_ : 1;
                        }
                            
                            $tran_unit_name = "$num_dates days";
                            $rate = $tran_unit_cost = $row["rate"];
                            $line_total_cost = ($rate * $num_dates * $tran_qty);
                    } elseif ($type == ST_I_OWE_YOU_BATCH) {
                        $item_description = $row["bill_no"].' - '.$row["expence_description"];
                        
                        $tran_unit_name = "";
                        $no_of_units = $tran_qty = 0;
                        $rate = 0;
                        
//                        $taxes = $row["taxes"];
//                        $ubh_total = $row["total"];
//                        $tax_factor = ($taxes + $ubh_total)/$ubh_total;
                        $tax_factor = 1;
                        $tran_unit_cost = $row["approved_amount"] * $tax_factor;
                        $line_total_cost = $tran_unit_cost; 
                        
                    } elseif ($type == ST_TOOL_USAGE_CHARGE) {
                        $item_description = $row["asset_code"].' - '.$row["description"];
                        $tran_unit_name = "Days * Qty";
                        $no_of_units = $tran_qty = $row["no_of_units"];
                        $rate = $tran_unit_cost = $row["rate"];
                        $line_total_cost = ($rate * $no_of_units); 
                        
                    } elseif ($type == ST_UTILITY_BILLS || $type == ST_UTILITY_BILL_CREDIT_NOTE) {
                        $item_description = $row["bill_reference"].' - '.$row["description"];
                        $tran_unit_name = "";
                        $no_of_units = $tran_qty = 0;
                        $rate = 0;
                        
//                        $taxes = $row["taxes"];
//                        $ubh_total = $row["total"];
//                        $tax_factor = ($taxes + $ubh_total)/$ubh_total;
                        $tax_factor = 1;
                        $tran_unit_cost = $row["amount"] * $tax_factor;
                        $line_total_cost = $tran_unit_cost;
                    } else {
                        $item_description = get_stock_item_formatted_name($row["stock_id"], $row["editable"], $row["sm_description"], 
                                                                          $row["item_transaction_description"]);
                        
                        $tran_unit_name = $row["tran_unit_name"];
                        
                        $line_total_cost = ($tran_unit_cost * $tran_qty);
                    }
                    label_cell($item_description);
                    label_cell($tran_unit_name, 'align=center');
                    
                    if($tran_qty != 0){
                        label_cell(number_format($tran_qty, $dec), 'align=right');
                    }else{
                        label_cell('');
                    }
                    label_cell(number_format2($tran_unit_cost, $dec), "align=right");
                    
                    label_cell(number_format2($line_total_cost, $dec), "align=right");
                    
                    $trans_type_total_cost += $line_total_cost;
                    
                end_row();
                
                    $previous_trans_no = $trans_no;
            }
            
            start_row();
                label_cell(text_bold('Total for '.$systypes_array[$type].'s :'), "align=right colspan=9");
                label_cell(text_bold(number_format2($trans_type_total_cost, $dec)), "align=right");
            end_row();
            
            start_row();
                vertical_space('height=20px colspan=10');
            end_row();
            
            $total_cost += $trans_type_total_cost;
}

function display_material_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_MATERIAL_ISSUE) {
        return;
    }
    
        $result = get_material_issue_cost_details($project_id, $job_id, $stock_id, $location);

        display_job_cost_transaction_type_details(ST_MATERIAL_ISSUE, $result, $total_cost);
}

function display_material_return_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_MATERIAL_RETURN) {
        return;
    }
    
        $result = get_material_return_cost_details($project_id, $job_id, $stock_id, $location);

        display_job_cost_transaction_type_details(ST_MATERIAL_RETURN, $result, $total_cost);
}

function display_inventory_receipt_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_INVENTORY_RECEIPT) {
        return;
    }
    
        $result = get_inventory_receipt_cost_details($project_id, $job_id, ST_INVENTORY_RECEIPT, $stock_id, $location, ST_INVENTORY_RECEIPT_REQUEST);

        display_job_cost_transaction_type_details(ST_INVENTORY_RECEIPT, $result, $total_cost);
}

function display_inventory_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_INVENTORY_ISSUE) {
        return;
    }
    
        $result = get_inventory_receipt_cost_details($project_id, $job_id, ST_INVENTORY_ISSUE, $stock_id, $location, ST_INVENTORY_ISSUE_REQUEST);

        display_job_cost_transaction_type_details(ST_INVENTORY_ISSUE, $result, $total_cost);
}

function display_pr_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_PR_ISSUE) {
        return;
    }
    
        $result = get_pr_issue_cost_details($project_id, $job_id, $stock_id, $location);

        display_job_cost_transaction_type_details(ST_PR_ISSUE, $result, $total_cost);
}

function display_pr_return_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_PR_RETURN) {
        return;
    }
    
        $result = get_pr_return_cost_details($project_id, $job_id, $stock_id, $location);

        display_job_cost_transaction_type_details(ST_PR_RETURN, $result, $total_cost);
}

function display_daily_item_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_DAILY_ITEM_ISSUE) {
        return;
    }
    
        $result = get_daily_item_issue_cost_details($project_id, $job_id, ST_DAILY_ITEM_ISSUE, $stock_id, $location);

        display_job_cost_transaction_type_details(ST_DAILY_ITEM_ISSUE, $result, $total_cost);
}

function display_daily_item_return_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_DAILY_ITEM_RETURN) {
        return;
    }
    
        $result = get_daily_item_issue_cost_details($project_id, $job_id, ST_DAILY_ITEM_RETURN, $stock_id, $location);

        display_job_cost_transaction_type_details(ST_DAILY_ITEM_RETURN, $result, $total_cost);
}

function display_raw_material_issue_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_RAW_MATERIAL_ISSUE) {
        return;
    }
    
        $result = get_raw_material_issue_cost_details($project_id, $job_id, ST_RAW_MATERIAL_ISSUE, $stock_id, $location);

        display_job_cost_transaction_type_details(ST_RAW_MATERIAL_ISSUE, $result, $total_cost);
}

function display_raw_material_return_cost_details($project_id, $job_id, $type, $stock_id, $location, &$total_cost) {
    if ($type > 0 && $type != ST_RAW_MATERIAL_RETURN) {
        return;
    }
    
        $result = get_raw_material_issue_cost_details($project_id, $job_id, ST_RAW_MATERIAL_RETURN, $stock_id, $location);

        display_job_cost_transaction_type_details(ST_RAW_MATERIAL_RETURN, $result, $total_cost);
}

function display_i_owe_you_cost_details($project_id, $job_id, $type, &$total_cost) {
    if ($type > 0 && $type != ST_I_OWE_YOU_BATCH) {
        return;
    }
    
        $result = get_i_owe_you_cost_details($project_id, $job_id, ST_I_OWE_YOU_BATCH);

        display_job_cost_transaction_type_details(ST_I_OWE_YOU_BATCH, $result, $total_cost);
}

function display_utility_bill_cost_details($project_id, $job_id, $type, &$total_cost) {
    if ($type > 0 && $type != ST_UTILITY_BILLS) {
        return;
    }
    
        $result = get_utility_bill_cost_details($project_id, $job_id, ST_UTILITY_BILLS);

        display_job_cost_transaction_type_details(ST_UTILITY_BILLS, $result, $total_cost);
}

function display_utility_bill_cn_cost_details($project_id, $job_id, $type, &$total_cost) {
    if ($type > 0 && $type != ST_UTILITY_BILL_CREDIT_NOTE) {
        return;
    }
    
        $result = get_utility_bill_cn_cost_details($project_id, $job_id, ST_UTILITY_BILL_CREDIT_NOTE);

        display_job_cost_transaction_type_details(ST_UTILITY_BILL_CREDIT_NOTE, $result, $total_cost);
}


function display_daily_tool_return_cost_details($project_id, $job_id, $type, &$total_cost) {
    if ($type > 0 && $type != ST_DAILY_TOOL_RETURN) {
        return;
    }
    
        $result = get_daily_tool_return_cost_details($project_id, $job_id, ST_DAILY_TOOL_RETURN);

        display_job_cost_transaction_type_details(ST_DAILY_TOOL_RETURN, $result, $total_cost);
}

function display_tool_usage_charges_details($project_id, $job_id, $type, &$total_cost) {
    if ($type > 0 && $type != ST_TOOL_USAGE_CHARGE) {
        return;
    }
    
        $result = get_tool_usage_charges_details($project_id, $job_id, ST_TOOL_USAGE_CHARGE);

        display_job_cost_transaction_type_details(ST_TOOL_USAGE_CHARGE, $result, $total_cost);
}

function display_job_cost_addition_details($project_id, $job_id, $type, &$total_cost) {
    if ($type > 0 && $type != ST_JOB_COST_ADDITION) {
        return;
    }
    
        $result = get_job_cost_adjustments_details($project_id, $job_id, ST_JOB_COST_ADDITION, $type);

        display_job_cost_adjustments_type_details(ST_JOB_COST_ADDITION, $result, $total_cost);
}

function display_job_cost_deduction_details($project_id, $job_id, $type, &$total_cost) {
    if ($type > 0 && $type != ST_JOB_COST_DEDUCTION) {
        return;
    }
    
        $result = get_job_cost_adjustments_details($project_id, $job_id, ST_JOB_COST_DEDUCTION, $type);

        display_job_cost_adjustments_type_details(ST_JOB_COST_DEDUCTION, $result, $total_cost);
}

function display_job_cost_adjustments_type_details($type, $result, &$total_cost) {
    global $systypes_array;
    
        start_row();
            label_cell(text_bold($systypes_array[$type].'s'), "align=center colspan=10 style=background-color:#8cd4be");
        end_row();

        $dec = 2;
        $k = $trans_type_total_cost = 0;
            while($row = db_fetch($result)) {
                alt_table_row_color($k);
                    $trandate = sql2date($row["tran_date"]);
                    $type = $row["type"];
                    $type_name = $systypes_array[$type];
                    $item_description = $row["item_description"]; 
                    $cost = $row["cost"]; 

                    label_cell($row["trans_id"], "align=center");
                    label_cell($type_name);
                    label_cell(get_trans_view_str($type, $row["trans_no"]), "align=center");
                    label_cell($trandate, "align=center");
                    label_cell('');

                    label_cell($item_description);
                    label_cell('', 'align=center');
                    label_cell('', 'align=right');
                    label_cell('', "align=right");

                    if($type == ST_JOB_COST_DEDUCTION){
                        $cost = -$cost;
                    }
                    $line_total_cost = $cost;
                    label_cell(number_format2($line_total_cost, $dec), "align=right");
                    
                    $trans_type_total_cost += $line_total_cost;
                end_row();
            }
            
            start_row();
                label_cell(text_bold('Total for '.$systypes_array[$type].'s :'), "align=right colspan=9");
                label_cell(text_bold(number_format2($trans_type_total_cost, $dec)), "align=right");
            end_row();
            
            start_row();
                vertical_space('height=20px colspan=10');
            end_row();
            
            $total_cost += $trans_type_total_cost;
}
