<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_ASSET_DEPRICIATION_RUN';
if (!@$_GET['popup'])
	$path_to_root = "..";
else	
	$path_to_root = "../..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/inventory.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/assets/includes/db/asset_depreciation_run_db.inc");
include_once($path_to_root . "/assets/includes/calculate_asset_run.inc");

$js = '';

if ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

if (user_use_date_picker()) {
	$js .= get_js_date_picker();
}

page(_($help_context = "Asset Depreciation Runs"));

//----------------------------------------------------------------------------------------
simple_page_mode(true);
    
$run = false;

if(substr($selected_id, 0, 6) == "Select"){
    $selected_id = substr($selected_id, 6);
    $run = true;
}

$calculate_summary = false;

if(substr($selected_id, 0, 16) == "CalculateSummary"){
    $selected_id = substr($selected_id, 16);
    $calculate_summary = true;
}

if (isset($_GET['AddedID'])) 
{
	$trans_no = $_GET['AddedID'];
	$trans_type = ST_PAYROLL;
        
        display_notification_centered("Request $trans_no has been submitted to job queue");
        
//	display_note(get_trans_view_str($trans_type, $trans_no, _("&View this payroll")), 0, 1);
//
//	display_note(print_document_link($trans_no, _("&Print This Payslips"), true, $trans_type), 0, 0);

	display_footer_exit();
}


function check_data($selected_id)
{	
    if (strlen($_POST['description']) < 1)
    {
        display_error( _("Description can not be empty."));
        set_focus('description');
        return false;
    }
    

    if (!is_date($_POST['period_end_date'])) 
    {
        display_error( _('Period end date is not a valid date'));
        set_focus('period_end_date');
        return false;
    }
    
    
    if (!check_num('no_of_months',0.0001) )
    {
        display_error( _('No of months has be a positive value'));
        set_focus('no_of_months');
        return false;
    }

    return true;    
}

function get_current_period_start_date()
{
   $row = get_last_period_start_date();
   if(isset($row['period_end_date'])){
       $current_period_start_date = add_days(sql2date($row['period_end_date']), 1);
   }else{
       $current_period_start_date = sql2date(INFINITE_START_DATE);
   }
   
   return $current_period_start_date;
}
//--------------------------------------------------------------------------------------------------

if (($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') && check_data($selected_id))
{
//    if($_POST['linked_payroll_run_id'] > 0){
//        $linked_payroll_run_id = $_POST['linked_payroll_run_id'];
//    }
//    else{
//        $linked_payroll_run_id = 0;
//    }

    if ($Mode == 'ADD_ITEM') 
    {
        
            $ar_id = add_asset_depreciation_run($_POST['description'], 
                          date2sql($_POST['period_end_date']), input_num('no_of_months'), "N");
                       
//            set_session_variable('Asset_Request_id', $ar_id);
            
            display_notification(_("New asset depreciation run has been added."));
    } 
    if ($Mode == 'UPDATE_ITEM') 
    {
        update_asset_depreciation_run($selected_id, $_POST['description'], 
                             date2sql($_POST['period_end_date']), input_num('no_of_months'), "U");
                           

            $selected_id = -1;
            display_notification(_("Asset depreciation run has been updated."));
    }
    $Mode = 'RESET';
}

//-------------------------------------------------------------------------------------------------

//function calculate_asset_depreciations($ar_id)
//{
//    $result = get_asset_details_for_depreciation($ar_id);
//     
//    delete_asset_depreciation($ar_id);
//     
//    while($row = db_fetch($result)){
//            $depreciation = $row['current_value'] - $row['depreciation_rate'];
//               
//            $task_id=0;
//            $department_id=0;
//            $project_id=0;
//            $status='N';
//            $comment='';
//            add_asset_depreciation($ar_id, $row_b['asset_id'],
//                                    $row_b['current_value'], $depreciation, $task_id, 
//                                    $department_id, $project_id,
//                                    $status, $comment, $row['depreciation_rate']);
//    
//            update_last_calculated_asset($ar_id, $row_b['asset_id']);
//    }
//
//}


function display_asset_depreciation_runs()
{
    $result = get_asset_depreciation_runs();

    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no asset depreciation runs defined."));
    }
    else
    {
        start_table(TABLESTYLE, "width=60%");

		$th = array(_("Id"), _("Description"), _("Calculated Upto Date"),                         
                            "No Of Months", _("Status"),  "", "", "");

        table_header($th);

        $k = $j = 0; //row colour counter

        while ($myrow = db_fetch($result))
        {
            alt_table_row_color($k);

            label_cell($myrow["id"]);
//            label_cell($myrow["payroll_id"]);
            label_cell($myrow["description"]);
//            label_cell(sql2date($myrow["period_start_date"]), "align=center");
            label_cell(sql2date($myrow["period_end_date"]), "align=center");
            qty_cell($myrow['no_of_months'], false, 1);
            
//            $linked_payroll_run_id = $myrow["linked_payroll_run_id"];
//            if($linked_payroll_run_id == 0){
//                $linked_payroll_run_id = '';
//            }
//            label_cell($linked_payroll_run_id, "align=center");
//            $start_date = sql2date($myrow["start_time"]);
//            $start_time = sql2time($myrow["start_time"]);
//            if(substr($start_date,0,2) == "00"){
//                label_cell("");
//                label_cell("");
//            }
//            else{
//                label_cell($start_date." ".$start_time, "align=center");
//                
//                $end_date = sql2date($myrow["end_time"]);
//                $end_time = sql2time($myrow["end_time"]);
//                label_cell($end_date." ".$end_time, "align=center");
//            }
            
            
            
            label_cell($myrow["status_name"], "align=center");
//            label_cell($myrow["real_name"]);
            
//            label_cell('');
//            label_cell('');
            
            $s = $myrow["status"];
                    if($s == "N" || $s == "U"){
                        edit_button_cell("Edit".$myrow['id'], _("Edit"));
                        delete_button_cell("Delete".$myrow['id'], _("Delete"));
                    }
                    else{
                        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                    }
                    
//                    if($s == "N" || $s == "U" || $s == "C" || $s == "L"){
//                        select_button_cell("EditCalculateSummary".$myrow['id'], _("Select"), _("Calculate Summary"));
//                    }
//                    else{
//                        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
//                    }
                    
                    
                    if($s == "N" || $s == "U" || $s == "C" || $s == "L"){
                        select_button_cell("EditSelect".$myrow['id'], _("Select"), _("Calculate Depreciation"));
                    }
                    else{
                        label_cell("&nbsp"."&nbsp"."&nbsp"."&nbsp"."&nbsp");
                    }	
                        
            end_row();

            $j++;
            If ($j == 25)
            {
            	$j = 1;
        		table_header($th);
            } //end of page full new headings
        } //end of while loop

        //hidden("selected_id", $_POST['id']);
        end_table();
    }
}


if(isset($_POST['Calculate_Depreciation']))
{
//    $ar_id = get_session_variable($name);
    
    calculate_asset_depreciations($ar_id);
    
}


//--------------------------------------------------------------------------------------------------

if ($Mode == 'Delete')
{      
    delete_asset_depreciation_run($selected_id);
    display_notification(_("The shift has been sucessfully deleted."));
    $Mode = 'RESET';
//        return;
}

if ($Mode == 'RESET')
{
	$selected_id = -1;
}

if (isset($_POST['_selected_id_update']))
{
    $selected_id = $_POST['selected_id'];
    $Ajax->activate('_page_body');
}

//--------------------------------------------------------------------------------------------------

if (isset($_POST['run_asset_calculation']))
{
    $asset_run_id = $_POST['selected_id'];    
     
    $msg_cjr = calculate_asset_depreciations($asset_run_id);
//        if($msg_cjr['passed'] == true){
//            update_payroll_run_joq_request_id($selected_id, (int)$msg_cjr['message']);
//            meta_forward($_SERVER['PHP_SELF'], "AddedID=".$msg_cjr['message']);
//        }
//        else{
//            display_error($msg_cjr['message']);
//        }
//    
//    
        $selected_id = -1;
}

if (isset($_POST['calculate_summary']) )
{
        if($_POST['linked_payroll_run_id'] > 0){
            $linked_payroll_run_id = $_POST['linked_payroll_run_id'];
        }
        else{
            $linked_payroll_run_id = 0;
        }
    
        $upli = update_payroll_link_id($linked_payroll_run_id, $selected_id);

        if($upli == 1){
            $parameters[] = array('payroll_run_id' => $selected_id, 'payroll_processing_type' => 'CALCULATE_SUMMARY');
            $parameters_json = json_encode($parameters);

            $submitted_by = $_SESSION['wa_current_user']->user;

            $msg_cjr = create_jobq_request(ST_PAYROLL, $submitted_by, $parameters_json);
            if($msg_cjr['passed'] == true){
                update_payroll_run_joq_request_id($selected_id, (int)$msg_cjr['message']);
                meta_forward($_SERVER['PHP_SELF'], "AddedID=".$msg_cjr['message']);
            }
            else{
                display_error($msg_cjr['message']);
            }
            $selected_id = -1;
        }
}



	start_form();

        $Ajax->activate('price_table');

            
    div_start('price_table');
    
    display_asset_depreciation_runs();
br();	


    div_end();

    display_note('Actual depreciation rate of an asset will be derived by multiplying the "Monthly Depreciation Rate" (= Annual Depreciation Rate / 12) by the value in the "No. Of. Months From Last Run" field');

//-----------------------------------------------------------------------------------------------
      
    $_POST['id'] = 0;
    $_POST['payroll_id'] = "";
    //$_POST['payroll_name'] = "";
    $_POST['description'] = "";
//    $_POST['period_start_date'] = 0;
    $_POST['period_end_date'] = 0;
//    $_POST['tran_date'] = 0;
    
$dec2 = 6;
if ($Mode =='Edit')
{
    $myrow = get_asset_depreciation_run_details($selected_id);

    //$_POST['linked_payroll_run_id'] = $myrow["linked_payroll_run_id"];
    $_POST['id'] = $myrow["id"];
//    $_POST['payroll_id'] = $myrow["payroll_id"];
   // $_POST['payroll_name'] = $myrow["payroll_name"];
    $_POST['description'] = $myrow["description"];
    $_POST['period_start_date'] = sql2date($myrow["period_start_date"]);
    $_POST['period_end_date'] = sql2date($myrow["period_end_date"]);
    $_POST['no_of_months'] = $myrow["no_of_months"];
    
    hidden('id', $_POST['id']); 
}
else{
    $_POST['no_of_months'] = 1.0;
}

br();

hidden('selected_id', $selected_id);


if($run == true){
    start_table(TABLESTYLE2);
    
//    label_row("Payroll Name:", $_POST['payroll_id']);
    label_row("Description:", $_POST['description']);          
//    label_row(_("Period Start Date:"), $_POST['period_start_date']);
    label_row(_("Period End Date:"), $_POST['period_end_date']);
    label_row(_("No. Of. Months From Last Run:"), $_POST['no_of_months']);
    
    end_table(2);    
 
    submit_center_first('run_asset_calculation', _("Calculate Asset Depreciation"), '', 'default');

}
elseif($calculate_summary == true){
    start_table(TABLESTYLE2);
    
//    label_row("Payroll Name:", $_POST['payroll_id']);
    label_row("Description:", $_POST['description']);
    
    label_row(_("Period Start Date:"), $_POST['period_start_date']);
    label_row(_("Period End Date:"), $_POST['period_end_date']);
//    label_row(_("Transaction Date:"), $_POST['tran_date']);
    //payroll_run_list_row("Linked Payroll Run:", 'linked_payroll_run_id', null, '');
    
    end_table(2);
    
 
    submit_center_first('calculate_summary', _("Calculate Summary"), '', 'default');

}
else{
    start_table(TABLESTYLE2);

//    value_list_row('Select Payroll:', 'payroll_id', 'PAYROLLS', $_POST['payroll_id']);
    text_row("Description:", "description", $_POST['description'], 50,200);
    
    
    $current_period_start_date = get_current_period_start_date();
     
//    label_row("Period Start Date:", $current_period_start_date);
//    hidden('period_start_date', $current_period_start_date);
    
//    date_row(_(""), 'period_start_date');
    date_row(_("Calculate Up To Date:"), 'period_end_date');
    qty_row("No. Of. Months From Last Run:", 'no_of_months', null, null, null, 1);

    
    end_table(2);
    
    submit_add_or_update_center($selected_id == -1, '', 'both');
    br(1);
//    submit_center_last('Calculate_Depreciation', _("Calculate"), '', @$_REQUEST['popup'] ? true : 'default');
}

br(3);

if (!@$_GET['popup'])
{
    end_form();
    end_page(@$_GET['popup'], false, false);
}


?>
