<?php
$PageSecurity = 15;

$table = 'hr_performance_appraisal';
$modid = $_REQUEST['modid'];
$frmid = $_REQUEST['frmid'];
$rurl  = "index.php?route=HRModule/PerformanceAppraisal&modid=" . $modid . "&frmid=" . $frmid;

/* ===================== SAVE (INSERT / UPDATE) ===================== */
if ($_REQUEST['Save']) {
    $data['emp_id']         = $_REQUEST['emp_id'];
    $data['appraisal_year'] = $_REQUEST['appraisal_year'];
    $data['appraisal_date'] = FormatDateForSQL($_REQUEST['appraisal_date']);
    $data['punctuality']    = (int)$_REQUEST['punctuality'];
    $data['work_quality']   = (int)$_REQUEST['work_quality'];
    $data['teamwork']       = (int)$_REQUEST['teamwork'];
    $data['knowledge']      = (int)$_REQUEST['knowledge'];
    $data['communication']  = (int)$_REQUEST['communication'];
    $data['total_score']    = $data['punctuality'] + $data['work_quality'] + $data['teamwork']
                              + $data['knowledge'] + $data['communication'];
    $ts = $data['total_score'];
    if ($ts >= 23)      { $data['overall_rating'] = 'Excellent'; }
    elseif ($ts >= 18)  { $data['overall_rating'] = 'Very Good'; }
    elseif ($ts >= 13)  { $data['overall_rating'] = 'Good'; }
    elseif ($ts >= 8)   { $data['overall_rating'] = 'Average'; }
    else                { $data['overall_rating'] = 'Poor'; }
    $data['remarks']       = $_REQUEST['remarks'];
    $data['appraised_by']  = $_REQUEST['appraised_by'];
    $data['CompanyId']     = $_SESSION['ACGCompanyId'];
    $data['created_by']    = $_SESSION['LoginUserName'];
    $data['created_date']  = date('Y-m-d');

    if ($_REQUEST['action'] != 'Edit') {
        $insert = $s->RecordInsert($table, $data);
    } else {
        $cond   = "id='" . $_REQUEST['id'] . "'";
        $insert = $s->RecordEdit($table, $data, $cond);
    }
    if ($insert) {
        $s->pageLocation($rurl . '&action=view&daction=Saved');
    }
}

/* ===================== LOAD FOR EDIT ===================== */
if ($_REQUEST['action'] == 'Edit') {
    $query = DB_query("SELECT * FROM $table WHERE id='" . $_REQUEST['id'] . "'", $db);
    while ($row = DB_fetch_array($query)) {
        $emp_id         = $row['emp_id'];
        $appraisal_year = $row['appraisal_year'];
        $appraisal_date = $row['appraisal_date'];
        $punctuality    = $row['punctuality'];
        $work_quality   = $row['work_quality'];
        $teamwork       = $row['teamwork'];
        $knowledge      = $row['knowledge'];
        $communication  = $row['communication'];
        $total_score    = $row['total_score'];
        $overall_rating = $row['overall_rating'];
        $remarks        = $row['remarks'];
        $appraised_by   = $row['appraised_by'];
    }
}

/* ===================== DELETE ===================== */
if ($_REQUEST['action'] == 'Delete') {
    $cond = "id='" . $_REQUEST['id'] . "'";
    $s->DeleteRecord($table, $cond);
    $s->pageLocation($rurl . '&action=view&daction=Deleted');
}
?>
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div">

<h1>Performance Appraisal</h1>

<?php if ($_REQUEST['daction'] != '') { ?>
<div class="success"><center>Record <?php echo $_REQUEST['daction']; ?> Successfully</center></div>
<?php } ?>

<!-- ===================== ADD / EDIT FORM ===================== -->
<?php if ($_REQUEST['action'] == 'Addnew' || $_REQUEST['action'] == 'Edit') { ?>

<form action="" method="post" onsubmit="return validate();">
<?php if ($_REQUEST['action'] == 'Edit') { ?>
<input type="hidden" name="id" value="<?php echo $_REQUEST['id']; ?>" />
<?php } ?>
<input type="hidden" name="action" value="<?php echo $_REQUEST['action']; ?>" />

<table width="100%" border="0" cellpadding="3" cellspacing="0">
    <tr class="row1">
        <td width="15%" align="right">Employee</td>
        <td width="35%">
            <select name="emp_id" id="emp_id">
                <option value="0">--- Select Employee ---</option>
                <?php
                $emp_sql = DB_query("SELECT id, emp_code, emp_name FROM empmaster WHERE CompanyId='" . $_SESSION['ACGCompanyId'] . "' AND (blocked IS NULL OR blocked=0) ORDER BY emp_name ASC", $db);
                while ($emp_row = DB_fetch_array($emp_sql)) {
                ?>
                <option value="<?php echo $emp_row['id']; ?>" <?php echo ($emp_id == $emp_row['id'] ? 'selected' : ''); ?>>
                    <?php echo $emp_row['emp_code'] . ' - ' . $emp_row['emp_name']; ?>
                </option>
                <?php } ?>
            </select>
        </td>
        <td width="15%" align="right">Appraisal Year</td>
        <td width="35%">
            <select name="appraisal_year" id="appraisal_year">
                <option value="0">--- Select Year ---</option>
                <?php for ($yr = date('Y'); $yr >= 2015; $yr--) { ?>
                <option value="<?php echo $yr; ?>" <?php echo ($appraisal_year == $yr ? 'selected' : ''); ?>><?php echo $yr; ?></option>
                <?php } ?>
            </select>
        </td>
    </tr>
    <tr class="row1">
        <td align="right">Appraisal Date</td>
        <td><input type="text" name="appraisal_date" id="appraisal_date" class="datepick" value="<?php echo $appraisal_date != '' ? ConvertSQLDate($appraisal_date) : date('d/m/Y'); ?>" autocomplete="off" /></td>
        <td align="right">Appraised By</td>
        <td><input type="text" name="appraised_by" id="appraised_by" value="<?php echo htmlspecialchars($appraised_by); ?>" autocomplete="off" /></td>
    </tr>
</table>

<br>
<table width="100%" border="0" cellpadding="3" cellspacing="0" class="thborder">
    <tr>
        <th width="40%">Rating Criteria</th>
        <th class="text-center">1 - Poor</th>
        <th class="text-center">2 - Below Avg</th>
        <th class="text-center">3 - Average</th>
        <th class="text-center">4 - Good</th>
        <th class="text-center">5 - Excellent</th>
    </tr>
    <?php
    $criteria = array(
        'punctuality'   => 'Punctuality & Attendance',
        'work_quality'  => 'Work Quality',
        'teamwork'      => 'Team Work',
        'knowledge'     => 'Knowledge & Skills',
        'communication' => 'Communication',
    );
    $current = compact('punctuality', 'work_quality', 'teamwork', 'knowledge', 'communication');
    foreach ($criteria as $field => $label) { ?>
    <tr class="row1">
        <td align="right"><b><?php echo $label; ?></b></td>
        <?php for ($r = 1; $r <= 5; $r++) { ?>
        <td align="center">
            <input type="radio" name="<?php echo $field; ?>" value="<?php echo $r; ?>"
                <?php echo ($current[$field] == $r || ($current[$field] == '' && $r == 3) ? 'checked' : ''); ?>
                onchange="calcTotal();" />
        </td>
        <?php } ?>
    </tr>
    <?php } ?>
    <tr class="row1">
        <td align="right"><b>Total Score (max 25)</b></td>
        <td colspan="4" align="center">
            <input type="text" id="total_score_display" readonly value="<?php echo $total_score != '' ? $total_score : 15; ?>" style="width:50px;text-align:center;" class="input_read" />
        </td>
        <td align="center">
            <b id="overall_rating_display" style="color:#336699;"><?php echo $overall_rating != '' ? $overall_rating : 'Average'; ?></b>
        </td>
    </tr>
</table>

<br>
<table width="100%" border="0" cellpadding="3" cellspacing="0">
    <tr class="row1">
        <td width="15%" align="right">Remarks</td>
        <td><textarea name="remarks" id="remarks" rows="3" style="width:80%;"><?php echo htmlspecialchars($remarks); ?></textarea></td>
    </tr>
    <tr class="row1">
        <td colspan="2" align="center">
            <input type="submit" name="Save" class="search" value="<?php echo ($_REQUEST['action'] == 'Edit' ? 'Update' : 'Save'); ?>" />
            &nbsp;
            <a href="<?php echo $rurl; ?>"><input type="button" class="search" value="Cancel" /></a>
        </td>
    </tr>
</table>
</form>

<!-- ===================== LIST VIEW ===================== -->
<?php } else { ?>

<p align="left">
    <a href="<?php echo $rurl; ?>&action=Addnew">
        <input type="button" class="search" value="Add New" <?php if ($_SESSION['frmAdd'] == '0') { ?>disabled<?php } ?> />
    </a>
</p>

<!-- Search/Filter Row -->
<form method="get" action="index.php">
<input type="hidden" name="route" value="HRModule/PerformanceAppraisal" />
<input type="hidden" name="modid" value="<?php echo $modid; ?>" />
<input type="hidden" name="frmid" value="<?php echo $frmid; ?>" />
<table width="100%" border="0" cellpadding="3" cellspacing="0">
    <tr class="row1">
        <td width="15%" align="right">Filter by Employee</td>
        <td width="30%">
            <select name="filter_emp" id="filter_emp">
                <option value="">--- All Employees ---</option>
                <?php
                $ef_sql = DB_query("SELECT id, emp_code, emp_name FROM empmaster WHERE CompanyId='" . $_SESSION['ACGCompanyId'] . "' ORDER BY emp_name ASC", $db);
                while ($ef_row = DB_fetch_array($ef_sql)) {
                ?>
                <option value="<?php echo $ef_row['id']; ?>" <?php echo ($_GET['filter_emp'] == $ef_row['id'] ? 'selected' : ''); ?>>
                    <?php echo $ef_row['emp_code'] . ' - ' . $ef_row['emp_name']; ?>
                </option>
                <?php } ?>
            </select>
        </td>
        <td width="15%" align="right">Filter by Year</td>
        <td width="20%">
            <select name="filter_year">
                <option value="">--- All Years ---</option>
                <?php for ($yr = date('Y'); $yr >= 2015; $yr--) { ?>
                <option value="<?php echo $yr; ?>" <?php echo ($_GET['filter_year'] == $yr ? 'selected' : ''); ?>><?php echo $yr; ?></option>
                <?php } ?>
            </select>
        </td>
        <td><input type="submit" class="search" value="Search" /></td>
    </tr>
</table>
</form>
<br>

<table cellpadding="3" cellspacing="0" border="0" width="100%" class="thborder">
    <tr>
        <th width="5%">#</th>
        <th width="20%">Employee</th>
        <th width="8%">Year</th>
        <th width="10%">Date</th>
        <th width="8%" class="text-center">Punctuality</th>
        <th width="8%" class="text-center">Work Quality</th>
        <th width="8%" class="text-center">Team Work</th>
        <th width="8%" class="text-center">Knowledge</th>
        <th width="8%" class="text-center">Communication</th>
        <th width="7%" class="text-center">Score</th>
        <th width="8%" class="text-center">Rating</th>
        <th width="4%" class="text-center">Edit</th>
        <th width="4%" class="text-center">Delete</th>
    </tr>
    <?php
    $where = "pa.CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
    if (!empty($_GET['filter_emp']))  { $where .= " AND pa.emp_id='"        . $_GET['filter_emp']  . "'"; }
    if (!empty($_GET['filter_year'])) { $where .= " AND pa.appraisal_year='" . $_GET['filter_year'] . "'"; }

    $list_sql = DB_query(
        "SELECT pa.*, em.emp_code, em.emp_name
         FROM $table pa
         LEFT JOIN empmaster em ON em.id = pa.emp_id
         WHERE $where
         ORDER BY pa.appraisal_year DESC, em.emp_name ASC",
        $db
    );
    $sno = 1;
    while ($row = DB_fetch_array($list_sql)) {
        $badge = '';
        switch ($row['overall_rating']) {
            case 'Excellent': $badge = 'color:#006600;font-weight:bold;'; break;
            case 'Very Good': $badge = 'color:#3366cc;font-weight:bold;'; break;
            case 'Good':      $badge = 'color:#009900;';                  break;
            case 'Average':   $badge = 'color:#cc6600;';                  break;
            default:          $badge = 'color:#cc0000;';                  break;
        }
    ?>
    <tr>
        <td align="center"><?php echo $sno++; ?></td>
        <td><?php echo htmlspecialchars($row['emp_code'] . ' - ' . $row['emp_name']); ?></td>
        <td align="center"><?php echo $row['appraisal_year']; ?></td>
        <td align="center"><?php echo ConvertSQLDate($row['appraisal_date']); ?></td>
        <td align="center"><?php echo $row['punctuality']; ?></td>
        <td align="center"><?php echo $row['work_quality']; ?></td>
        <td align="center"><?php echo $row['teamwork']; ?></td>
        <td align="center"><?php echo $row['knowledge']; ?></td>
        <td align="center"><?php echo $row['communication']; ?></td>
        <td align="center"><b><?php echo $row['total_score']; ?>/25</b></td>
        <td align="center"><span style="<?php echo $badge; ?>"><?php echo $row['overall_rating']; ?></span></td>
        <td align="center">
            <?php if ($_SESSION['frmEdit'] == '1') { ?>
            <a href="<?php echo $rurl . '&id=' . $row['id'] . '&action=Edit'; ?>" class="link">
                <img src="images/icon-edit.png" width="15" title="Edit" />
            </a>
            <?php } else { ?>
            <img src="images/icon-edit.png" width="15" style="opacity:0.6;" title="No Permission to Edit" />
            <?php } ?>
        </td>
        <td align="center">
            <?php if ($_SESSION['frmDelete'] == '1') { ?>
            <a href="<?php echo $rurl . '&id=' . $row['id'] . '&action=Delete'; ?>"
               onclick="return confirm('Are you sure you want to delete this appraisal record?')" class="link">
                <img src="images/Icon_Delete.png" width="13" title="Delete" />
            </a>
            <?php } else { ?>
            <img src="images/Icon_Delete.png" width="15" style="opacity:0.6;" title="No Permission to Delete" />
            <?php } ?>
        </td>
    </tr>
    <?php } ?>
</table>

<?php } ?>
</div>
</div>

<script type="text/javascript">
function calcTotal() {
    var fields = ['punctuality', 'work_quality', 'teamwork', 'knowledge', 'communication'];
    var total = 0;
    for (var i = 0; i < fields.length; i++) {
        var radios = document.getElementsByName(fields[i]);
        for (var j = 0; j < radios.length; j++) {
            if (radios[j].checked) {
                total += parseInt(radios[j].value);
                break;
            }
        }
    }
    document.getElementById('total_score_display').value = total;
    var rating = '';
    if      (total >= 23) { rating = 'Excellent'; document.getElementById('overall_rating_display').style.color = '#006600'; }
    else if (total >= 18) { rating = 'Very Good';  document.getElementById('overall_rating_display').style.color = '#3366cc'; }
    else if (total >= 13) { rating = 'Good';       document.getElementById('overall_rating_display').style.color = '#009900'; }
    else if (total >= 8)  { rating = 'Average';    document.getElementById('overall_rating_display').style.color = '#cc6600'; }
    else                  { rating = 'Poor';       document.getElementById('overall_rating_display').style.color = '#cc0000'; }
    document.getElementById('overall_rating_display').innerHTML = rating;
}

function validate() {
    if (document.getElementById('emp_id').value == '0' || document.getElementById('emp_id').value == '') {
        alert('Please select an Employee');
        document.getElementById('emp_id').focus();
        return false;
    }
    if (document.getElementById('appraisal_year').value == '0' || document.getElementById('appraisal_year').value == '') {
        alert('Please select Appraisal Year');
        document.getElementById('appraisal_year').focus();
        return false;
    }
    if (document.getElementById('appraisal_date').value == '') {
        alert('Please enter Appraisal Date');
        document.getElementById('appraisal_date').focus();
        return false;
    }
    return true;
}
</script>
