<?php
declare(strict_types=1);

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

require_once __DIR__ . '/inc/auth.php';
require_login();

header('Content-Type: application/json; charset=UTF-8');

try {
  $pdo = dbx();

  $employeeId = (int)($_GET['id'] ?? 0);
  if ($employeeId <= 0) {
    echo json_encode(['ok'=>0,'msg'=>'bad id']); exit;
  }

  // عمود الكود (QR)
  $cols = $pdo->query("SHOW COLUMNS FROM employees")->fetchAll(PDO::FETCH_COLUMN, 0);
  $codeCol = '';
  if (in_array('qr_token2', $cols, true)) $codeCol = 'qr_token2';
  elseif (in_array('qr_token', $cols, true)) $codeCol = 'qr_token';

  if ($codeCol === '') {
    echo json_encode(['ok'=>0,'msg'=>'no code column']); exit;
  }

  // تحقق من الفرع
  $branchId = current_branch_id();
  $hasBranch = in_array('branch_id', $cols, true);

  // جلب employee.user_id أو employee_id للربط بالمستخدم الحالي (لو موجود)
  $linkCol = '';
  if (in_array('user_id', $cols, true)) $linkCol = 'user_id';
  elseif (in_array('employee_id', $cols, true)) $linkCol = 'employee_id';

  $sql = "SELECT id, {$codeCol} AS code" . ($linkCol ? ", {$linkCol} AS link_uid" : "") . " FROM employees WHERE id = ?";
  $params = [$employeeId];

  if ($hasBranch) { $sql .= " AND branch_id = ?"; $params[] = $branchId; }

  $st = $pdo->prepare($sql);
  $st->execute($params);
  $row = $st->fetch(PDO::FETCH_ASSOC);

  if (!$row) {
    echo json_encode(['ok'=>0,'msg'=>'not found']); exit;
  }

  // صلاحية: الأدمن يرى الجميع، الموظف يرى نفسه فقط إذا يوجد ربط
  if (!is_admin()) {
    $currentUserId = (int)($_SESSION['user_id'] ?? 0);

    if ($linkCol === '') {
      echo json_encode(['ok'=>0,'msg'=>'no link to user (user_id/employee_id missing)']); exit;
    }

    $linked = (int)($row['link_uid'] ?? 0);
    if ($currentUserId <= 0 || $linked !== $currentUserId) {
      echo json_encode(['ok'=>0,'msg'=>'forbidden']); exit;
    }
  }

  $code = trim((string)($row['code'] ?? ''));
  echo json_encode(['ok'=>1,'code'=>$code !== '' ? $code : '-']);
  exit;

} catch (Throwable $e) {
  echo json_encode(['ok'=>0,'msg'=>'server error']);
  exit;
}