<style>
  /* Global Styles */
  body {
    font-family: 'Roboto', sans-serif;
    background-color: #f7f9fc;
    margin: 0;
    padding: 20px;
    color: #333;
  }

  #container {
    background: #ffffff;
    padding: 40px;
    border-radius: 12px;
    box-shadow: 0 6px 30px rgba(0, 0, 0, 0.1);
    margin: 20px auto;
    max-width: 1200px;
  }

  .table-responsive {
    overflow-x: auto;
  }

  table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 30px;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  }

  th,
  td {
    white-space: nowrap;
    /* Prevent wrapping of text in both headers and data cells */
    overflow: hidden;
    /* Hide overflow text */
    text-overflow: ellipsis;
    /* Add ellipsis if text overflows */
  }

  th {
    background-color: #2d87f0;
    color: white;
    font-weight: 700;
    text-transform: uppercase;
    padding: 15px;
  }

  td {
    padding: 15px;
    font-size: 14px;
    text-align: center;
    border: 1px solid #ddd;
    border-radius: 4px;
    color: #333;
    background-color: #ffffff;
  }


  tbody td {
    background-color: #ffffff;
    font-size: 14px;
  }

  tbody tr:nth-child(even) {
    background-color: #f9f9f9;
  }

  tbody tr:hover {
    background-color: #f1f1f1;
    cursor: pointer;
    transform: translateY(-2px);
    transition: all 0.3s ease;
  }

  /* Highlighting specific rows */
  .highlight-green {
    background-color: #28a745;
    color: white;
    font-weight: bold;
  }

  .highlight-late {
    background-color: #f44336;
    color: white;
    font-weight: bold;
  }

  .highlight-attendance {
    background-color: #ffc107;
    color: white;
    font-weight: bold;
  }

  tfoot td {
    font-weight: 600;
    background-color: #e3f2fd;
  }

  /* Button styles */
  .btn {
    padding: 12px 24px;
    font-size: 16px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-right: 10px;
    font-weight: bold;
  }

  .btn-warning {
    background-color: #f8b400;
    color: white;
  }

  .btn-warning:hover {
    background-color: #f0a800;
    transform: translateY(-2px);
  }

  /* Add margin to the button */
  .btn-success {
    margin-top: 1px;
    /* Adds space above the button */
  }

  .table-responsive {
    margin-bottom: 20px;
    /* Adds space below the table */
  }

  /* Hover effect for the button */
  .btn-success:hover {
    background-color: #45a049;
    /* Slightly darker green for hover background */
    color: #4caf50;
    /* Change text color to green on hover */
  }

  .btn-success .btn-icon-left i {
    color: #4caf50;
    /* Ensure icon color is green on hover */
  }


  /* Ensure space between icon and text */
  .btn-icon-left {
    display: flex;
    align-items: center;
  }

  .btn-icon-left i {
    margin-right: 8px;
    /* Adjust this to control the space between the icon and text */
  }


  .footer-text {
    font-size: 14px;
    color: #777;
    text-align: center;
    margin-top: 30px;
  }

  .highlight-amount {
    color: #ff4b5c;
    font-weight: 600;
  }

  /* Responsive Styles */
  @media (max-width: 768px) {
    table {
      font-size: 12px;
    }

    th,
    td {
      padding: 10px;
    }

    .btn {
      font-size: 14px;
      padding: 10px 18px;
    }
  }
</style>
<div class="table-responsive" id="container">
  <button type="button" class="btn btn-success" onclick="btnExport_monthly();">
    <span class="btn-icon-left">
      <i class="fa fa-download"></i> Download
    </span>
  </button>
  <table id="example5" style="margin-top:11px">
    <thead>
      <tr>
        <th>Name</th>
        <th>Total Attendance</th>
        <th>Absents</th>
        <th>Absent Dates</th>
        <th>Total Late</th>
        <th>Total Salary</th>
        <th>Total Over Time</th>
        <th>Over Time Amount</th>
        <th>Loan Due</th>
        <th>Loan Paid</th>
        <th>Advance</th>
        <th>Allowance</th>
        <th>Monthly Tea/Petrol</th>
        <th>Total Salary With Deduction</th>
      </tr>
    </thead>
    <tbody>
      <?php if (empty($filter_data)): ?>
        <tr>
          <td colspan="12">No data available.</td>
        </tr>
      <?php else: ?>
        <?php foreach ($filter_data as $emp_id => $records): ?>
          <?php
          $value = $records[0];
          $date = $value['date'];

          $month = date('m', strtotime($date));
          $year = date('Y', strtotime($date));
          $salary = (float) salary_emp($emp_id);
          $per_day_salary = $salary / 30;
          $total_attendance = count($records);
          ;

          $total_days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
          $sundays = 0;
          for ($i = 1; $i <= $total_days; $i++) {
            if (date('N', strtotime("$year-$month-$i")) == 7)
              $sundays++;
          }
          $working_days = $total_days - $sundays;
          $present_dates = array_column($records, 'date'); // Dates when employee was present
          $present_dates = array_map('strtotime', $present_dates);
          sort($present_dates);

            // Build a map of all days in the month
            $all_days = [];
            for ($i = 1; $i <= $total_days; $i++) {
                $current = strtotime("$year-$month-$i");
                $day = date('Y-m-d', $current);
                $all_days[] = $day;
            }

            // Initialize absents and sandwich logic
          $absent_dates = [];
            $sandwich_absents = [];

            for ($i = 0; $i < count($all_days); $i++) {
                $current = strtotime($all_days[$i]);
                $is_sunday = (date('N', $current) == 7);
                $is_present = in_array($current, $present_dates);
               if (!$is_present) {
                  if ($is_sunday) {
                      // Sandwich rule: count Sunday as absent ONLY if surrounded by absents
                      $prev = isset($all_days[$i - 1]) ? strtotime($all_days[$i - 1]) : null;
                      $next = isset($all_days[$i + 1]) ? strtotime($all_days[$i + 1]) : null;

                      $prev_absent = $prev && !in_array($prev, $present_dates);
                      $next_absent = $next && !in_array($next, $present_dates);

                      if ($prev_absent && $next_absent) {
                          $absent_dates[] = $current; // ✅ Count Sunday only if sandwich
                      }
                  } else {
                      $absent_dates[] = $current; // ✅ Count all other days normally
                  }
              }
            }

            $all_absents = array_unique(array_merge($absent_dates, $sandwich_absents));
            sort($all_absents);

            $absents = count($all_absents); // ✅ make sure this line exists
            
            $absent_relieve = ($absents > 0 ) ? max(0, $absents - 1) : $absents;
          
            $absent_dates_formatted = array_map(function($ts) {
                return date('d-m-Y', $ts);
            }, $all_absents);
            $absent_dates_string = implode(', ', $absent_dates_formatted);


          $total_lates = 0;
          $total_lates = (int) $total_lates;
          $no_tapout_count = 0;
          $absents = (int) $absents;
          foreach ($records as $value) {
            $new_tapin = strtotime(date('H:i', strtotime($value['tap_in']))); // Tap In time
            $emp_time = strtotime(date('H:i', strtotime(get_emp_time($value['emp_id'])))); // Expected time
            $is_late = false; // Initialize as false
      
            if ($new_tapin > $emp_time) {
              $is_late = true; // Mark as late if tap-in is after expected time
            }

            if ($is_late) {
              $total_lates++;
            }

            $record_date = strtotime($value['date']);
            $record_month = date('m', $record_date);
            $record_year = date('Y', $record_date);

          }

          $late_penalty_days = floor($total_lates / 5);
          $late_deduction = $late_penalty_days * $per_day_salary;

          $ot_rate = (float) get_over_time($emp_id);
          $ot_count = (float) count_overtime($emp_id, $month, $year);
         
          $hours = floor($ot_count);
         
          $minutes = round(($ot_count - $hours) * 60);
          $ot_amount = round($ot_count * $ot_rate);
          $advance_summary = advance_summary($emp_id, $month, $year);

          $advance = $advance_summary['advance'];
          $loan = (float) $advance_summary['loan'];
          $loan_paid = (float) $advance_summary['paid'];
          $loan_due = max(0, $loan - $loan_paid);
          $advance_paid = $advance_summary['advance_paid'];


          $allowance = ($absents == 0) ? check_allowance($emp_id) : 0;
          $per_day_tea_petrol = (float) tea_petrol($emp_id);
          $condition = $total_attendance - $absent_relieve;
          if ($condition < 0) {
            $tea_petrol_days = max(0, $absent_relieve - $total_attendance + $sundays);
          }else{
            $tea_petrol_days = max(0, $total_attendance - $absent_relieve + $sundays);
          }
         
          $tea_petrol = max(0, $per_day_tea_petrol * $tea_petrol_days);
        
          
          $gross_payable = (
          $salary 
          - ($absent_relieve * $per_day_salary) 
          - $late_deduction 
          + $ot_amount 
          + $allowance 
          + $tea_petrol
          - $loan_paid
          - $advance_paid // Deduct paid advance
        );


          ?>

          <tr>
            <td><?= fullname($emp_id); ?></td>
            <td><?= $total_attendance; ?></td>
            <td class="highlight-late"><?= $absents; ?></td>
            <td>
              <span title="<?= htmlspecialchars(implode(', ', $absent_dates_formatted)); ?>">
                <?= count($absent_dates_formatted); ?> days
              </span>
            </td>

            <td style="background-color:rgb(234, 199, 87);"><?= $total_lates; ?></td>
            <td> <?= number_format($salary, 2); ?></td>
            <td><?= "{$hours}h {$minutes}m"; ?></td>
            <td> <?= number_format($ot_amount, 2); ?></td>
            <?php
             $display_paid = ($loan_paid == $loan) ? 0 : $loan_paid;
            ?>
            <td> <?= number_format($loan_due, 2); ?></td>
            <td style="background-color:rgb(141, 219, 144);"><?= number_format($display_paid, 2); ?></td>
            <td><?= number_format($advance, 2); ?><?php if ($advance_paid > 0): ?>
                <br><span class="text-danger">(Deducted: <?= number_format($advance_paid, 2); ?>)</span>
            <?php endif; ?></td>

            <td> <?= number_format($allowance, 2); ?></td>
            <td> <?= number_format($tea_petrol, 2); ?></td>
            <td class="highlight-green"> <?= number_format($gross_payable, 2); ?></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>

</div>
<script>
document.querySelectorAll('.pay-advance-btn').forEach(button => {
  button.addEventListener('click', function () {
    const empId = this.getAttribute('data-emp');
    const month = this.getAttribute('data-month');
    const year = this.getAttribute('data-year');

    if (!confirm('Are you sure you want to mark this advance as paid?')) return;

    fetch('<?= base_url("AdvanceController/pay_advance") ?>', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest'
      },
      body: JSON.stringify({ emp_id: empId, month: month, year: year })
    })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        alert('Advance marked as paid!');
        location.reload(); // reload table to reflect changes
      } else {
        alert('Error: ' + data.message);
      }
    });
  });
});
</script>


<script type="text/javascript">
  function btnExport_monthly() {
    var tab_text = "<table border='2px'><tr bgcolor='#ebebeb'>";
    var textRange;
    var j = 0;
    tab = document.getElementById('example5'); // id of table

    for (j = 0; j < tab.rows.length; j++) {
      tab_text = tab_text + tab.rows[j].innerHTML + "</tr>";
    }

    tab_text = tab_text + "</table>";
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove links
    tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove images
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // remove input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
      txtArea2.document.open("txt/html", "replace");
      txtArea2.document.write(tab_text);
      txtArea2.document.close();
      txtArea2.focus();
      txtArea2.document.execCommand("SaveAs", true, "Generation_School_Report");
    } else {
      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
    }
  }

  function printData1() {
    var divToPrint = document.getElementById("container");
    var newWin = window.open("");
    newWin.document.write(divToPrint.outerHTML);
    newWin.print();
    newWin.close();
  }

</script>