<?php
require_once __DIR__ . '/../includes/functions.php';
require_role('admin');

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = $_POST['action'] ?? '';

    if ($action === 'toggle') {
        $uid = (int)$_POST['user_id'];
        $stmt = $pdo->prepare("UPDATE users SET is_active = 1 - is_active WHERE id = ?");
        $stmt->execute([$uid]);
        $success = 'وضعیت کاربر بروزرسانی شد.';
    } elseif ($action === 'reset_password') {
        $uid = (int)$_POST['user_id'];
        $new_pass = $_POST['new_password'] ?? '';
        if (strlen($new_pass) < 6) {
            $error = 'رمز عبور جدید باید حداقل ۶ کاراکتر باشد.';
        } else {
            $hash = password_hash($new_pass, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->execute([$hash, $uid]);
            $success = 'رمز عبور بازنشانی شد.';
        }
    } elseif ($action === 'edit') {
        $uid = (int)$_POST['user_id'];
        $personnel_code = trim($_POST['personnel_code'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $hire_date_j = trim($_POST['hire_date'] ?? '');
        $pre_test_required = isset($_POST['pre_employment_test_required']) ? 1 : 0;
        $pre_test_date_j = trim($_POST['pre_employment_test_date'] ?? '');

        $hire_date = null;
        if ($hire_date_j !== '') {
            $g = parse_jalali_date($hire_date_j);
            if ($g) {
                $hire_date = sprintf('%04d-%02d-%02d', $g[0], $g[1], $g[2]);
            }
        }
        $pre_test_date = null;
        if ($pre_test_required && $pre_test_date_j !== '') {
            $g2 = parse_jalali_date($pre_test_date_j);
            if ($g2) {
                $pre_test_date = sprintf('%04d-%02d-%02d', $g2[0], $g2[1], $g2[2]);
            }
        }
        $stmt = $pdo->prepare("UPDATE users SET personnel_code = ?, email = ?, hire_date = ?, pre_employment_test_required = ?, pre_employment_test_date = ? WHERE id = ?");
        $stmt->execute([$personnel_code ?: null, $email ?: null, $hire_date, $pre_test_required, $pre_test_date, $uid]);
        $success = 'اطلاعات کاربر بروزرسانی شد.';
    }
}

$users = $pdo->query("SELECT * FROM users ORDER BY role, full_name")->fetchAll();

$page_title = 'مدیریت کارمندان';
include __DIR__ . '/../includes/header.php';
?>

<h4 class="mb-4">مدیریت کاربران</h4>

<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>

<div class="mb-4">
  <a href="add_user.php" class="btn btn-primary">+ افزودن کاربر جدید</a>
</div>

<div class="table-responsive">
<table class="table table-bordered align-middle">
  <thead class="table-light">
    <tr><th>نام</th><th>نام کاربری</th><th>کد پرسنلی</th><th>ایمیل</th><th>تاریخ استخدام</th><th>نقش</th><th>وضعیت</th><th>عملیات</th></tr>
  </thead>
  <tbody>
    <?php foreach ($users as $u): ?>
      <tr>
        <td><?= htmlspecialchars($u['full_name']) ?></td>
        <td><?= htmlspecialchars($u['username']) ?></td>
        <td><?= htmlspecialchars($u['personnel_code'] ?? '-') ?></td>
        <td class="small"><?= htmlspecialchars($u['email'] ?? '-') ?></td>
        <td class="small"><?= $u['hire_date'] ? to_jalali_string($u['hire_date']) : '-' ?></td>
        <td><?= $u['role'] === 'admin' ? 'مدیر/مالی' : 'کارمند' ?></td>
        <td>
          <span class="badge <?= $u['is_active'] ? 'bg-success' : 'bg-secondary' ?>"><?= $u['is_active'] ? 'فعال' : 'غیرفعال' ?></span>
        </td>
        <td class="d-flex gap-1 flex-wrap">
          <form method="post" class="d-inline">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="toggle">
            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
            <button class="btn btn-sm btn-outline-secondary" onclick="return confirm('تغییر وضعیت این کاربر؟')"><?= $u['is_active'] ? 'غیرفعال‌سازی' : 'فعال‌سازی' ?></button>
          </form>
          <button class="btn btn-sm btn-outline-info" data-bs-toggle="modal" data-bs-target="#editModal<?= $u['id'] ?>">ویرایش</button>
          <button class="btn btn-sm btn-outline-warning" data-bs-toggle="modal" data-bs-target="#resetModal<?= $u['id'] ?>">تغییر رمز</button>
          <?php if ($u['role'] === 'employee'): ?>
            <a href="view_profile.php?id=<?= $u['id'] ?>" class="btn btn-sm btn-outline-secondary">پروفایل/مدارک</a>
          <?php endif; ?>
        </td>
      </tr>

      <div class="modal fade" id="editModal<?= $u['id'] ?>" tabindex="-1">
        <div class="modal-dialog">
          <div class="modal-content">
            <form method="post">
              <?= csrf_field() ?>
              <input type="hidden" name="action" value="edit">
              <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
              <div class="modal-header"><h6 class="modal-title">ویرایش اطلاعات: <?= htmlspecialchars($u['full_name']) ?></h6></div>
              <div class="modal-body">
                <div class="mb-2">
                  <label class="form-label small">کد پرسنلی</label>
                  <input type="text" name="personnel_code" class="form-control" value="<?= htmlspecialchars($u['personnel_code'] ?? '') ?>">
                </div>
                <div class="mb-2">
                  <label class="form-label small">ایمیل</label>
                  <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($u['email'] ?? '') ?>">
                </div>
                <div class="mb-2">
                  <label class="form-label small">تاریخ استخدام (شمسی)</label>
                  <input type="text" name="hire_date" class="form-control jalali-date-input" autocomplete="off" data-allow-future="1" value="<?= $u['hire_date'] ? to_jalali_string_latin($u['hire_date']) : '' ?>">
                </div>
                <div class="form-check mb-2">
                  <input type="checkbox" name="pre_employment_test_required" value="1" class="form-check-input pre-test-toggle" id="preTestEdit<?= $u['id'] ?>" <?= $u['pre_employment_test_required'] ? 'checked' : '' ?>>
                  <label class="form-check-label small" for="preTestEdit<?= $u['id'] ?>">مشمول آزمایش بدو استخدام</label>
                </div>
                <div class="mb-2 pre-test-date-wrap" style="<?= $u['pre_employment_test_required'] ? '' : 'display:none;' ?>">
                  <label class="form-label small">تاریخ آزمایش بدو استخدام</label>
                  <input type="text" name="pre_employment_test_date" class="form-control jalali-date-input" autocomplete="off" data-allow-future="1" value="<?= $u['pre_employment_test_date'] ? to_jalali_string_latin($u['pre_employment_test_date']) : '' ?>">
                </div>
              </div>
              <div class="modal-footer">
                <button type="submit" class="btn btn-primary">ذخیره</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <div class="modal fade" id="resetModal<?= $u['id'] ?>" tabindex="-1">
        <div class="modal-dialog">
          <div class="modal-content">
            <form method="post">
              <?= csrf_field() ?>
              <input type="hidden" name="action" value="reset_password">
              <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
              <div class="modal-header"><h6 class="modal-title">تغییر رمز عبور: <?= htmlspecialchars($u['full_name']) ?></h6></div>
              <div class="modal-body">
                <input type="password" name="new_password" class="form-control" placeholder="رمز عبور جدید (حداقل ۶ کاراکتر)" required minlength="6">
              </div>
              <div class="modal-footer">
                <button type="submit" class="btn btn-primary">ذخیره</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    <?php endforeach; ?>
  </tbody>
</table>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.pre-test-toggle').forEach(function (cb) {
        var wrap = cb.closest('.row, .modal-body').querySelector('.pre-test-date-wrap');
        if (!wrap) return;
        cb.addEventListener('change', function () {
            wrap.style.display = cb.checked ? '' : 'none';
        });
    });
});
</script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
