<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$debug = true;

ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/500_hr_employee_form.log');

if ($debug) {
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', '0');
    ini_set('display_startup_errors', '0');
    error_reporting(E_ALL);
}

require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/layout.php';

require_login();

$pdo = dbx();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if (!function_exists('h')) {
    function h($s): string {
        return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
    }
}

$branchId = (int)current_branch_id();
$userId   = (int)current_user_id();

$role = strtoupper(trim((string)current_role()));

$isOwner = in_array($role, ['OWNER', 'SUPER_ADMIN'], true);
$isAdmin = in_array($role, ['ADMIN', 'OWNER', 'SUPER_ADMIN'], true);

if (!$isAdmin) {
    http_response_code(403);
    die('غير مصرح');
}

/* CSRF */
function csrf_input(): string {
    if (function_exists('csrf_token')) {
        return '<input type="hidden" name="csrf" value="' . h((string)csrf_token()) . '">';
    }

    if (empty($_SESSION['csrf'])) {
        $_SESSION['csrf'] = bin2hex(random_bytes(32));
    }

    return '<input type="hidden" name="csrf" value="' . h((string)$_SESSION['csrf']) . '">';
}

function csrf_verify(): void {
    if (function_exists('csrf_check')) {
        csrf_check();
        return;
    }

    $t = (string)($_POST['csrf'] ?? '');

    if ($t === '' || empty($_SESSION['csrf']) || !hash_equals((string)$_SESSION['csrf'], $t)) {
        http_response_code(419);
        die('CSRF');
    }
}

/* QR */
function create_employee_qr4_and_save(PDO $pdo, int $employeeId): void {
    $qr4 = str_pad((string)$employeeId, 4, '0', STR_PAD_LEFT);

    $st = $pdo->prepare("UPDATE employees SET qr_token2 = ? WHERE id = ? LIMIT 1");
    $st->execute([$qr4, $employeeId]);

    $qrLib = __DIR__ . '/inc/phpqrcode/qrlib.php';
    if (!file_exists($qrLib)) {
        return;
    }

    require_once $qrLib;

    $qrDirAbs = __DIR__ . '/uploads/qr/';
    if (!is_dir($qrDirAbs)) {
        @mkdir($qrDirAbs, 0777, true);
    }

    $fileAbs = $qrDirAbs . 'emp_' . $employeeId . '.png';

    if (class_exists('QRcode')) {
        QRcode::png($qr4, $fileAbs, QR_ECLEVEL_H, 6);
    }
}

$id = (int)($_GET['id'] ?? 0);

$msg = '';
$err = '';

$row = [
    'full_name' => '',
    'email'     => '',
    'phone'     => '',
    'job_title' => '',
    'status'    => 'ACTIVE',
    'hired_at'  => '',
    'branch_id' => $branchId,
];

/* عند التعديل: OWNER يفتح أي موظف، ADMIN يفتح موظفي فرعه فقط */
if ($id > 0) {
    if ($isOwner) {
        $st = $pdo->prepare("SELECT * FROM employees WHERE id = ? LIMIT 1");
        $st->execute([$id]);
    } else {
        $st = $pdo->prepare("SELECT * FROM employees WHERE id = ? AND branch_id = ? LIMIT 1");
        $st->execute([$id, $branchId]);
    }

    $found = $st->fetch();

    if (!$found) {
        http_response_code(404);
        die('Not found');
    }

    $row = array_merge($row, $found);
}

/* فرع الموظف الفعلي عند التعديل */
$empBranchId = (int)($row['branch_id'] ?? $branchId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $full_name = trim((string)($_POST['full_name'] ?? ''));
    $email     = trim((string)($_POST['email'] ?? ''));
    $phone     = trim((string)($_POST['phone'] ?? ''));
    $job_title = trim((string)($_POST['job_title'] ?? ''));
    $status    = strtoupper(trim((string)($_POST['status'] ?? 'ACTIVE')));
    $hired_at  = trim((string)($_POST['hired_at'] ?? ''));

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

    if (!in_array($status, ['ACTIVE', 'INACTIVE'], true)) {
        $status = 'ACTIVE';
    }

    $hired_at_db = ($hired_at !== '') ? $hired_at : null;

    if ($err === '') {
        if ($id > 0) {
            if ($isOwner) {
                $st = $pdo->prepare("
                    UPDATE employees
                    SET full_name = ?,
                        email = ?,
                        phone = ?,
                        job_title = ?,
                        status = ?,
                        hired_at = ?
                    WHERE id = ?
                    LIMIT 1
                ");

                $st->execute([
                    $full_name,
                    $email !== '' ? $email : null,
                    $phone !== '' ? $phone : null,
                    $job_title !== '' ? $job_title : null,
                    $status,
                    $hired_at_db,
                    $id
                ]);
            } else {
                $st = $pdo->prepare("
                    UPDATE employees
                    SET full_name = ?,
                        email = ?,
                        phone = ?,
                        job_title = ?,
                        status = ?,
                        hired_at = ?
                    WHERE id = ?
                      AND branch_id = ?
                    LIMIT 1
                ");

                $st->execute([
                    $full_name,
                    $email !== '' ? $email : null,
                    $phone !== '' ? $phone : null,
                    $job_title !== '' ? $job_title : null,
                    $status,
                    $hired_at_db,
                    $id,
                    $branchId
                ]);
            }
        } else {
            $insertBranchId = $isOwner
                ? (int)($_POST['branch_id'] ?? $branchId)
                : $branchId;

            if ($insertBranchId <= 0) {
                $insertBranchId = $branchId;
            }

            $st = $pdo->prepare("
                INSERT INTO employees
                    (branch_id, full_name, email, phone, job_title, status, hired_at)
                VALUES
                    (?, ?, ?, ?, ?, ?, ?)
            ");

            $st->execute([
                $insertBranchId,
                $full_name,
                $email !== '' ? $email : null,
                $phone !== '' ? $phone : null,
                $job_title !== '' ? $job_title : null,
                $status,
                $hired_at_db
            ]);

            $id = (int)$pdo->lastInsertId();

            try {
                create_employee_qr4_and_save($pdo, $id);
            } catch (Throwable $e) {
                error_log('QR_CREATE_FAIL: ' . $e->getMessage());
            }
        }

        header('Location: hr_employees.php?ok=1');
        exit;
    }
}

render_layout_start($id > 0 ? 'تعديل موظف' : 'إضافة موظف');
?>
<style>
.btn.is-locked{
  opacity:.45;
  filter:grayscale(1);
  cursor:not-allowed;
  pointer-events:none;
}

.status-wrap{
  position:relative;
}

.status-select{
  width:100%;
  height:52px;
  border-radius:16px;
  border:1px solid rgba(255,255,255,.10);
  background:
    linear-gradient(180deg, rgba(255,255,255,.04), rgba(255,255,255,.02)),
    linear-gradient(90deg, rgba(2,24,34,.98), rgba(6,36,49,.98));
  color:#f3fbff;
  padding:0 16px 0 48px;
  font-size:16px;
  font-weight:700;
  outline:none;
  appearance:none;
  -webkit-appearance:none;
  -moz-appearance:none;
  box-shadow:
    inset 0 1px 0 rgba(255,255,255,.04),
    0 10px 24px rgba(0,0,0,.18);
  transition:border-color .18s ease, box-shadow .18s ease, transform .18s ease;
  cursor:pointer;
}

.status-select:hover{
  border-color:rgba(69, 197, 224, .45);
  box-shadow:
    inset 0 1px 0 rgba(255,255,255,.05),
    0 12px 28px rgba(0,0,0,.22);
}

.status-select:focus{
  border-color:#1bb6d3;
  box-shadow:
    0 0 0 4px rgba(27,182,211,.14),
    0 14px 32px rgba(0,0,0,.24);
}

.status-wrap::after{
  content:"⌄";
  position:absolute;
  left:16px;
  top:50%;
  transform:translateY(-52%);
  color:#8fd8e6;
  font-size:20px;
  font-weight:900;
  pointer-events:none;
  line-height:1;
}

.status-select:disabled{
  opacity:.72;
  cursor:not-allowed;
}

.status-select option{
  background:#0a1f2a;
  color:#ffffff;
}

.label-strong{
  display:inline-block;
  margin-bottom:8px;
  color:#cfeaf0;
  font-weight:800;
  font-size:14px;
}
.date-field-wrap{
  display:flex;
  align-items:center;
}

.date-ui{
  width:100%;
  direction:ltr;
  text-align:center;
  letter-spacing:.5px;
  font-weight:700;
}
.form-actions{
  display:flex;
  gap:10px;
  justify-content:flex-start;
  align-items:center;
  margin-top:18px; /* ينزل الأزرار قليلاً */
}
</style>

<div class="grid">
  <?php if ($msg): ?><div class="msg ok"><?=h($msg)?></div><?php endif; ?>
  <?php if ($err): ?><div class="msg err"><?=h($err)?></div><?php endif; ?>

  <div class="card">
    <div class="cardHead">
      <div style="font-weight:900"><?= ($id>0 ? 'تعديل موظف' : 'إضافة موظف') ?></div>

      <div class="row">
        <?php if ($id>0): ?>
          <?php if ($isOwner): ?>

            <a class="btn ghost" href="hr_employee_docs.php?id=<?= (int)$id ?>">مستندات الموظف</a>
          <?php else: ?>
            <a class="btn ghost is-locked" href="#" title="صلاحية الأدمن فقط">مستندات الموظف</a>
          <?php endif; ?>
        <?php endif; ?>

        <a class="btn ghost" href="hr_employees.php">رجوع</a>
      </div>
    </div>

    <form method="post" class="grid" style="gap:10px">
      <?= csrf_input() ?>

      <div class="row">
        <div style="flex:1;min-width:220px">
          <label class="muted">اسم الموظف</label>
          <input class="input" name="full_name" value="<?=h($row['full_name'])?>" required <?= $isAdmin ? '' : 'readonly' ?>>
        </div>

        <div style="width:220px;min-width:190px">
          <label class="label-strong">الحالة</label>
          <div class="status-wrap">
            <select class="input input-select status-select" name="status" <?= $isAdmin ? '' : 'disabled' ?>>
              <option value="ACTIVE" <?=($row['status']==='ACTIVE'?'selected':'')?>>نشط</option>
              <option value="INACTIVE" <?=($row['status']==='INACTIVE'?'selected':'')?>>غير نشط</option>
            </select>
          </div>
          <?php if (!$isAdmin): ?>
            <input type="hidden" name="status" value="<?=h($row['status'])?>">
          <?php endif; ?>
        </div>
      </div>

      <div class="row">
        <div style="flex:1;min-width:220px">
          <label class="muted">البريد</label>
          <input class="input" name="email" value="<?=h($row['email'] ?? '')?>" type="email" <?= $isAdmin ? '' : 'readonly' ?>>
        </div>

        <div style="width:260px;min-width:220px">
          <label class="muted">الهاتف</label>
          <input class="input" name="phone" value="<?=h($row['phone'] ?? '')?>" <?= $isAdmin ? '' : 'readonly' ?>>
        </div>
      </div>

      <div class="row">
        <div style="flex:1;min-width:220px">
          <label class="muted">المسمى الوظيفي</label>
          <input class="input" name="job_title" value="<?=h($row['job_title'] ?? '')?>" <?= $isAdmin ? '' : 'readonly' ?>>
        </div>

       <div style="width:260px;min-width:220px">
  <label class="muted">تاريخ التعيين</label>

  <div class="date-field-wrap">
    <input
      class="input date-ui"
      id="hired_at_ui"
      inputmode="numeric"
      maxlength="10"
      placeholder="dd/mm/yyyy"
      autocomplete="off"
      value="<?= !empty($row['hired_at']) ? h(date('d/m/Y', strtotime((string)$row['hired_at']))) : '' ?>"
      <?= $isAdmin ? '' : 'readonly' ?>
    >

    <input
      type="hidden"
      name="hired_at"
      id="hired_at"
      value="<?= h((string)($row['hired_at'] ?? '')) ?>"
    >
  </div>
      </form>
  </div>
</div>

<div class="form-actions">
  <?php if ($isAdmin): ?>
    <button class="btn" type="submit">حفظ</button>
  <?php else: ?>
    <button class="btn is-locked" type="button" title="صلاحية الأدمن فقط">حفظ</button>
  <?php endif; ?>

  <a class="btn ghost" href="hr_employees.php">إلغاء</a>
</div>
</div>

<?php render_layout_end(); ?>