
<?
$defaultTimeZone='UTC';
if(date_default_timezone_get()!=$defaultTimeZone){
	date_default_timezone_set($defaultTimeZone);
}

/* 
if(isset($_REQUEST['delete']) && $_REQUEST['delete'] != ''){
	mysqli_query($conn,"DELETE FROM appointment WHERE id='".$_REQUEST['delete']."' ");
}	
 */
$where = "";
$next_page_condition 	= "";
$leave_type 	= isset($_REQUEST['leave_type']) ? $_REQUEST['leave_type'] : "";
if(isset($leave_type) && $leave_type !=""){
	$where .= "  leave_holiday_type = '$leave_type' AND";
	$next_page_condition 	.= "&leave_type=$leave_type";
}
$employee_name_id 	= isset($_REQUEST['employee_name_id']) ? $_REQUEST['employee_name_id'] : "";
if(isset($employee_name_id) && $employee_name_id !=""){
	$where .= "  employee_name_id = '$employee_name_id' AND";
	$next_page_condition 	.= "&employee_name_id=$employee_name_id";
}

$current_month_array = array();
$current_month_appointment_array = array();
$current_month_appointment_html_array = array();
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'view_calendar'){	
	$year_month = $_REQUEST['year_month'];
	$year_year = $_REQUEST['year_year'];
}else{
	$year_month = date('m');
	$year_year = date('Y');
}

$next_page_condition 	.= "&action=view_calendar";
$next_page_condition 	.= "&year_month=".$year_month;
$next_page_condition 	.= "&year_year=".$year_year;


$date_string = "01-".$year_month."-".$year_year;
$first_day_of_current_month = $year_year."-".$year_month."-01";
$number_of_days_in_month = cal_days_in_month(CAL_GREGORIAN, $year_month, $year_year);
$last_day_of_current_month = $year_year."-".$year_month."-".$number_of_days_in_month;


for($i=1;$i<=$number_of_days_in_month;$i++){
	array_push($current_month_array,str_pad($i,2,0,STR_PAD_LEFT)."-".$year_month."-".$year_year);
}

$where .= "(
    (
        leave_holiday_start_date BETWEEN '$first_day_of_current_month' AND '$last_day_of_current_month'
        OR leave_holiday_end_date BETWEEN '$first_day_of_current_month' AND '$last_day_of_current_month'
        OR (
            leave_holiday_start_date < '$first_day_of_current_month' 
            AND leave_holiday_end_date > '$last_day_of_current_month'
        )
    ) 
    AND is_authorised = '1'
)";
$where_listing .= "(
    (
        leave_holiday_start_date BETWEEN '$first_day_of_current_month' AND '$last_day_of_current_month'
        OR leave_holiday_end_date BETWEEN '$first_day_of_current_month' AND '$last_day_of_current_month'
        OR (
            leave_holiday_start_date < '$first_day_of_current_month' 
            AND leave_holiday_end_date > '$last_day_of_current_month'
        )
    ))";

?>
<style>
.approved-row {
    background-color: #d4edda !important; /* Light green */
}

.rejected-row {
    background-color: #f8d7da !important; /* Light red */
}

</style>
<link rel="stylesheet" href="../css/SimpleCalendar.css" />
<section class="content-header hide">
  <h1 style="float:left;margin-bottom:10px;">
	Appointment Management
  </h1>
  <div style="floar:right;float:right;display:none;">
	<a href="<?php echo $siteURL ?>/appointment/index?page=view_appointment_for_admin"><i class="fa fa-list"></i> <span>List View</span></a>
  </div>
</section>
<section class="content">
	<div class="container-fluid row">
			<div class="col-lg-9">
			<div class="box">
				<div class="box-body">
					<form class="form-horizontal noprint"  id="view_calender_form" action="index?page=view&action=view_calendar" method="post">
						<div class="row">
						  <!-- <div class="col-sm-2" id="year_div">
						   <label for="Years" class="control-label">Years</label>
							<?
								$gsi->getYearList("year_year",$year_year,"100%",false);
							?>
						   </div>
						   <div class="col-sm-4" id="month_div" style="height: 60px;">
						   <label for="Months" class="control-label">Months</label>
							   <div class="col-sm-12">
								<span id="left_scroll" style="float: left;margin: 8px 9px 0 0;cursor:pointer;"> <i class="fa fa-fw fa-arrow-left"></i></span>
								<?
									$gsi->getYearMonth("year_month",$year_month,"78%",false);
								?>
								<span id="right_scroll" style="float: left;margin: 8px 0 0 9px;cursor:pointer;"> <i class="fa fa-fw fa-arrow-right"></i></span>
							   </div>
						   </div>
						   <div class="col-sm-2 " id="month_div">
						   <label for="Months" class="control-label">Employee</label>
							<? $gsi->getEmployeeList("employee_name_id", $employee_name_id, "100%", false, "form-control"); ?>
						   </div> 
						   <div class="col-sm-2 " id="month_div">
						   <label for="Months" class="control-label">Leave Type</label>
							<?
								$gsi->getLeaveType("leave_type",$leave_type,"78%",false);
							?>
						   </div>-->
						  
						  <div class="col-sm-2">
						     <br>
							<a href="" onClick="window.print();" id="print_button" class="btn btn-default" style="float:right !important;"><i class="fa fa-print"></i> Print</a>
						  </div>
						</div>
					</form>
					<!--<div class="mt-3">
					<?php
					
					?>
				</div>-->
				<div class="mt-3">
				<?php
$view_mode = isset($_REQUEST['view_mode']) ? $_REQUEST['view_mode'] : '4weeks';

$range_start = new DateTime('today');
$range_end   = clone $range_start;

switch ($view_mode) {
    case '2weeks': $range_end->modify('+13 days'); break;
    case 'month':  $range_end->modify('+29 days'); break;
    default:       $range_end->modify('+27 days'); break; // 4 weeks
}

$range_start_str = $range_start->format('Y-m-d');
$range_end_str   = $range_end->format('Y-m-d');


// --- 2. Pull all approved leave/holiday records in range ---
$sql_leaves = "
    SELECT
        lhm.employee_name_id,
        lhm.leave_holiday_start_date,
        lhm.leave_holiday_end_date,
        lhm.leave_holiday_type,
        lhm.is_authorised,
		lhm.is_annual_holiday,
		lhm.is_sickness,
		lhm.is_authorised_absence,
		lhm.is_unauthorised_absence,
		lhm.is_late
    FROM leave_holiday_management lhm
    WHERE
        is_authorised = '1'
        AND (
            leave_holiday_start_date <= '$range_end_str'
            AND leave_holiday_end_date >= '$range_start_str'
        )
    ORDER BY lhm.employee_name_id, lhm.leave_holiday_start_date ASC
";

$rs_leaves = mysqli_query($conn, $sql_leaves);

// Group leave records by employee_name_id
$leaves_by_employee = [];
if ($rs_leaves && mysqli_num_rows($rs_leaves) > 0) {
    while ($row = mysqli_fetch_assoc($rs_leaves)) {
        $eid = $row['employee_name_id'];
        if (!isset($leaves_by_employee[$eid])) {
            $leaves_by_employee[$eid] = [];
        }
        $leaves_by_employee[$eid][] = [
            'start' => $row['leave_holiday_start_date'],  // "Y-m-d"
            'end'   => $row['leave_holiday_end_date'],    // "Y-m-d"
            'type' => (
				$row['is_annual_holiday'] ? 'annual' :
				($row['is_sickness'] ? 'sickness' :
				($row['is_authorised_absence'] ? 'authorised' :
				($row['is_unauthorised_absence'] ? 'unauthorised' :
				($row['is_late'] ? 'late' :
				($row['leave_holiday_type'] == 1 ? 'holiday' : 'leave')
			))))
			),
        ];
    }
}

$employee_filter_sql = "";

$sql_employees = "
    SELECT id, uname AS name
    FROM admin
    WHERE clock_no IS NOT NULL AND clock_no != ''
    ORDER BY uname ASC
";

$rs_employees = mysqli_query($conn, $sql_employees);
$sql_generic_holidays = "
    SELECT holiday_date
    FROM admin_holidays
    WHERE holiday_date BETWEEN '$range_start_str' AND '$range_end_str'
";

$rs_generic_holidays = mysqli_query($conn, $sql_generic_holidays);

$generic_holidays = [];

if ($rs_generic_holidays && mysqli_num_rows($rs_generic_holidays) > 0) {
    while ($row = mysqli_fetch_assoc($rs_generic_holidays)) {
        $generic_holidays[] = $row['holiday_date'];
    }
}
$employees_data = [];
if ($rs_employees && mysqli_num_rows($rs_employees) > 0) {
    while ($emp = mysqli_fetch_assoc($rs_employees)) {
        $eid = $emp['id'];

        // Build initials if not stored separately
        if (empty($emp['initials'])) {
            $parts    = explode(' ', trim($emp['name']));
            $initials = '';
            foreach ($parts as $p) {
                $initials .= strtoupper(substr($p, 0, 1));
            }
            $initials = substr($initials, 0, 2);
        } else {
            $initials = strtoupper($emp['initials']);
        }

        $employees_data[] = [
            'id'       => $eid,
            'name'     => $emp['name'],
            'initials' => $initials,
            'leaves'   => isset($leaves_by_employee[$eid]) ? $leaves_by_employee[$eid] : [],
        ];
    }
}

// --- 4. Encode for JS injection ---
$employees_json   = json_encode($employees_data,   JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT);
$range_start_json = json_encode($range_start_str);
$range_end_json   = json_encode($range_end_str);
$view_mode_json   = json_encode($view_mode);
$generic_holidays_json = json_encode($generic_holidays);
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>

.lc-dot.annual        { background:#9333ea; color:#fff; }   /* Purple */
.lc-dot.sickness      { background:#f59e0b; color:#fff; }   /* Orange */
.lc-dot.authorised    { background:#10b981; color:#fff; }   /* Green */
.lc-dot.unauthorised  { background:#ef4444; color:#fff; }   /* Red */
.lc-dot.late          { background:#dc2626; color:#fff; }   /* Dark red */
.lc-wrap *         { box-sizing: border-box; margin: 0; padding: 0; }
.lc-wrap           { font-family: inherit; padding: 0; }
.lc-toolbar        { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; flex-wrap: wrap; }
.lc-toolbar .lc-btn-primary { background: #1a7a4a; color: #fff; border: none; border-radius: 6px;
                               padding: 7px 14px; font-size: 13px; cursor: pointer; }
.lc-toolbar input[type=text],
.lc-toolbar select { border: 1px solid #ccc; border-radius: 6px; padding: 6px 10px;
                      font-size: 13px; background: #fff; }
.lc-sync           { margin-left: auto; font-size: 12px; color: #2563eb;
                      text-decoration: underline; cursor: pointer; }
.lc-outer          { overflow-x: auto; border-radius: 8px;
                      border: 1px solid #e5e7eb; background: #fff; }
table.lc-table     { border-collapse: collapse; width: 100%; }
table.lc-table th,
table.lc-table td  { border: 1px solid #f0f0f0; font-size: 12px; }
table.lc-table thead th { background: #f9fafb; color: #6b7280; font-weight: 500;
                           text-align: center; padding: 5px 3px; white-space: nowrap; }
th.lc-emp-col      { text-align: left; padding-left: 10px; width: 180px;
                      min-width: 160px; font-size: 12px; color: #111; font-weight: 500; }
td.lc-emp-cell     { padding: 4px 8px; background: #f9fafb; min-width: 160px; }
.lc-emp-row        { display: flex; align-items: center; gap: 8px; }
.lc-avatar         { width: 28px; height: 28px; border-radius: 50%;
                      display: flex; align-items: center; justify-content: center;
                      font-size: 11px; font-weight: 600; flex-shrink: 0; }
.lc-emp-name       { font-size: 12px; font-weight: 500; color: #111; }
td.lc-day          { text-align: center; padding: 4px 2px; height: 42px;
                      min-width: 34px; cursor: default; }
td.lc-day.weekend  { background: #fafafa; }
td.lc-day.lc-today-col { background: #ecfdf5; }
.lc-dot            { display: inline-flex; align-items: center; justify-content: center;
                      border-radius: 50%; width: 26px; height: 26px;
                      font-size: 11px; font-weight: 500; }
.lc-dot.leave      { background: #d1fae5; color: #065f46; }
.lc-dot.holiday    { background: #dbeafe; color: #1e40af; }
.lc-dot.today      { background: #1a7a4a; color: #fff; }
.lc-dot.today-leave { background: #065f46; color: #a7f3d0; }
.lc-num            { font-size: 12px; color: #9ca3af; }
.lc-legend         { display: flex; gap: 16px; margin-top: 10px; flex-wrap: wrap; }
.lc-legend-item    { display: flex; align-items: center; gap: 6px;
                      font-size: 12px; color: #6b7280; }
.lc-legend-dot     { width: 14px; height: 14px; border-radius: 50%; }
</style>

<div class="lc-wrap">

  <div class="lc-toolbar">
    <button class="lc-btn-primary hide" onclick="void(0)">
      <i class="fa fa-plushide"></i> Request time off
    </button>
    <input type="text" id="lcSearch" placeholder="&#x1F50D; Search" oninput="lcRender()">
    <select id="lcTeam" onchange="lcRender()" class="hide">
      <option value="">All teams</option>
      <!-- Add department options here if needed -->
    </select>
    <select id="lcView" onchange="lcRender()">
      <option value="4weeks"  <?= $view_mode === '4weeks' ? 'selected' : '' ?>>Next 4 weeks</option>
      <option value="month"   <?= $view_mode === 'month'  ? 'selected' : '' ?>>This month</option>
      <option value="2weeks"  <?= $view_mode === '2weeks' ? 'selected' : '' ?>>Next 2 weeks</option>
    </select>
    <span class="lc-sync hide">Sync with my calendar</span>
  </div>

  <div class="lc-outer">
    <table class="lc-table" id="lcTable"></table>
  </div>

  <div class="lc-legend">
    <div class="lc-legend-item">
      <div class="lc-legend-dot" style="background:#1a7a4a;"></div> Today
    </div>
    <div class="lc-legend-item">
  <div class="lc-legend-dot" style="background:#9333ea;"></div> Annual Holiday
</div>
<div class="lc-legend-item">
  <div class="lc-legend-dot" style="background:#f59e0b;"></div> Sickness
</div>
<div class="lc-legend-item">
  <div class="lc-legend-dot" style="background:#10b981;"></div> Authorised
</div>
<div class="lc-legend-item">
  <div class="lc-legend-dot" style="background:#ef4444;"></div> Unauthorised
</div>
<div class="lc-legend-item">
  <div class="lc-legend-dot" style="background:#dc2626;"></div> Late
</div>
    <div class="lc-legend-item">
      <div class="lc-legend-dot" style="background:#dbeafe; border:1px solid #93c5fd;"></div> Holiday
    </div>
  </div>
</div>

<script>
var lcEmployees  = <?= $employees_json ?>;
var lcViewMode   = <?= $view_mode_json ?>;
var lcGenericHolidays = <?= $generic_holidays_json ?>;
// Avatar color palette
var lcColors = [
  {bg:'#e0e7ff', fg:'#3730a3'}, {bg:'#fce7f3', fg:'#9d174d'},
  {bg:'#d1fae5', fg:'#065f46'}, {bg:'#fee2e2', fg:'#991b1b'},
  {bg:'#fef3c7', fg:'#92400e'}, {bg:'#ede9fe', fg:'#4c1d95'},
  {bg:'#e0f2fe', fg:'#075985'}, {bg:'#fef9c3', fg:'#713f12'},
];

function lcGetDates(viewMode) {
  var today = new Date(); today.setHours(0,0,0,0);
  var days = viewMode === '2weeks' ? 14 : viewMode === 'month' ? 30 : 28;
  var out = [];
  for (var i = 0; i < days; i++) {
    var d = new Date(today);
    d.setDate(today.getDate() + i);
    out.push(d);
  }
  return out;
}

function lcDateStr(d) {
  // Returns "Y-m-d" for comparison with PHP dates
  var y = d.getFullYear();
  var m = ('0'+(d.getMonth()+1)).slice(-2);
  var dd = ('0'+d.getDate()).slice(-2);
  return y+'-'+m+'-'+dd;
}

function lcBuildLeaveMap(leaves) {
  // Returns {  "Y-m-d": "leave"|"holiday"  } for fast lookup
  var map = {};
  leaves.forEach(function(l) {
    var cur = new Date(l.start); cur.setHours(0,0,0,0);
    var end = new Date(l.end);   end.setHours(0,0,0,0);
    while (cur <= end) {
      map[lcDateStr(cur)] = l.type;
      cur.setDate(cur.getDate() + 1);
    }
  });
  return map;
}

function lcRender() {
  var view   = document.getElementById('lcView').value;
  var search = document.getElementById('lcSearch').value.toLowerCase();
  var dates  = lcGetDates(view);
  var today  = new Date(); today.setHours(0,0,0,0);
  var todayStr = lcDateStr(today);
  var dayNames = ['Su','Mo','Tu','We','Th','Fr','Sa'];

  var filtered = lcEmployees.filter(function(e) {
    return e.name.toLowerCase().indexOf(search) !== -1;
  });

  // Build header
  var html = '<thead><tr><th class="lc-emp-col">Employee</th>';
  dates.forEach(function(d) {
    var isToday = lcDateStr(d) === todayStr;
    var style = isToday ? ' style="color:#1a7a4a;font-weight:700;"' : '';
    html += '<th'+style+'>'+dayNames[d.getDay()]+'<br>'+d.getDate()+'</th>';
  });
  html += '</tr></thead><tbody>';

  // Build rows
  filtered.forEach(function(emp, idx) {
    var c = lcColors[idx % lcColors.length];
    var leaveMap = lcBuildLeaveMap(emp.leaves);

    html += '<tr>';
    html += '<td class="lc-emp-cell">'
          + '<div class="lc-emp-row">'
          + '<div class="lc-avatar" style="background:'+c.bg+';color:'+c.fg+';">'+emp.initials+'</div>'
          + '<span class="lc-emp-name">'+emp.name+'</span>'
          + '</div></td>';

    dates.forEach(function(d) {
      var ds      = lcDateStr(d);
      var isToday = ds === todayStr;
      var weekend = (d.getDay() === 0 || d.getDay() === 6);
      var ltype   = leaveMap[ds] || null;
      if (!ltype && lcGenericHolidays.includes(ds)) {
			ltype = 'holiday';
		}
      var cls = 'lc-day';
      if (weekend)  cls += ' weekend';
      if (isToday)  cls += ' lc-today-col';

      var inner = '';
      if (isToday && ltype) {
        inner = '<span class="lc-dot today-leave">'+d.getDate()+'</span>';
      } else if (isToday) {
        inner = '<span class="lc-dot today">'+d.getDate()+'</span>';
      } else if (ltype) {
	    inner = '<span class="lc-dot '+ltype+'">'+d.getDate()+'</span>';
	  } else {
        inner = '<span class="lc-num">'+d.getDate()+'</span>';
      }

      html += '<td class="'+cls+'">'+inner+'</td>';
    });

    html += '</tr>';
  });

  html += '</tbody>';
  document.getElementById('lcTable').innerHTML = html;
}

// Re-render when view switcher changes (also submits to server for fresh data)
document.getElementById('lcView').addEventListener('change', function() {
  // Option A: full page reload with new view_mode (server-side data refresh)
  var url = new URL(window.location.href);
  url.searchParams.set('view_mode', this.value);
  window.location.href = url.toString();

  // Option B: just re-render client-side with existing data (comment out the above)
  // lcRender();
});

lcRender();
</script>
				</div>
			</div>
			</div>
		</div>
		<div class="col-lg-3">
		<div class="table-responsive">
			<table id="example1" class="table table-bordered table-striped">
				<thead class="hide"></thead><br>
				<tbody>
					<?php
					$query_list = "SELECT id, is_authorised,employee_name_id, leave_holiday_start_date, leave_holiday_type, leave_holiday_end_date FROM leave_holiday_management WHERE $where_listing ORDER BY id DESC";
					$sql_list = mysqli_query($conn, $query_list);
					$result = mysqli_num_rows($sql_list);
						?>
				

					<?php foreach ($sql_list as $row_holidays_list): 
					       $rowClass='';
						   if ($row_holidays_list['is_authorised'] == 1) {
								$rowClass .= 'approved-row';
							} elseif ($row_holidays_list['is_authorised'] == 2) {
								$rowClass .= 'rejected-row';
							}else {
								$rowClass .= '';
							}
					?>
						<tr class="<?= $rowClass ?>" onClick="showLeaveDetails(<?= $row_holidays_list['id'] ?>)">
							<td><?= $gsi->getEmployeeById($row_holidays_list['employee_name_id']) ?>
							<br>Type: <?= $row_holidays_list['leave_holiday_type'] == 1 ? 'Holiday' : 'Leave' ?>
							</td>
							<td>From: <?= date("d-m-Y H:i", strtotime($row_holidays_list['leave_holiday_start_date'])) ?><br>
								To: <?= date("d-m-Y H:i", strtotime($row_holidays_list['leave_holiday_end_date'])) ?>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		</div>
	</div>
<!-- Modal Popup --><!-- Modal Popup -->
<div id="leaveDetailsModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Request Details</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="zone_checking" style="display: none;">Loading...</div>
                <table class="table table-bordered">
                    <tr>
                        <th>Employee Name</th>
                        <td><span id="employee_name_idd"></span></td>
                    </tr>
                    <tr>
                        <th>Type</th>
                        <td><span id="leave_holiday_type"></span></td>
                    </tr>
                    <tr>
                        <th>From</th>
                        <td><span id="from"></span></td>
                    </tr>
                    <tr>
                        <th>To</th>
                        <td><span id="to"></span></td>
                    </tr>
                </table>

                <!-- Approval/Rejection Radio Buttons -->
                <div class="form-group">
                    <label>Action:</label>
                    <div>
                        <label class="mr-2">
                            <input type="radio" name="action" value="1" id="radioApprove"> Approve
                        </label>
                        <label>
                            <input type="radio" name="action" value="2" id="radioReject"> Reject
                        </label>
                    </div>
                </div>

                <!-- Reason textarea for rejection -->
                <div id="rejectionReasonContainer" style="display: none;">
                    <label for="rejectionReason">Rejection Reason:</label>
                    <textarea id="rejectionReason" class="form-control" rows="3" placeholder="Enter rejection reason..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success" id="submitAction">Submit</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>


<script>

    function showLeaveDetails(id) {
    $('#rejectionReasonContainer').hide();
    $('#rejectionReason').val('');
    $('input[name="action"]').prop('checked', false);

    if (id !== "") {
        $('#zone_checking').show();
        var form_data = { 'leave_id': id };

        $.ajax({
            async: true,
            type: "POST",
            url: site_url + "/modules/leave_holiday_management/index.php?page=ajax_actions&action=get_leave_details",
            data: form_data,
            success: function(result) {
                var resultObj = jQuery.parseJSON(result);
                if (resultObj.status === 1) {
                    $('#zone_checking').hide();
                    $('#leaveDetailsModal').modal('show');

                    $("#employee_name_idd").text(resultObj.employee_name_id);
                    $("#leave_holiday_type").text(resultObj.leave_holiday_type);
                    $("#from").text(resultObj.from);
                    $("#to").text(resultObj.to);

                    var action_type = resultObj.is_authorised;
                    if (action_type == 1) {
                        $('input[name="action"][value="1"]').prop('checked', true);
                        $('#rejectionReasonContainer').hide();
                    } else if (action_type == 2) {
                        $('input[name="action"][value="2"]').prop('checked', true);
                        $('#rejectionReasonContainer').show();
                        $('#rejectionReason').val(resultObj.rejection_reason);
                    } else {
                        $('input[name="action"]').prop('checked', false);
                        $('#rejectionReasonContainer').hide();
                    }

                    $("#submitAction").attr("data-id", id);
                }
            }
        });
    }
}

    // Show or hide rejection reason based on the selected radio button
    $('input[name="action"]').on('change', function() {
        if ($('#radioReject').is(':checked')) {
            $('#rejectionReasonContainer').show();
        } else {
            $('#rejectionReasonContainer').hide();
            $('#rejectionReason').val('');  
        }
    });

    $('#submitAction').on('click', function() {
		var leaveId = $('#submitAction').data('id'); 
		var action = $('input[name="action"]:checked').val(); 
		var rejectionReason = $('#rejectionReason').val().trim(); 

		if (action === 'reject' && rejectionReason === '') {
			alert('Please enter a rejection reason.');
			return;
		}
		  var data = {
			'leave_id': leaveId,
			'action_type': action === '1' ? 1 : 2, 
			'rejection_reason': action === '2' ? rejectionReason : '' 
		};



    $.ajax({
        type: "POST",
        url: site_url + "/modules/leave_holiday_management/index.php?page=ajax_actions&action=submit_leave_action",
        data: data,
        success: function(response) {
            var result = JSON.parse(response);

            if (result.status === 1) {
              //  alert("Leave approved successfully.");
                $('#leaveDetailsModal').modal('hide');
                $('tr[onclick="showLeaveDetails(' + leaveId + ')"]').addClass('approved-row').removeClass('rejected-row');
            } else if (result.status === 2) {
                //alert("Leave rejected successfully.");
                $('#leaveDetailsModal').modal('hide');
                $('tr[onclick="showLeaveDetails(' + leaveId + ')"]').addClass('rejected-row').removeClass('approved-row');
            } else {
                alert("Failed to update leave status.");
            }
        },
        error: function() {
            alert("An error occurred while processing the request.");
        }
    });
});


/* 
    // Approve button click event
    $('#approveButton').on('click', function() {
        var leaveId = $(this).data('id');

        $.ajax({
            type: "POST",
            url: site_url + "/modules/leave_holiday_management/index.php?page=ajax_actions&action=approve_leave",
            data: { 'leave_id': leaveId },
            success: function(response) {
                var result = JSON.parse(response);
                if (result.status === 1) {
                    alert("Leave approved successfully.");
                    $('#leaveDetailsModal').modal('hide');
					$('tr[onclick="showLeaveDetails(' + leaveId + ')"]').removeClass('rejected-row').addClass('approved-row');
                } else {
                    alert("Failed to approve leave.");
                }
            }
        });
    });

    // Reject button click event
    $('#rejectButton').on('click', function() {
        var leaveId = $(this).data('id');
        var reason = $('#rejectionReason').val().trim();

        if (reason === '') {
            alert('Please enter a reason for rejection.');
            $('#rejectionReasonContainer').show();
            return;
        }

        $.ajax({
            type: "POST",
            url: site_url + "/modules/leave_holiday_management/index.php?page=ajax_actions&action=reject_leave",
            data: { 'leave_id': leaveId, 'reason': reason },
            success: function(response) {
                var result = JSON.parse(response);
                if (result.status === 1) {
                    alert("Leave rejected successfully.");
                    $('#leaveDetailsModal').modal('hide');
					 $('tr[onclick="showLeaveDetails(' + leaveId + ')"]').removeClass('approved-row').addClass('rejected-row');
                } else {
                    alert("Failed to reject leave.");
                }
            }
        });
    });
 */
	</script>

	</div>
	<div class='triangle' style='width:0; height:0; border-bottom:10px solid #3c8dbc; border-left:5px solid transparent; border-right:5px solid transparent;display: none;'></div>
	<div id='floating_div' style='display: none;'></div>
</section>

<style>


.badge{
	padding: 2px 3px;
}
.event{
	display:block;
	float:left;
	width:100%;
	cursor:default;
}
#year_month{
	float:left;
	clear:right;
}
.new_select{
    -webkit-border-radius: 0;
    border-radius: 0;
    background-color: white;
    font-family: inherit;
    border: 1px solid #cccccc;
    -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
    color: rgba(0, 0, 0, 0.75);
    display: block;
    font-size: 0.875em;
    margin: 0 0 1em 0;
    padding: 0.5em;
    height: 2.3125em;
    width: 100%;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    -webkit-transition: -webkit-box-shadow 0.45s, border-color 0.45s ease-in-out;
    -moz-transition: -moz-box-shadow 0.45s, border-color 0.45s ease-in-out;
    transition: box-shadow 0.45s, border-color 0.45s ease-in-out;
}
@media print
{
	/*.noprint {display:none;}*/
	table.SimpleCalendar tbody td{
		height: 130px;
	}
	#year_div,#month_div{
		width:30%;
		float:left;
		clear:right;
	}
	#print_button{
		display:none;
	}
}
@media only screen and (min-width: 1449px){
	#year_month{
		width:78% !important;
	}
}
@media only screen and (max-width: 1349px) and (min-width: 822px)  {
	#year_month{
		width:70% !important;
	}
}
@media only screen and (max-width: 822px) and (min-width: 600px)  {
	#year_month{
		width:65% !important;
	}
}
@media only screen and (max-width: 600px) and (min-width: 450px)  {
	#year_month{
		width:50% !important;
	}
}
@media only screen and (max-width: 450px){
	#year_month{
		width:78% !important;
	}
}
</style>
<script type="text/javascript">		
$(document).ready(function() {
	//alert($(window).width());
	$(".add_appointment").click(function(){	
		$("#myModalLabel").text("Appointment Management");
		var hide_top_left = "&hide_top=1&hide_left=1";
		var app_date = $(this).attr("alt");		
		$(".modal_iframe").attr("src","<?=$config->frontEndURL?>/admin/appointment/index?page=add_appointment_for_calender&app_date="+app_date+hide_top_left);
	});
	$(".edit_appointment").click(function(){	
		$("#myModalLabel").text("Appointment Management");
		var hide_top_left = "&hide_top=1&hide_left=1";
		var id = $(this).attr("alt");		
		$(".modal_iframe").attr("src","<?=$config->frontEndURL?>/admin/appointment/index?page=add_appointment_for_calender&action=edit&id="+id+hide_top_left);
	});
	$(".close_button").click(function(){
		$(".modal_iframe").attr("src","");
		location.reload();
	});
	
	$(document).scrollTop(5); // scroll top to put header fix
	$('.event').hover(
         function (event) {
		   var span_id = $(this).children("span").attr("id");   
		   content = $("#table_"+span_id).html();
		   //alert(content);
			position = $(this).parent().position();	
			position_of_event = $(this).position();	
			position_top = position.top + position_of_event.top;
			scrollHeight = 100;
			top_position = 145;
			top_position_for_triangle = 135;
			if ($(document).scrollTop() >= scrollHeight) {
				top_position = 100;
				top_position_for_triangle = 90;
			}
			if($(window).width() < 640){
				top_position = top_position + 40;
				top_position_for_triangle = top_position_for_triangle + 40;
			}
			//alert(position.left);
			//alert($( window ).width());	
			left_position = ((position.left)*100 / $( window ).width()) + 2;
			left_position_for_triangle = ((position.left)*100 / $( window ).width()) + 10;
			$("#floating_div").css({"padding":"10px","background":"#FFF","border":"1px solid #3c8dbc","width":"auto","position":"absolute","z-index":"9999","top":position_top+top_position,"left":left_position+"%"});
			$("#floating_div").html(content);
			$(".triangle").css({"position":"absolute","z-index":"9999","top":position_top+top_position_for_triangle,"left":left_position_for_triangle+"%" });
			$(".triangle").show();
			$("#floating_div").show();
         }, 
         function () {
			$("#floating_div").css({"border":"0px solid #3c8dbc"});
			$("#floating_div").html("");
			$("#floating_div").hide();
			$(".triangle").hide();
         }
     );
	
	//$("#month_year").on("change",function() {
	$("#year_month,#year_year,#employee_name_id,#leave_type").on("change",function() {
		$("#view_calender_form").submit();
	});
	
	$("#left_scroll").on("click",function() {
		var month = $("#year_month").val();
		if(month != 1){
			var one_month_before = month - 1;
			if(one_month_before != 10 && one_month_before != 11 && one_month_before != 12){
				$("#year_month").val("0"+one_month_before);
			}else{
				$("#year_month").val(one_month_before);
			}
			$("#view_calender_form").submit();
		}
	});
	$("#right_scroll").on("click",function() {
		var month = $("#year_month").val();
		if(month != 12){
			var one_month_after = parseInt(month) + 1;
			if(one_month_after != 10 && one_month_after != 11 && one_month_after != 12){
				$("#year_month").val("0"+one_month_after);
			}else{
				$("#year_month").val(one_month_after);
			}
			
			$("#view_calender_form").submit();
		}
	});
});
</script>
<script type="text/javascript">
$(function () {
	$(".close_button").click(function(){
		$(".modal_iframe").attr("src","");
	});
	///////////////////////////// START ARCHIVING/UNARCHIVING cause///////////////////////////////////////
	$("#archive_cause").click(function(){
		if ($(".checkbox:checked").length == 0){
			alert("Please select cause");
			return false;
		}
		if(confirm("Are you sure you want archive the selected cause(s).")){
			$('#form1').attr("action","index?page=view&action=archive<?=$next_page_condition.$paging;?>");
			$('#form1').submit();
		}
	});
	$("#unarchive_cause").click(function(){
		if ($(".checkbox:checked").length == 0){
			alert("Please select cause");
			return false;
		}
		if(confirm("Are you sure you want unarchive the selected cause(s).")){
			$('#form1').attr("action","index?page=view&action=unarchive<?=$next_page_condition.$paging;?>");
			$('#form1').submit();
		}
	});
	///////////////////////////// START ARCHIVING/UNARCHIVING cause///////////////////////////////////////
	$('#check_all').click(function(){
        if($("#check_all:checked").length == 1){
            $('.checkbox').prop( "checked", true );
        }else{
            $('.checkbox').prop( "checked", false );
        }
    });
});
</script>
<script>
	function setFormAction(action) {
		const form = document.getElementById('form1');
		if (action === 'add') {
			form.action = 'index?page=add';
		} else if (action === 'add_holiday') {
			form.action = 'index?page=add_holiday';
		}
	}
	document.addEventListener("DOMContentLoaded", function() {
	  if (window.location.href.includes("page=view")) {
		document.body.classList.add("sidebar-mini", "layout-fixed", "sidebar-collapse");
	  }
   });
</script>