<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_login();

$pdo = db();
$cid = (int)$_SESSION['company_id'];

$date = $_GET['date'] ?? date('Y-m-d');
$err = null;
$openModal = false;

$emps = $pdo->prepare("SELECT id, full_name FROM employees WHERE company_id=? AND status='ACTIVE' ORDER BY full_name");
$emps->execute([$cid]);
$emps = $emps->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $employee_id = (int)($_POST['employee_id'] ?? 0);
  $work_date = $_POST['work_date'] ?? date('Y-m-d');
  $check_in = $_POST['check_in'] ?? null;
  $check_out = $_POST['check_out'] ?? null;
  $notes = trim($_POST['notes'] ?? '');

  if (!$employee_id) $err = 'اختر الموظف';

  if (!$err) {
    $st = $pdo->prepare("INSERT INTO attendance (company_id, employee_id, work_date, check_in, check_out, notes)
                         VALUES (?,?,?,?,?,?)
                         ON DUPLICATE KEY UPDATE check_in=VALUES(check_in), check_out=VALUES(check_out), notes=VALUES(notes)");
    $st->execute([$cid, $employee_id, $work_date, $check_in ?: null, $check_out ?: null, $notes ?: null]);
    flash_set('تم حفظ الحضور والانصراف بنجاح');
    header('Location: attendance.php?date='.urlencode($work_date));
    exit;
  }
  $openModal = true;
}

$att = $pdo->prepare("SELECT a.*, e.full_name FROM attendance a JOIN employees e ON e.id=a.employee_id
                      WHERE a.company_id=? AND a.work_date=? ORDER BY e.full_name");
$att->execute([$cid,$date]);
$att = $att->fetchAll(PDO::FETCH_ASSOC);

render_layout('الحضور والانصراف','الموارد البشرية <span class="mx-1">/</span> الحضور والانصراف', function() use ($emps,$att,$date,$err,$openModal) {
?>
<div class="container-fluid mt-3">
  <div class="d-flex align-items-start align-items-md-center justify-content-between flex-column flex-md-row gap-2 mb-3">
    <div>
      <div class="fw-bold fs-4">الحضور والانصراف</div>
      <div class="text-secondary small">تسجيل حضور وانصراف الموظفين من خلال نافذة سريعة داخل الصفحة.</div>
    </div>
    <button class="btn btn-dark" data-bs-toggle="modal" data-bs-target="#attendanceCreateModal"><i class="bi bi-plus-lg"></i> تسجيل اليوم</button>
  </div>

  <?php if($err): ?>
    <div class="alert alert-danger"><?= h($err) ?></div>
  <?php endif; ?>

  <div class="card cardx">
    <div class="p-3 d-flex align-items-center justify-content-between flex-wrap gap-2">
      <div>
        <div class="fw-bold">سجل اليوم</div>
        <div class="text-secondary small"><?= h($date) ?></div>
      </div>
      <form method="get" class="d-flex gap-2">
        <div style="min-width:200px">
          <?= render_date_input('date', $date) ?>
        </div>
        <button class="btn btn-outline-secondary btn-sm">عرض</button>
      </form>
    </div>
    <div class="table-responsive px-3 pb-3">
      <table class="table align-middle mb-0">
        <thead>
          <tr class="text-secondary small">
            <th>الموظف</th><th>دخول</th><th>خروج</th><th>ملاحظات</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($att as $r): ?>
            <tr>
              <td class="fw-semibold"><?= h($r['full_name']) ?></td>
              <td><?= h($r['check_in'] ?? '-') ?></td>
              <td><?= h($r['check_out'] ?? '-') ?></td>
              <td class="text-secondary"><?= h($r['notes'] ?? '') ?></td>
            </tr>
          <?php endforeach; ?>
          <?php if(!count($att)): ?>
            <tr><td colspan="4" class="text-center text-secondary py-4">لا يوجد حضور/انصراف لهذا اليوم</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="attendanceCreateModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post">
        <?= csrf_field() ?>
        <div class="modal-header">
          <h5 class="modal-title">تسجيل حضور/انصراف</h5>
          <button type="button" class="btn-close m-0" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3 modal-inline-grid">
            <div class="col-md-4">
              <label class="form-label">التاريخ</label>
              <?= render_date_input('work_date', $_POST['work_date'] ?? $date) ?>
            </div>
            <div class="col-md-8">
              <label class="form-label">الموظف</label>
              <div class="picker-with-action"><select class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" data-width="100%" required id="employee_id" name="employee_id" title="اختر الموظف">
                <?php foreach($emps as $e): ?>
                  <option value="<?= (int)$e['id'] ?>" <?= ((int)($e['id']) === (int)($_POST['employee_id'] ?? 0)) ? 'selected' : '' ?>><?= h($e['full_name']) ?></option>
                <?php endforeach; ?>
              </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="employee" data-target="#employee_id" title="إضافة موظف"><i class="bi bi-plus-lg"></i></button></div>
            </div>
            <div class="col-md-6">
              <label class="form-label">دخول</label>
              <input class="form-control" type="time" name="check_in" value="<?= h($_POST['check_in'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">خروج</label>
              <input class="form-control" type="time" name="check_out" value="<?= h($_POST['check_out'] ?? '') ?>">
            </div>
            <div class="col-12">
              <label class="form-label">ملاحظات</label>
              <input class="form-control" name="notes" value="<?= h($_POST['notes'] ?? '') ?>">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-save"></i> حفظ</button>
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php if($openModal): ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
  const el = document.getElementById('attendanceCreateModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>
<?php }); ?>
