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

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

$err = null;
$openModal = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $full_name = trim($_POST['full_name'] ?? '');
  $phone = trim($_POST['phone'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $job_title = trim($_POST['job_title'] ?? '');
  $hire_date = trim($_POST['hire_date'] ?? '');
  $salary = (float)($_POST['salary_monthly'] ?? 0);

  if ($full_name === '') $err = 'اسم الموظف مطلوب';

  if (!$err) {
    $st = $pdo->prepare("INSERT INTO employees (company_id, full_name, phone, email, job_title, hire_date, salary_monthly) VALUES (?,?,?,?,?,?,?)");
    $st->execute([$cid, $full_name, $phone ?: null, $email ?: null, $job_title ?: null, $hire_date ?: null, $salary]);
    flash_set('تم إضافة الموظف بنجاح');
    header('Location: employees.php');
    exit;
  }
  $openModal = true;
}

$rows = $pdo->prepare("SELECT * FROM employees WHERE company_id=? ORDER BY id DESC");
$rows->execute([$cid]);
$rows = $rows->fetchAll(PDO::FETCH_ASSOC);

render_layout('الموظفين','الموارد البشرية <span class="mx-1">/</span> الموظفين', function() use ($rows,$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="#employeeCreateModal"><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">
      <div class="fw-bold">قائمة الموظفين</div>
      <span class="text-secondary small"><?= count($rows) ?> موظف</span>
    </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><th>الحالة</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($rows as $r): ?>
            <tr>
              <td class="text-secondary"><?= (int)$r['id'] ?></td>
              <td class="fw-semibold"><?= h($r['full_name']) ?></td>
              <td><?= h($r['job_title'] ?? '-') ?></td>
              <td class="text-end"><?= number_format((float)$r['salary_monthly'],2) ?></td>
              <td><span class="badge bg-success-subtle text-success border border-success-subtle">نشط</span></td>
            </tr>
          <?php endforeach; ?>
          <?php if(!count($rows)): ?>
            <tr><td colspan="5" class="text-center text-secondary py-4">لا يوجد موظفين بعد</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="modal fade modal-erp" id="employeeCreateModal" 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-12">
              <label class="form-label">اسم الموظف</label>
              <input class="form-control" name="full_name" required value="<?= h($_POST['full_name'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">هاتف</label>
              <input class="form-control" name="phone" value="<?= h($_POST['phone'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">Email</label>
              <input class="form-control" name="email" type="email" value="<?= h($_POST['email'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">المسمى الوظيفي</label>
              <input class="form-control" name="job_title" value="<?= h($_POST['job_title'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">تاريخ التعيين</label>
              <?= render_date_input('hire_date', $_POST['hire_date'] ?? date('Y-m-d')) ?>
            </div>
            <div class="col-12">
              <label class="form-label">الراتب الشهري</label>
              <input class="form-control" name="salary_monthly" type="number" step="0.01" value="<?= h($_POST['salary_monthly'] ?? '0') ?>">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></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('employeeCreateModal');
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
</script>
<?php endif; ?>
<?php }); ?>
