<?php
declare(strict_types=1);

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

/* توحيد db.php */
require_once __DIR__ . '/../db.php';

if (!function_exists('db')) {
  http_response_code(500);
  die('Function db() not found in db.php');
}

function dbx(): PDO {
  $pdo = db();
  if (!$pdo instanceof PDO) {
    http_response_code(500);
    die('db() did not return PDO');
  }
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  return $pdo;
}

function require_login(): void {
  if (empty($_SESSION['user_id'])) {
    header("Location: index.html?e=1");
    exit;
  }
}

if (!function_exists('h')) {
  function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
  }
}
function current_user_id(): int { return (int)($_SESSION['user_id'] ?? 0); }
function current_role(): string { return strtoupper((string)($_SESSION['role'] ?? 'STAFF')); }
function current_branch_id(): int { return (int)($_SESSION['branch_id'] ?? 1); }

/* ADMIN/OWNER = صلاحيات كاملة */
function is_admin(): bool {
  return in_array(current_role(), ['OWNER','ADMIN'], true);
}

/* ===== صلاحيات مخصصة =====
   ملاحظة: لازم تكون محفوظة في session عند تسجيل الدخول:
   $_SESSION['can_hr']=1 ... الخ
*/
function can_cases(): bool {
  return is_admin() || ((int)($_SESSION['can_cases'] ?? 0) === 1);
}
function can_tasks(): bool {
  return is_admin() || ((int)($_SESSION['can_tasks'] ?? 0) === 1);
}
function can_hr(): bool {
  return is_admin() || ((int)($_SESSION['can_hr'] ?? 0) === 1);
}
function can_finance(): bool {
  return is_admin() || ((int)($_SESSION['can_finance'] ?? 0) === 1);
}
function can_reports(): bool {
  return is_admin() || ((int)($_SESSION['can_reports'] ?? 0) === 1);
}
function can_permissions(): bool {
  return is_admin() || ((int)($_SESSION['can_permissions'] ?? 0) === 1);
}

/* اختياري: اسم الفرع */
function branch_name_ar(int $branchId): string {
  return ($branchId === 2) ? 'دبي' : 'أبوظبي';
}

/* CSRF */
function csrf_token(): string {
  if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
  }
  return (string)$_SESSION['csrf'];
}

function csrf_check(): void {
  $t = (string)($_POST['csrf'] ?? '');
  if ($t === '' || empty($_SESSION['csrf']) || !hash_equals((string)$_SESSION['csrf'], $t)) {
    http_response_code(419);
    die('CSRF');
  }
}
function require_perm(string $perm): void {
  require_login();
  $perm = strtolower(trim($perm));

  $map = [
    'cases' => 'can_cases',
    'tasks' => 'can_tasks',
    'hr' => 'can_hr',
    'finance' => 'can_finance',
    'reports' => 'can_reports',
    'permissions' => 'can_permissions',
  ];

  if (!isset($map[$perm])) {
    http_response_code(500);
    exit('Unknown permission');
  }

  $key = $map[$perm];
  $ok = is_admin() || ((int)($_SESSION[$key] ?? 0) === 1);

  if (!$ok) {
    http_response_code(403);
    exit('غير مصرح');
  }
}
/* =========================
   تسجيل إنجاز الموظف تلقائياً
========================= */

if (!function_exists('log_employee_achievement')) {
  function log_employee_achievement(PDO $pdo, string $title, string $description = ''): void {

    try {

      $employeeId = (int)($_SESSION['employee_id'] ?? 0);
      if ($employeeId <= 0) {
        return;
      }

      /* تأكد أن الجدول موجود */
      $check = $pdo->query("
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
        AND table_name = 'employee_achievements'
      ");

      if ((int)$check->fetchColumn() === 0) {
        return;
      }

      $stmt = $pdo->prepare("
        INSERT INTO employee_achievements
        (employee_id, title, description, achievement_date)
        VALUES
        (?, ?, ?, NOW())
      ");

      $stmt->execute([
        $employeeId,
        $title,
        $description
      ]);

    } catch (Throwable $e) {
      error_log('EMPLOYEE ACHIEVEMENT ERROR: ' . $e->getMessage());
    }

  }
}