<?php

namespace FAAPI;

set_time_limit(0);
ini_set('memory_limit', '50024M');
error_reporting(E_ALL | E_STRICT);
$path_to_root = "../..";
include_once($path_to_root . "/modules/api/session-custom.inc");
include_once $path_to_root . "/modules/external/utils.php";
include_once $path_to_root . "/modules/property/includes/db/property_db.php";
include_once $path_to_root . "/modules/property/propertytypes.php";
include_once $path_to_root . "/modules/FrontHrm/includes/db/attendance_db.inc";
include_once($path_to_root . "/modules/FrontHrm/includes/db/employee_db.inc");
include_once($path_to_root . "/modules/FrontHrm/includes/db/overtime_db.inc");
include_once($path_to_root . '/modules/FrontHrm/includes/frontHrm_ui.inc');

class HRM {

    // Add Item
    public function clockin_clockout($rest) {
        $req = $rest->request();
        $info = $req->post();

        // Validate Required Fields
        if (empty($info['user_bio_id'])) {
            api_field_error(200, 'user_bio_id is required', 'user_bio_id');
        }

        if (empty($info['time'])) {
            api_error(200, 'time is required', 'time');
        }
        if (empty($info['date'])) {
            api_error(200, 'date is required', 'date');
        }

        if (empty($info['type'])) {
            api_error(200, 'type  is required', 'type');
        }

        if ($info['status'] == '') {
            api_error(200, 'status  is required : ' . $info['status'], 'status');
        }


        $emp = db_fetch(db_query(get_employees(false, false, false, false, false, -1, false, $info['user_bio_id'])));
        $emp_id = $emp["emp_id"];

        if ($info['type'] == "44") {
            $clockin = get_last_clockin($info['user_bio_id']);
            $total_time = time_diff2_min($info['time'], $clockin['time']);
            $regular_time = 0;
            $total_overtime = 0;

            if ($this->round_time($total_time) == 24 || $this->round_time($total_time) > 24) {
                api_error(200, _("User did not clock out withind 24 hrs. Please clockin afresh."));
                return false;
            }

            if (time1_greater_time2($clockin['time'], $info['time'])) {
                api_error(200, _("Clockedin Is in future."));
                return false;
            }

            if (empty($clockin['time'])) {
                api_error(200, _("Last clockin is not valid."));
                return false;
            }

            if ($total_time < 0) {
                api_error(200, _("Last clockin was made in future."));
                return false;
            }

            $shift_change1 = $clockin['date'] . " 07:00:00";
            $shift_change2 = $clockin['date'] . " 17:00:00";

            /*             * ********* daytime ************ */
            //api_error(200, " ".$shift_change1."  > ".$clockin['time']." = ".datetime_comp($shift_change1,$clockin['time'])."    ------   ".$shift_change2." > ".$clockin['time']." = ".datetime_comp($shift_change2,$clockin['time']));
            if (datetime_comp($shift_change1, $clockin['time']) == -1 && datetime_comp($shift_change2, $clockin['time']) == 1) {
                $day_min = 0;
                if (datetime_comp($info['time'], $shift_change2) == 1) {
                    $day_min = time_diff2_min($shift_change2, $clockin['time']);
                } else {
                    $day_min = time_diff2_min($info['time'], $clockin['time']);
                }
                if ($day_min / 60 > 1) {
                    //api_error(200, "TOTAL TIME".$total_time." day time: ".$day_min);
                    $total_time -= $day_min;
                    write_attendance($emp_id, 0, $this->get_regular_work_hrs($this->round_time($day_min)), 1, sql2date($clockin['date']));
                }
            }

            /*             * ********* night shift ************ */
            if ($total_time / 60 > 1) {
                write_attendance($emp_id, 1, $this->get_night_work_hrs($this->round_time($total_time)), 1, sql2date($clockin['date']));
            }
        }

        write_clockin_clockout($info['user_bio_id'], $info['date'], $info['time'], $info['type'], $info['status']);
        api_success_response();
    }

    function round_time($min) {
        $minutes = $min % 60;
        $hours = intval($min / 60);
        if ($minutes > 29) {
            return ($hours + 1);
        } else {
            return $hours;
        }
    }

    function get_regular_work_hrs($hrs) {
        global $Work_hours;
        //api_error(200, "hrs:".$hrs." Work_hours:".$Work_hours);
        if ($hrs > $Work_hours || $hrs == $Work_hours) {
            return $Work_hours;
        } else {
            return $hrs;
        }
    }

    function get_night_work_hrs($hrs) {
        $Night_hours = 14;
        //api_error(200, "hrs:".$hrs." Work_hours:".$Work_hours);
        if ($hrs > $Night_hours || $hrs == $Night_hours) {
            return $Night_hours;
        } else {
            return $hrs;
        }
    }

    // Get Items
    public function get($rest) {
        $req = $rest->request();

        $from = isset($_GET["start"]) ? $_GET["start"] : null;
        $length = isset($_GET["length"]) ? $_GET["length"] : null;
        $term = isset($_GET["term"]) ? $_GET["term"] : '';
        $this->employees_all($from, $length, $term);
    }

    // Get 
    public function getById($id) {
        $sql = "SELECT * FROM " . TB_PREF . "employee WHERE emp_id=" . db_escape($id);
        $result = db_query($sql, _('Could not get group data.'));
        $row = db_fetch($result);
        if (!$row)
            $row = array();
        api_success_response(json_encode($row));
    }

    private function employees_all($from = null, $length = null, $term = '') {
        if ($from == null)
            $from = 0;
        if ($length == null)
            $length = RESULTS_PER_PAGE;
        if ($term == null)
            $term = '';
        $sql = "SELECT *,concat(emp_first_name,' ',emp_last_name) text FROM " . TB_PREF . "employee WHERE inactive=0 and emp_first_name like " . db_escape("%" . $term . "%") . " or emp_last_name like " . db_escape("%" . $term . "%") . " LIMIT " . $from . ", " . $length;
        $query = db_query($sql, "error");

        $info = array();
        while ($data = db_fetch($query, "error")) {
            $info[] = array(
                'id' => $data['emp_id'],
                'text' => $data['text']
            );
        }
        $response['items'] = $info;
        $response['incomplete_results'] = FALSE;
        $response['total_count'] = $length;
        api_success_response(json_encode($response));
    }

}
