<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_PAYROLL_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 . "/payroll/includes/payroll_db.inc");

include_once($path_to_root . "/payroll/includes/payroll_calculation.inc");
include_once($path_to_root . "/payroll/includes/db/payroll_calculation_db.inc");
include_once($path_to_root . "/payroll/includes/db/calculate_payroll_departments_summary_db.inc");
include_once($path_to_root . "/jobq/includes/jobq_requests.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 = "Payroll Run"), false, false, "", $js);

//----------------------------------------------------------------------------------------
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_start_date'])) 
    {
        display_error( _('Period start date is not a valid date'));
        set_focus('period_start_date');
        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;
    }


    return true;
    
}
//--------------------------------------------------------------------------------------------------

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') 
    {
            add_payroll_run($linked_payroll_run_id, $_POST['payroll_id'], $_POST['description'], '',
                        date2sql($_POST['period_start_date']), date2sql($_POST['period_end_date']),
                        date2sql($_POST['tran_date']),"N");
            
            display_notification(_("Payroll run has been added."));
    } 
    if ($Mode == 'UPDATE_ITEM') 
    {
            update_payroll_run($selected_id, $linked_payroll_run_id, $_POST['payroll_id'], $_POST['description'], '',
                        date2sql($_POST['period_start_date']), date2sql($_POST['period_end_date']),
                        date2sql($_POST['tran_date']),"U");

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

}

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

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

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_payroll']) || isset($_POST['continue_payroll']) )
{
        if (isset($_POST['run_payroll'])){
            delete_payroll_run_details($selected_id);
            delete_payroll_departments_summary($payroll_run_id);
        }
    /**************************************
    Direct run
    ***************************************/

//        $calculate_payroll_msg = calculate_payroll($selected_id);
//        if($calculate_payroll_msg['passed'] == true){
//            display_notification($calculate_payroll_msg['message']);
//        }
//        else{
//            display_error($calculate_payroll_msg['message']);
//        }

    /**************************************
    Jobq run
    ***************************************/
        $parameters[] = array('payroll_run_id' => $selected_id, 'payroll_processing_type' => 'CALCULATE');
        $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;
}

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;
        }
}


if (!@$_GET['popup'])
	start_form();


br();	

    $result = get_payroll_runs();
    
    div_start('price_table');
    
    if (db_num_rows($result) == 0)
    {
    	display_note(_("There are no payroll runs defined."));
    }
    else
    {
        start_table(TABLESTYLE, "width=90%");

		$th = array(_("Id"), _("Payroll Name"), _("Description"),
                        _("Period Start Date"), _("Period End Date"),
                        _("Transaction Date"),_("Linked Payroll Run"),
                        _("Status"), _("Run By"), "", "", "", "");

        table_header($th);

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

        while ($myrow = db_fetch($result))
        {
            alt_table_row_color($k);
            
            $link_id = get_payroll_trans_view_str(ST_PAYROLL, $myrow["id"]);
            label_cell($link_id);
            label_cell($myrow["payroll_name"]);
            label_cell($myrow["description"]);
            label_cell(sql2date($myrow["period_start_date"]), "align=center");
            label_cell(sql2date($myrow["period_end_date"]), "align=center");
            label_cell(sql2date($myrow["tran_date"]), "align=center");
            
            $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["payroll_run_status_name"]);
            label_cell($myrow["real_name"]);
//            label_cell($myrow["last_completed_employee_code"]);
            
            $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"), _("Run Payroll"));
                    }
                    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

        end_table();
    }
    div_end();

//-----------------------------------------------------------------------------------------------
    $_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_payroll_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['tran_date'] = sql2date($myrow["tran_date"]);
    
    hidden('id', $_POST['id']); 
}

br();

hidden('selected_id', $selected_id);



if($run == true){
    start_table(TABLESTYLE2);
    
    label_row("Payroll Name:", $_POST['payroll_name']);
    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']);
    
    end_table(1);
    
    if(strlen($myrow['last_completed_employee_code']) > 0){
        submit_center_first('run_payroll', _("Run Payroll - From Beginning"), '', 'default');
        submit_center_last('continue_payroll', _("Run Payroll - Continue"), '', 'default');
    }
    else{
        submit_center_first('run_payroll', _("Run Payroll - From Beginning"), '', 'default');
    }

}
elseif($calculate_summary == true){
    start_table(TABLESTYLE2);
    
    label_row("Payroll Name:", $_POST['payroll_name']);
    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(1);
    

    submit("calculate_summary", "Calculate Summary" );

}
else{
    start_table(TABLESTYLE2);

    value_list_row('Select Payroll:', 'payroll_id', 'PAYROLLS', $_POST['payroll_id']);
    text_row("Description:", "description", $_POST['description'], 50,200);
    date_row(_("Period Start Date:"), 'period_start_date');
    date_row(_("Period End Date:"), 'period_end_date');
    date_row(_("Transaction Date:"), 'tran_date');
    
    if ($Mode =='Edit')
    {
        payroll_run_list_row("Linked Payroll Run:", 'linked_payroll_run_id', $_POST['linked_payroll_run_id'], '');
    }
    else{
        payroll_run_list_row("Linked Payroll Run:", 'linked_payroll_run_id', null, '');
    }

    end_table(1);
    br();
    submit_add_or_update_center($selected_id == -1, '', 'both');
}


end_form(2);
end_page(@$_GET['popup'], false, false);

?>