<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_APPROVE_LEAVE';
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/data_checks.inc");
include_once($path_to_root . "/payroll/includes/payroll_db.inc");
include_once($path_to_root . "/payroll/includes/leave_calculation.inc");

simple_page_mode(true);

page(_($help_context = "Approve Leaves"));

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

function build_monthly_limit_array($entitlement_rec, $validating_from_date)
{
    $period_start_date = $validating_from_date;
    $period_end_date = date2sql(add_months(sql2date($period_start_date), 1));
    
    while ($period_end_date < $entitlement_rec['to_date']) {
        $monthly_limits[] = build_monthly_limit_array_line($period_start_date, $period_end_date, $entitlement_rec['monthly_limit']);
        $period_end_date = date2sql(add_months(sql2date($period_end_date), 1));
    }
    
    return $monthly_limits;
}

function build_monthly_limit_array_line($start_date, $end_date, $monthly_limit)
{

    $l = array("start_date" => $start_date,
                "end_date" => $end_date,
                "days" => $monthly_limit);
    
    return $l;
}


function allocate_to_monthly_limit_array(&$monthly_limit_array, $leave, $this_allocation)
{
    $unallocated_leave_days = $this_allocation;
    
    foreach ($monthly_limit_array as &$line) {
        if($leave["from_date"] > $line['end_date']){
            if($line['days'] > 0){
                if($unallocated_leave_days > $line['days']){
                    $unallocated_leave_days -= $line['days'];
                    $line['days'] = 0;
                }
                elseif($unallocated_leave_days == $line['days']){
                    $line['days'] = 0;
                    $unallocated_leave_days = 0;
                }
                else{
                    $line['days'] -= $unallocated_leave_days;
                    $unallocated_leave_days = 0;
                }
            }
        }
        
        if($unallocated_leave_days <= 0){
            return 0;
        }
    }
    
    return $unallocated_leave_days;

}



function approve_leave($leave_id, $status, $leave_entitlement_id, $current_leave_days, $is_revoke)
{ 
    $monthly_limit_array = '';
    
    if($status == "A"){
        $entitlement_rec = get_leave_entitlement($leave_entitlement_id);
        $validating_from_date = $entitlement_rec['from_date'];
        $employee_code = $entitlement_rec['employee_code'];

        $leave_entitlement_balances = get_leave_entitlement_balances($leave_entitlement_id, $employee_code);
        $applied_nopay_days = $leave_entitlement_balances['nopay_days'];

        $employee = get_employee($employee_code);
        if(date1_greater_date2(sql2date($employee['date_of_joining']), sql2date($validating_from_date))){
            $validating_from_date = $employee['date_of_joining'];
        }

        $allowed_leave_days_en = $entitlement_rec['leave_entitlement'];
        $leave_used_total = 0.0;
        $approved_leave_days_total = 0.0;
        $approved_nopay_days_total = 0;


        //$result = get_leave_detail_records($leave_entitlement_id, $employee_code);

        //Monthly limit based calculation
        $monthly_limit_array = build_monthly_limit_array($entitlement_rec, $validating_from_date);

        //Allocate approved leaves to slots of monthly limit array
        $result = get_entitlement_leave_records($leave_entitlement_id, $employee_code);
        while ($leave = db_fetch($result)) {
            if(!($leave['status_code'] == "N" || $leave['status_code'] == "W" || $leave['status_code'] == "J" || 
                    $leave['id'] == $leave_id)){

                if($leave['is_revoke'] == 1){
                    $leave_days = -$leave['leave_days'];
                }
                else{
                    $leave_days = $leave['leave_days'];
                }

                $leave_nopay_days = $leave['nopay_days'];

                $this_allocation = $leave_days - $leave_nopay_days;
                if($this_allocation > 0){
                    allocate_to_monthly_limit_array($monthly_limit_array, $leave, $this_allocation);
                }

                $approved_leave_days_total += $leave_days;
                $approved_nopay_days_total += $leave_nopay_days;
            }

        }

        //Existing leaves allocation to monthly limit array completed.
        //Now allocate the current approving leave

        $current_leave_nopay_days_ml = 0;
        $current_leave = get_leave_record_by_id($leave_id);
        if($current_leave && $entitlement_rec['monthly_limit'] > 0) {
            $current_leave_nopay_days_ml = allocate_to_monthly_limit_array($monthly_limit_array, $current_leave, $current_leave['leave_days']);              
        }

        // Entitlement based calculation
        $current_leave_nopay_days_en = 0;
        if($allowed_leave_days_en < ($approved_leave_days_total + $current_leave['leave_days'] - $approved_nopay_days_total)){
            $current_leave_nopay_days_en = ($approved_leave_days_total + $current_leave['leave_days'] - $approved_nopay_days_total) - $allowed_leave_days_en;
        }

        if($current_leave_days < $current_leave_nopay_days_ml){
            $current_leave_nopay_days_ml = $current_leave_days;
        }

        if($current_leave_days < $current_leave_nopay_days_en){
            $current_leave_nopay_days_en = $current_leave_days;
        }            

        if($current_leave_nopay_days_ml > $current_leave_nopay_days_en){
            $current_leave_nopay_days = $current_leave_nopay_days_ml;
        }
        else{
            $current_leave_nopay_days = $current_leave_nopay_days_en;
        }

        if($is_revoke){
            $current_leave_nopay_days = 0;
        }

        $leave_used_total = $entitlement_rec['leave_used'];
        update_approved_leave($leave_id, $current_leave_nopay_days, $status, $leave_entitlement_id, $leave_used_total);
    }
    elseif($status == "J"){
        update_approved_leave($leave_id, null, $status, 
                                null, null, null);
    }

}


function approve_leave_with_manual_nopay($leave_id, $status, $leave_entitlement_id, $current_leave_days, $manual_nopay_days, $is_revoke)
{
    $entitlement_rec = get_leave_entitlement($leave_entitlement_id);
    $leave_used_total = $entitlement_rec['leave_used'];
    
    if($is_revoke){
            $manual_nopay_days = 0;
    }
        
    if($status == "A"){
       update_approved_leave($leave_id, $manual_nopay_days, $status, $leave_entitlement_id, $leave_used_total);
    }
    elseif($status == "J"){
        update_approved_leave($leave_id, null, $status, 
                                null, null, null);
    }
}

start_form();


br();


$Ajax->activate('leaves');

div_start('leaves');

start_table(TABLESTYLE, "width=90%");

$th = array(_("Employee Code"),_("Employee Name"), _("Leave Type"),
            _("From Date"),_("From Time"), _("To Date"), _("To Time"),
            _("Leave Days"),_("Entitlement"), //_("Used"),
            _("Nopay"),_("Comment"),_("Action"),"Select");
table_header($th);

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


if (isset($_POST['UpdateData']))
{
    $a_result = get_unapproved_leave_records();
    $updates_count = 0;
    
    while ($a_row = db_fetch($a_result))
    {

        if((isset($_POST["selected_".$a_row["id"]])) &&
                ($_POST["selected_".$a_row["id"]] == true))
        {
            $any_selected = true;
            $temp_name = 'leave_approval_status'.$a_row["id"];

            //approve_leave($a_row["id"], $_POST[$temp_name], $a_row["leave_entitlement_id"], $a_row["leave_days"], $a_row["is_revoke"]);
            
            $error_prefix = $a_row["employee_code"]." - ".$a_row["initials"]." ".$a_row["last_name"]." (".$a_row["first_name"].") - "
                            .$a_row["leave_type_name"]." - from ".sql2date($a_row["from_date"])." to ".sql2date($a_row["to_date"]);
            
            if(!check_num('nopay_days'.$a_row["id"], 0, $a_row["leave_days"])){
                display_error($error_prefix." - Entered number of leave days is not valid");
                continue;
            }
            $rem = fmod($_POST['nopay_days'.$a_row["id"]], 0.5);
            if($rem != 0){
                display_error($error_prefix." - Nopay days should be a multiple of 0.5 ");
                continue;
            }
            
            approve_leave_with_manual_nopay($a_row["id"], $_POST[$temp_name], $a_row["leave_entitlement_id"], $a_row["leave_days"], 
                                            $_POST['nopay_days'.$a_row["id"]], $a_row["is_revoke"]);
            $updates_count++;
            
        }
    }
    
    if($updates_count > 0){
        display_notification(_("Selected leaves have been updated."));
    }
    else{
        display_error(_("No records were updated."));
    }
}


$result = get_unapproved_leave_records();

while ($myrow = db_fetch($result))
{

	alt_table_row_color($k);

        //label_cells('',$myrow["id"]);
        label_cells('',$myrow["employee_code"]);
        label_cells('',$myrow["initials"]." ".$myrow["last_name"]."(".$myrow["first_name"].")");
        label_cells('',$myrow["leave_type_name"]);
        label_cells('',sql2date($myrow["from_date"]));
        label_cells('',$myrow["from_time_name"]);
        label_cells('',sql2date($myrow["to_date"]));
        label_cells('',$myrow["to_time_name"]);
        //label_cells('',$myrow["leave_days"], "align=right");
        qty_cell($myrow["leave_days"], false, 1);
        //label_cells('',$myrow["leave_entitlement"]);
        qty_cell($myrow["leave_entitlement"], false, 1);
        //label_cells('',$myrow["leave_used"]);
        //qty_cells(null, 'nopay_days'.$myrow["id"], '0.0', null, null, 1);
        if($myrow['uninformed_leave_type'] == 1){
            $_POST['nopay_days'.$myrow["id"]] = $myrow["leave_days"];
        }
        else{
            $_POST['nopay_days'.$myrow["id"]] = 0.0;
        }
        small_qty_cells(null, 'nopay_days'.$myrow["id"], null, null, null, 1);
        label_cells('',$myrow["comment"]);
        value_list_code_cells(null, 'leave_approval_status'.$myrow["id"], "LEAVE_STATUS", null);

        check_cells('', 'selected_'.$myrow["id"],0);

	end_row();
	$j++;
	If ($j == 12)
	{
		$j = 1;
		table_header($th);
	}
}

end_table(1);
div_end();
submit_center('UpdateData', _("Update"), true, false, 'default');

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