<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-attendance">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Attendance</h4>
      <div class="d-flex gap-2">
        <select id="attBranch" class="form-select form-select-sm" style="min-width:200px"></select>
        <select id="attMonth" class="form-select form-select-sm" style="width:auto">
          <?php for($m=1;$m<=12;$m++): $label=date('M', mktime(0,0,0,$m,10)); ?>
          <option value="<?php echo $m; ?>" <?php echo ((int)date('n')===$m)?'selected':''; ?>><?php echo $label; ?></option>
          <?php endfor; ?>
        </select>
        <select id="attYear" class="form-select form-select-sm" style="width:auto">
          <?php $y=(int)date('Y'); for($i=$y-2;$i<=$y+1;$i++): ?>
          <option value="<?php echo $i; ?>" <?php echo ($i===$y)?'selected':''; ?>><?php echo $i; ?></option>
          <?php endfor; ?>
        </select>
        <button id="btnAttRefresh" class="btn btn-sm btn-outline-secondary">Refresh</button>
        <button id="btnAttExport" class="btn btn-sm btn-outline-primary">Export CSV</button>
      </div>
    </div>

    <div class="card shadow-sm">
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-sm table-bordered align-middle" id="att-table">
            <thead id="attHead"></thead>
            <tbody id="attBody"></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Edit Cell Modal -->
<div class="modal fade" id="attEditModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"><h6 class="modal-title">Edit Attendance</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
      <form id="attEditForm">
        <div class="modal-body">
          <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
          <input type="hidden" name="employee_id" id="att_emp_id">
          <input type="hidden" name="date" id="att_date">
          <div class="mb-2">
            <label class="form-label">Status</label>
            <select class="form-select" name="status" id="att_status">
              <option value="present">Present</option>
              <option value="half_day">Half Day</option>
              <option value="short_leave">Short Leave</option>
              <option value="absent">Absent</option>
              <option value="leave">Leave</option>
              <option value="holiday">Holiday</option>
              <option value="off">Off</option>
              <option value="work_from_home">Work From Home</option>
            </select>
          </div>
          <div class="row g-2">
            <div class="col-6">
              <label class="form-label">Check In</label>
              <input type="time" class="form-control" name="check_in" id="att_in">
            </div>
            <div class="col-6">
              <label class="form-label">Check Out</label>
              <input type="time" class="form-control" name="check_out" id="att_out">
            </div>
          </div>
          <div class="row g-2 mt-1">
            <div class="col-4">
              <label class="form-label">Hours</label>
              <input type="number" step="0.25" class="form-control" name="hours_worked" id="att_hours">
            </div>
            <div class="col-4">
              <label class="form-label">Late (min)</label>
              <input type="number" class="form-control" name="late_minutes" id="att_late">
            </div>
            <div class="col-4">
              <label class="form-label">OT (min)</label>
              <input type="number" class="form-control" name="ot_minutes" id="att_ot">
            </div>
          </div>
          <div class="mt-2">
            <label class="form-label">Notes</label>
            <input type="text" class="form-control" name="notes" id="att_notes">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(function(){
  const csrf = '<?php echo htmlspecialchars(csrf_token()); ?>';
  const $head = $('#attHead');
  const $body = $('#attBody');
  const monthSel = $('#attMonth');
  const yearSel = $('#attYear');
  let originalIn = null;
  let originalOut = null;

  function loadBranches() {
    $.get('api/branches.php', { action:'list' }, function(res){
      const sel = $('#attBranch').empty();
      sel.append('<option value="">All Branches</option>');
      (res.data||[]).forEach(b=> sel.append(`<option value="${b.id}">${$('<div>').text(b.name).html()}</option>`));
    });
  }

  function buildHead(start){
    const d = new Date(start);
    const year = d.getFullYear();
    const month = d.getMonth()+1;
    const daysInMonth = new Date(year, month, 0).getDate();
    const tr = $('<tr>');
    tr.append('<th style="min-width:200px">Employee</th>');
    for(let day=1; day<=daysInMonth; day++){
      const wd = new Date(year, month-1, day).getDay(); // 0=Sun,6=Sat
      const isWknd = (wd===0 || wd===6);
      tr.append(`<th class="text-center ${isWknd?'table-secondary':''}" style="width:36px">${day}</th>`);
    }
    $head.html(tr);
  }

  function statusBadge(st, notes = '') {
    const map = { 
      present: 'success', 
      half_day: 'info', 
      short_leave: 'primary', 
      absent: 'danger', 
      leave: 'warning', 
      holiday: 'info', 
      off: 'secondary', 
      work_from_home: 'primary' 
    };
    const label = { 
      present: 'P', 
      half_day: 'HD', 
      short_leave: 'SL', 
      absent: 'A', 
      leave: 'L', 
      holiday: 'H', 
      off: 'O', 
      work_from_home: 'WFH' 
    };
    
    // Check for half-day or short leave in notes if status is present
    if (st === 'present') {
      if (notes && (notes.includes('half') || notes.includes('halfday'))) {
        st = 'half_day';
      } else if (notes && notes.includes('short leave')) {
        st = 'short_leave';
      }
    }
    
    const cls = map[st] || 'secondary';
    return `<span class="badge bg-${cls}" title="${notes || ''}">${label[st] || '?'}</span>`;
  }

  function loadGrid(){
    const month = monthSel.val(); const year = yearSel.val(); const branch_id = $('#attBranch').val();
    $.get('api/attendance.php', { action:'list_days', month, year, branch_id }, function(res){
      buildHead(res.start);
      $body.empty();
      const start = new Date(res.start);
      const daysInMonth = new Date(start.getFullYear(), start.getMonth()+1, 0).getDate();
      (res.employees||[]).forEach(e=>{
        const tr = $('<tr>');
        tr.append(`<td><div class="small text-muted">${$('<div>').text(e.emp_code).html()}</div><div>${$('<div>').text(e.full_name).html()}</div></td>`);
        for(let day=1; day<=daysInMonth; day++){
          const d = `${res.start.substring(0,8)}${String(day).padStart(2,'0')}`;
          const a = (res.attendance && res.attendance[e.id] && res.attendance[e.id][d]) ? res.attendance[e.id][d] : null;
          const badge = a ? statusBadge(a.status) : '<span class="badge bg-light text-dark">-</span>';
          const wd = new Date(start.getFullYear(), start.getMonth(), day).getDay();
          const isWknd = (wd===0 || wd===6);
          const td = $(`<td class="text-center ${isWknd?'bg-light':''}" data-emp="${e.id}" data-date="${d}" data-status="${a?a.status:''}">${badge}</td>`);
          if (a && (a.check_in || a.check_out)) td.attr('title', `${a.check_in||''} - ${a.check_out||''}`);
          tr.append(td);
        }
        $body.append(tr);
      });
    });
  }

  $('#btnAttRefresh, #attMonth, #attYear, #attBranch').on('change click', loadGrid);

  // Cell click to edit
  $('#attBody').on('click','td', function(){
    const emp = $(this).data('emp');
    const date = $(this).data('date');
    if (!emp || !date) return;
    
    // Set the basic fields
    $('#att_emp_id').val(emp);
    $('#att_date').val(date);
    
    // Reset form
    $('#attEditForm')[0].reset();
    
    // Get existing attendance data
    const month = monthSel.val();
    const year = yearSel.val();
    
    $.get('api/attendance.php', { 
      action: 'list_days', 
      month, 
      year, 
      employee_id: emp 
    }, function(res) {
      // Find the attendance record for the selected date
      const attDate = date.substring(0, 10); // Ensure YYYY-MM-DD format
      const record = res.attendance && res.attendance[emp] && res.attendance[emp][attDate];
      
      if (record) {
        // Populate the form with existing data
        $('#att_status').val(record.status || 'present');
        $('#att_in').val(record.check_in || '');
        $('#att_out').val(record.check_out || '');
        $('#att_hours').val(record.hours_worked || '');
        $('#att_late').val(record.late_minutes || '');
        $('#att_ot').val(record.ot_minutes || '');
        $('#att_notes').val(record.notes || '');
        originalIn = record.check_in || null;
        originalOut = record.check_out || null;
      } else {
        // Set default values for new record
        $('#att_status').val('present');
        originalIn = null;
        originalOut = null;
        // Default times for new present record if empty
        if (!$('#att_in').val()) $('#att_in').val('08:00');
        if (!$('#att_out').val()) $('#att_out').val('17:00');
      }
      
      // Show the modal after data is loaded
      $('#attEditModal').modal('show');
    });
  });

  // Double-click to toggle Present/Absent quickly
  $('#attBody').on('dblclick','td', function(e){
    const emp = $(this).data('emp');
    const date = $(this).data('date');
    if (!emp || !date) return;
    const cur = ($(this).attr('data-status')||'').toLowerCase();
    const next = (cur==='present') ? 'absent' : 'present';
    const fd = new FormData();
    fd.append('csrf', csrf);
    fd.append('employee_id', String(emp));
    fd.append('date', String(date));
    fd.append('status', next);
    fd.append('action', 'upsert_day');
    $.ajax({ url:'api/attendance.php', method:'POST', data:fd, processData:false, contentType:false })
      .done(()=> loadGrid())
      .fail(xhr=> alert(xhr.responseJSON?.message||'Error'));
  });

  // Auto-calc Hours from Check In/Out (round to nearest 15 mins)
  function setHoursFromTimes(){
    const tin = $('#att_in').val();
    const tout = $('#att_out').val();
    if (!tin || !tout) return; // keep as is until both are set
    const parse = t => { const [h,m] = t.split(':').map(x=>parseInt(x,10)); return (isFinite(h)&&isFinite(m)) ? (h*60+m) : null; };
    const minIn = parse(tin), minOut = parse(tout);
    if (minIn==null || minOut==null || minOut<=minIn) { $('#att_hours').val(''); return; }
    let diff = minOut - minIn;
    diff = Math.round(diff/15)*15; // nearest 15
    const hours = (diff/60).toFixed(2);
    $('#att_hours').val(hours);
  }
  $('#att_in, #att_out').on('change input', setHoursFromTimes);

  $('#att_status').on('change', function(){
    if (this.value === 'present') {
      if (originalIn || originalOut) {
        $('#att_in').val(originalIn || '');
        $('#att_out').val(originalOut || '');
      } else {
        if (!$('#att_in').val()) $('#att_in').val('08:00');
        if (!$('#att_out').val()) $('#att_out').val('17:00');
      }
    } else {
      $('#att_in').val('');
      $('#att_out').val('');
    }
  });

  $('#attEditForm').on('submit', function(e){
    e.preventDefault();
    const data = new FormData(this);
    data.append('action','upsert_day');
    $.ajax({ url:'api/attendance.php', method:'POST', data, processData:false, contentType:false })
      .done(function(){ $('#attEditModal').modal('hide'); loadGrid(); })
      .fail(function(xhr){ alert(xhr.responseJSON?.message || 'Error'); });
  });

  // Export CSV (month summary)
  $('#btnAttExport').on('click', function(){
    const month = monthSel.val(); const year = yearSel.val(); const branch_id = $('#attBranch').val();
    $.get('api/attendance.php', { action:'month_summary', month, year, branch_id }, function(res){
      const rows = res.data || [];
      const header = ['Emp Code','Employee','Present','Half Day','Short Leave','Absent','Leave','Holiday','Hours','Late (min)','OT (min)'];
      const csv = [header.join(',')].concat(rows.map(r=>[
        (r.emp_code||'').replaceAll(',', ' '),
        (r.full_name||'').replaceAll(',', ' '),
        r.present_days||0,
        r.halfday_days||0,
        r.short_leave_days||0,
        r.absent_days||0,
        r.leave_days||0,
        r.holiday_days||0,
        Number(r.hours_total||0).toFixed(2),
        r.late_total||0,
        r.ot_total||0
      ].join(',')));
      const blob = new Blob([csv.join('\n')], { type:'text/csv;charset=utf-8;' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `attendance_summary_${year}-${String(month).padStart(2,'0')}.csv`;
      document.body.appendChild(a); a.click(); document.body.removeChild(a);
      URL.revokeObjectURL(url);
    });
  });

  // init
  loadBranches();
  loadGrid();
})();
</script>
