<?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:
// optionally hide all errors from displaying (but still log them)
ini_set('display_errors', '1');

/**
 * Insert a leave record into the specified table.
 */
function insertLeaveRecord($table, $periodId, $employeeId, $type, $opening, $accruals, $adjustments, $remarks, $balance, $logs) {
    $type    = addslashes($type);
    $remarks = addslashes($remarks);
    $logs    = addslashes($logs);
    $sql = "
      INSERT INTO {$table}
        (periodid,payid,employeeid,type,
         opening_balance,accruals,adjustments,
         remarks,balance,logs)
      VALUES
        ('{$periodId}',NULL,'{$employeeId}','{$type}',
         '{$opening}','{$accruals}','{$adjustments}',
         '{$remarks}','{$balance}','{$logs}')
    ";
    DB_query($sql, _('Could not insert leave record'));
}

/**
 * Bereavement Leave accruals → leave_register_bereavement_leave
 *
 * Logic:
 *  - Everyone must have >3 months service by period end.
 *  - If hired before Feb 1 2025, give a one-time 3-day grant (if they’ve never had one).
 *  - If hired on/after Feb 1 2025, grant 3 days on their anniversary if it falls within this period.
 *  - No rollover—each anniversary only grants once per calendar year.
 *
 * @param int $periodId  calendar_management.id
 */
function processBereavementAccruals($periodId) {

    // load period window
    $p = DB_fetch_array(DB_query(
      "SELECT start_date,end_date
         FROM calendar_management
        WHERE id = '$periodId'",
      _('Could not fetch period')
    ));
    $periodStart = new DateTime($p['start_date']);
    $periodEnd   = new DateTime($p['end_date']);

    // cutoff for pseudo-anniversary
    $cutDate = new DateTime('2025-02-01');

    // loop active employees
    $emps = DB_query("
      SELECT employeeid, start_date
        FROM employeemaster
       WHERE status = 'Active'
    ");
    while ($e = DB_fetch_array($emps)) {
        $eid      = $e['employeeid'];
        $hireDate = new DateTime($e['start_date']);

        // must have >3 months service
        $cut3m = clone $hireDate;
        $cut3m->add(new DateInterval('P3M'));
        if ($periodEnd <= $cut3m) {
            continue;
        }

        // hired before Feb 1 2025 → one-time grant
        if ($hireDate < $cutDate) {
            // skip if they already have any bereavement entry
            $chk = DB_query("
              SELECT 1
                FROM leave_register_bereavement_leave
               WHERE employeeid = '$eid'
               LIMIT 1
            ");
            if (DB_num_rows($chk) > 0) {
                continue;
            }
            // insert 3-day one-time grant
            $remarks = 'Bereavement one-time grant for pre-Feb 2025 hires';
            $logs     = 'Granted 3 days one-time';
            DB_query("
              INSERT INTO leave_register_bereavement_leave
                (periodid,payid,employeeid,type,
                 opening_balance,accruals,adjustments,
                 remarks,balance,logs)
              VALUES
                ('$periodId',NULL,'$eid','Bereavement Leave',
                 0,3,0,
                 '".addslashes($remarks)."',
                 3,
                 '".addslashes($logs)."')
            ", _('Could not insert bereavement accrual'));
        }
        else {
            // hired on/after Feb 1 2025 → check true anniversary in this window
            $years = [(int)$periodStart->format('Y')];
            if ($periodEnd->format('Y') !== $periodStart->format('Y')) {
                $years[] = (int)$periodEnd->format('Y');
            }
            foreach ($years as $yr) {
                $ann = DateTime::createFromFormat(
                    'Y-m-d',
                    "{$yr}-{$hireDate->format('m-d')}"
                );
                if ($ann && $ann >= $periodStart && $ann <= $periodEnd) {
                    // skip if already granted this year
                    $chk = DB_query("
                      SELECT 1
                        FROM leave_register_bereavement_leave lr
                        JOIN calendar_management cm ON lr.periodid = cm.id
                       WHERE lr.employeeid = '$eid'
                         AND lr.type       = 'Bereavement Leave'
                         AND YEAR(cm.end_date) = '$yr'
                       LIMIT 1
                    ");
                    if (DB_num_rows($chk) > 0) {
                        break;
                    }
                    // insert 3-day anniversary grant
                    $remarks = 'Bereavement anniversary grant on ' . $ann->format('d-m-Y');
                    $logs     = 'Granted 3 days';
                    DB_query("
                      INSERT INTO leave_register_bereavement_leave
                        (periodid,payid,employeeid,type,
                         opening_balance,accruals,adjustments,
                         remarks,balance,logs)
                      VALUES
                        ('$periodId',NULL,'$eid','Bereavement Leave',
                         0,3,0,
                         '".addslashes($remarks)."',
                         3,
                         '".addslashes($logs)."')
                    ", _('Could not insert bereavement accrual'));
                    break;  // only once per period
                }
            }
        }
    }
}








// ── HANDLE POSTS ─────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF check
    if (!isset($_POST['FormID']) || $_POST['FormID'] !== $_SESSION['FormID']) {
        prnMsg(_('This form was not submitted with a correct ID'), 'error');
        exit;
    }

    // DELETE
    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        if ($userid === 'admin') {
            $delId = (int)$_POST['id'];
            deletePeriodAndLeaves($delId);
            prnMsg("Period #{$delId} and all its leave records have been deleted.", 'success');
        } else {
            prnMsg(_('Only admin may delete periods.'), 'error');
        }
    }
    // ADD or SAVE
    elseif (
        isset($_POST['action']) &&
        ($_POST['action'] === 'add' || $_POST['action'] === 'save')
    ) {
        $sd     = $_POST['start_date'];
        $ed     = $_POST['end_date'];
        $period = 'Weekending- ' . date('d-m-Y', strtotime($ed));
        $status = $_POST['status'];

        if ($_POST['action'] === 'save') {
            DB_query(
              "UPDATE calendar_management
                  SET start_date = '{$sd}',
                      end_date   = '{$ed}',
                      period     = '{$period}',
                      status     = '{$status}'
                WHERE id = '{$_POST['id']}'",
              _('Could not update period')
            );
            $pid = $_POST['id'];
            prnMsg("Period #{$pid} updated.", 'success');
        } else {
            $now = date('Y-m-d H:i:s');
            DB_query(
              "INSERT INTO calendar_management
                (period, start_date, end_date, status, created_by, date_created)
               VALUES
                ('{$period}', '{$sd}', '{$ed}',
                 '{$status}', '{$userid}', '{$now}')",
              _('Could not create period')
            );
            $pid = DB_Last_Insert_ID();
            prnMsg("New period #{$pid} created.", 'success');
        }

        // when status moves past processing, run accruals
        if ($status == 'processing') {
		//  processDeductions();
           
			processBereavementAccruals($pid);
				
            prnMsg("Accruals processed for period #{$pid}.", 'success');
			
			
        }
    }
}

// ── PREPARE FORM DEFAULTS ────────────────────────────────────
$editMode    = false;
$form_id     = '';
$form_start  = date('Y-m-d');
$form_end    = date('Y-m-d');
$form_status = 'processing';
$form_action = 'add';

if (isset($_GET['edit'])) {
    $eid  = (int)$_GET['edit'];
    $rres = DB_query("SELECT * FROM calendar_management WHERE id = '{$eid}'");
    if ($r = DB_fetch_array($rres)) {
        $editMode    = true;
        $form_id     = $r['id'];
        $form_start  = $r['start_date'];
        $form_end    = $r['end_date'];
        $form_status = $r['status'];
        $form_action = 'save';
    }
}

// ── PAGINATION ──────────────────────────────────────────────
$perPage    = 10;
$page       = (isset($_GET['page']) && ctype_digit($_GET['page']) && $_GET['page']>0)
              ? (int)$_GET['page']
              : 1;
$offset     = ($page - 1) * $perPage;
$count      = DB_fetch_array(DB_query("SELECT COUNT(*) AS cnt FROM calendar_management"))['cnt'];
$totalPages = (int)ceil($count / $perPage);

$listSql = "
  SELECT id, period, start_date, end_date, status, created_by, date_created
    FROM calendar_management
   ORDER BY id DESC
   LIMIT {$perPage} OFFSET {$offset}";
$paginatedList = DB_query($listSql);
?>

  <style>
    .table-hover tbody tr .actions {
      opacity: 0; transition: opacity 0.2s ease-in-out;
    }
    .table-hover tbody tr:hover .actions {
      opacity: 1;
    }
  </style>

  <div class="container my-4">
    <?php // prnMsg() outputs here ?>

    <div class="d-flex justify-content-between align-items-center mb-3">
      <h2>Pay-cycle Periods</h2>
      <button class="btn btn-success" data-bs-toggle="collapse" data-bs-target="#periodForm">
        <?php echo $editMode ? 'Edit Period' : '+ Add New Period'; ?>
      </button>
    </div>

    <div class="collapse <?php echo $editMode ? 'show' : ''; ?>" id="periodForm">
      <div class="card card-body mb-4">
        <form method="post" class="row g-3">
          <input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />
          <input type="hidden" name="action" value="<?php echo $form_action; ?>" />
          <?php if ($editMode): ?>
            <input type="hidden" name="id" value="<?php echo $form_id; ?>" />
          <?php endif; ?>

          <div class="col-md-4">
            <label class="form-label">Start Date</label>
            <input type="date" name="start_date" class="form-control"
                   value="<?php echo $form_start; ?>" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">End Date</label>
            <input type="date" name="end_date" class="form-control"
                   value="<?php echo $form_end; ?>" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
              <?php foreach (['processing'] as $st): ?>
                <option value="<?php echo $st; ?>" <?php echo $form_status === $st ? 'selected' : ''; ?>>
                  <?php echo ucfirst($st); ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-12">
            <button class="btn btn-primary">
              <?php echo $editMode ? 'Save Changes' : 'Create Period'; ?>
            </button>
            <?php if ($editMode): ?>
              <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="btn btn-secondary ms-2">Cancel</a>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>

    <div class="table-responsive">
      <table class="table table-hover align-middle">
        <thead class="table-light">
          <tr>
            <th>#</th><th>Period</th><th>Start Date</th>
            <th>End Date</th><th>Status</th><th>Created By</th>
            <th>Date Created</th><th></th>
          </tr>
        </thead>
        <tbody>
          <?php while ($row = DB_fetch_array($paginatedList)): ?>
            <tr>
              <td><?php echo $row['id']; ?></td>
              <td><?php echo htmlspecialchars($row['period']); ?></td>
              <td><?php echo date('d-m-Y', strtotime($row['start_date'])); ?></td>
              <td><?php echo date('d-m-Y', strtotime($row['end_date'])); ?></td>
              <td><?php echo htmlspecialchars($row['status']); ?></td>
              <td><?php echo htmlspecialchars($row['created_by']); ?></td>
              <td><?php echo date('d-m-Y H:i', strtotime($row['date_created'])); ?></td>
              <td class="actions text-end">
                <a href="?edit=<?php echo $row['id']; ?>"
                   class="btn btn-sm btn-primary me-1">Edit</a>
                <?php if ($userid === 'admin'): ?>
                  <form method="post" class="d-inline"
                        onsubmit="return confirm('Delete period #<?php echo $row['id']; ?>?');">
                    <input type="hidden" name="FormID"
                           value="<?php echo $_SESSION['FormID']; ?>" />
                    <input type="hidden" name="action" value="delete" />
                    <input type="hidden" name="id"
                           value="<?php echo $row['id']; ?>" />
                    <button class="btn btn-sm btn-danger">Delete</button>
                  </form>
                <?php endif; ?>
              </td>
            </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>

    <!-- pagination -->
    <nav>
      <ul class="pagination justify-content-center">
        <li class="page-item <?php echo $page > 1 ? '' : 'disabled'; ?>">
          <a class="page-link" href="?page=<?php echo $page-1; ?>">&laquo; Prev</a>
        </li>
        <?php for ($p = 1; $p <= $totalPages; $p++): ?>
          <li class="page-item <?php echo $p == $page ? 'active' : ''; ?>">
            <a class="page-link" href="?page=<?php echo $p; ?>"><?php echo $p; ?></a>
          </li>
        <?php endfor; ?>
        <li class="page-item <?php echo $page < $totalPages ? '' : 'disabled'; ?>">
          <a class="page-link" href="?page=<?php echo $page+1; ?>">Next &raquo;</a>
        </li>
      </ul>
    </nav>

  </div>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>




			  
 	</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>