<?php
/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
ob_start();
include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');

include('includes/SQL_CommonFunctions.inc');
include('includes/GetPaymentMethods.php');
include('includes/GetPrice.inc');
?>

		
  					
	<script src="angular/angular.min.js"></script>  
        
 
     

     
     
		

   
  
 									
									<?php
//this is where you paste. Below paste it:

$userid = $_SESSION['UserID'];



// ── HANDLE ADD / EDIT ───────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF check
    if (!isset($_POST['FormID']) || $_POST['FormID'] !== $_SESSION['FormID']) {
        prnMsg(_('Invalid form submission'), 'error');
        exit;
    }

    $action      = $_POST['actionType'];
    $periodid     = isset($_POST['periodid'])     ? (int)$_POST['periodid']     : 0;
    $periodId    = (int)$_POST['periodid'];
    $employeeId  = $_POST['employeeid'];
    $type        = $_POST['type'];
    $adjustments = (float)$_POST['adjustments'];
    $remarks     = addslashes($_POST['remarks']);

    // previous balance
    $last = DB_fetch_array(
      DB_query(
        "SELECT balance AS last_bal
           FROM leave_register_bereavement_leave
          WHERE employeeid='$employeeId'
            AND type='$type'
          ORDER BY periodid DESC
          LIMIT 1"
      )
    );
    $opening = $last ? (float)$last['last_bal'] : 0.0;

    // original accruals if editing
    if ($action === 'edit') {
        $orig = DB_fetch_array(
          DB_query("SELECT accruals FROM leave_register_bereavement_leave WHERE periodid='$periodid'")
        );
        $accruals = (float)$orig['accruals'];
    } else {
        $accruals = 0.0;
    }

    // compute new balance
    $newBalance = $opening + $accruals + $adjustments;
    $logs       = addslashes("$userid {$action}ed adjustment {$adjustments} on ".date('Y-m-d H:i:s'));

    if ($action === 'add') {
        DB_query("
          INSERT INTO leave_register_bereavement_leave
            (periodid, payid, employeeid, type,
             opening_balance, accruals, adjustments,
             balance, remarks, logs)
          VALUES
            ('$periodId', NULL, '$employeeId', '$type',
             '$opening', '$accruals', '$adjustments',
             '$newBalance', '$remarks', '$logs')
        ", _('Could not add leave record'));
        prnMsg(_('Record added'), 'success');
    } else {
        DB_query("
          UPDATE leave_register_bereavement_leave
             SET periodid         = '$periodId',
                 employeeid       = '$employeeId',
                 type             = '$type',
                 opening_balance  = '$opening',
                 accruals         = '$accruals',
                 adjustments      = '$adjustments',
                 balance          = '$newBalance',
                 remarks          = '$remarks',
                 logs             = '$logs'
           WHERE periodid = '$periodid'
        ", _('Could not update record'));
        prnMsg(_('Record updated'), 'success');
    }
}

// ── FETCH ALL ROWS ──────────────────────────────────────────
$res = DB_query("
  SELECT
    lr.leaveid,
    lr.periodid,
    COALESCE(cm.period,'N/A') AS period_label,
    lr.payid,
    lr.employeeid,
    CONCAT(em.first_name,' ',em.last_name) AS emp_name,
    lr.type,
    lr.opening_balance,
    lr.accruals,
    lr.adjustments,
    lr.balance,
    lr.remarks,
    lr.logs
  FROM leave_register_bereavement_leave lr
  LEFT JOIN calendar_management cm ON lr.periodid = cm.id
  LEFT JOIN employeemaster em     ON lr.employeeid = em.employeeid
  ORDER BY lr.periodid DESC
");
?>

  <meta charset="UTF-8">
  <title>Leave Register</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
  <link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet"/>
  <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css" rel="stylesheet"/>
  <link href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css" rel="stylesheet"/>

<div class="container my-4">
  <h2>Leave Register</h2>
  <button id="btnAdd" class="btn btn-success mb-2">Add Record</button>
  <div class="table-responsive">
    <table id="leaveTable" class="table table-striped nowrap" style="width:100%">
      <thead>
        <tr>
          <th>leaveid</th>
          <th>Period</th>
          <th>PayID</th>
          <th>Employee</th>
          <th>Type</th>
          <th>Opening</th>
          <th>Accruals</th>
          <th>Adjust</th>
          <th>Balance</th>
          <th>Remarks</th>
          <th>Logs</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php while ($r = DB_fetch_array($res)): ?>
        <tr data-periodid="<?= $r['leaveid'] ?>"
            data-periodid="<?= $r['periodid'] ?>"
            data-employeeid="<?= $r['employeeid'] ?>">
          <td><?= $r['periodid'] ?></td>
          <td><?= htmlspecialchars($r['period_label']) ?></td>
          <td><?= $r['payid'] ?></td>
          <td><?= htmlspecialchars($r['employeeid'].' - '.$r['emp_name']) ?></td>
          <td><?= htmlspecialchars($r['type']) ?></td>
          <td><?= $r['opening_balance'] ?></td>
          <td><?= $r['accruals'] ?></td>
          <td><?= $r['adjustments'] ?></td>
          <td><?= $r['balance'] ?></td>
          <td><?= htmlspecialchars($r['remarks']) ?></td>
          <td><?= htmlspecialchars($r['logs']) ?></td>
          <td><button class="btn btn-sm btn-primary editBtn">Edit</button></td>
        </tr>
        <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Modal -->
<div id="leaveModal" class="modal fade" tabindex="-1">
  <div class="modal-dialog">
    <form id="leaveForm" method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Leave Record</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="FormID" value="<?= $_SESSION['FormID'] ?>" />
        <input type="hidden" name="actionType" id="actionType" />
        <input type="hidden" name="periodid" id="periodid" />

        <div class="mb-3">
          <label class="form-label">Period</label>
          <select name="periodid" id="periodid" class="form-select" required>
            <option value="">-- Select Period --</option>
            <?php
            $pQ = DB_query("SELECT id,period FROM calendar_management ORDER BY id DESC");
            while ($p = DB_fetch_array($pQ)) {
              echo "<option value='{$p['id']}'>#{$p['id']} - {$p['period']}</option>";
            }
            ?>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">Employee</label>
          <select name="employeeid" id="employeeid" class="form-select" required>
            <option value="">-- Select Employee --</option>
            <?php
            $eQ = DB_query("SELECT employeeid,first_name,last_name FROM employeemaster");
            while ($emp = DB_fetch_array($eQ)) {
              $n = htmlspecialchars($emp['first_name'].' '.$emp['last_name']);
              echo "<option value='{$emp['employeeid']}'>#{$emp['employeeid']} - {$n}</option>";
            }
            ?>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">Type</label>
          <select name="type" id="type" class="form-select" required>
            <option>Annual Leave</option>
            <option>Sick Leave</option>
            <option>Bereavement Leave</option>
            <option>Maternity Leave</option>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label">Opening Balance</label>
          <input type="text" id="opening_balance" class="form-control" disabled>
        </div>
        <div class="mb-3">
          <label class="form-label">Accruals</label>
          <input type="text" id="accruals" class="form-control" disabled>
        </div>
        <div class="mb-3">
          <label class="form-label">Adjustments</label>
          <input type="number" step="0.01" name="adjustments" id="adjustments"
                 class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label">Balance</label>
          <input type="text" id="balance" class="form-control" disabled>
        </div>
        <div class="mb-3">
          <label class="form-label">Remarks</label>
          <textarea name="remarks" id="remarks" class="form-control"></textarea>
        </div>
        <div class="mb-3">
          <label class="form-label">Logs</label>
          <input type="text" id="logs" class="form-control" disabled>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Save</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
      </div>
    </form>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.0/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script>
$(function(){
  var table = $('#leaveTable').DataTable({
    responsive: true,
    autoWidth: false,
    paging: true,
    pageLength: 10,
    dom: 'Bfrtip',
    buttons: ['excel','pdf'],
    columnDefs: [{ targets: -1, orderable: false }]
  });

  $('#btnAdd').click(function(){
    $('#leaveForm')[0].reset();
    $('#actionType').val('add');
    $('#periodid').val('');
    $('.modal-title').text('Add Leave Record');
    $('#opening_balance,#accruals,#balance,#logs').val('');
    new bootstrap.Modal($('#leaveModal')).show();
  });

  function fetchOpening(){
    var e=$('#employeeid').val(), t=$('#type').val();
    if(!e||!t) return;
    $.post('fetch_opening.php',{employeeid:e,type:t},function(d){
      $('#opening_balance').val(d.opening.toFixed(2));
      $('#accruals').val((d.accruals||0).toFixed(2));
      $('#balance').val(d.opening.toFixed(2));
      $('#logs').val('');
    },'json');
  }
  $('#employeeid,#type').on('change', fetchOpening);

  $('#adjustments').on('input',function(){
    var o=parseFloat($('#opening_balance').val())||0,
        a=parseFloat($('#accruals').val())||0,
        adj=parseFloat(this.value)||0,
        nb=o+a+adj;
    $('#balance').val(nb.toFixed(2));
    $('#logs').val('<?= $userid ?> adjusted '+adj+' on '+new Date().toLocaleString());
  });

  $('#leaveTable').on('click','.editBtn',function(){
    var tr=$(this).closest('tr'),
        data=table.row(tr).data();
    $('#actionType').val('edit');
    $('#periodid').val(tr.data('periodid'));
    $('#periodid').val(tr.data('periodid'));
    $('#employeeid').val(tr.data('employeeid')).trigger('change');
    $('#type').val(data[4]).trigger('change');
    $('#opening_balance').val(data[5]);
    $('#accruals').val(data[6]);
    $('#adjustments').val(data[7]);
    $('#balance').val(data[8]);
    $('#remarks').val(data[9]);
    $('#logs').val(data[10]);
    $('.modal-title').text('Edit Leave '+tr.data('periodid'));
    new bootstrap.Modal($('#leaveModal')).show();
  });
});
</script>





<?php

			  
 	echo '</div >';
	?>
						

		
					</div>
				</div>
			</div>
					
					

						<!--end:: Widgets/Stats-->

						<!--Begin::Section-->
						
 
		<!-- end::Quick Sidebar -->

		<!-- begin::Scroll Top -->
		<div id="m_scroll_top" class="m-scroll-top">
			<i class="la la-arrow-up"></i>
		</div>

		<!-- end::Scroll Top -->

		<!-- begin::Quick Nav -->
		

		<!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

		<!--end::Page Scripts -->
	</body>

	<!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
	$_SESSION['Module'] = $_GET['Application'];
}








//include('includes/footer.inc');

function GetRptLinks($GroupID) {
/*
This function retrieves the reports given a certain group id as defined in /reports/admin/defaults.php
in the acssociative array $ReportGroups[]. It will fetch the reports belonging solely to the group
specified to create a list of links for insertion into a table to choose a report. Two table sections will
be generated, one for standard reports and the other for custom reports.
*/
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) { // then there are reports to show, show by grouping
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			// now fetch the form groups that are a part of this group (List after reports)
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']); // break into main group and form group array
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>



<script type="text/javascript">
jQuery(document).on("ready xcrudafterrequest",function(){
    
});
</script>