<?php
declare(strict_types=1);

require __DIR__ . '/../config/bootstrap.php';

$db = \App\Core\Database::getInstance();
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$lang = $_SESSION['lang'] ?? 'ar';
$rtl = ($lang === 'ar');
$err = null;

function find_author_role_id($db): int {
  try {
    $has = (int)$db->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='roles'")->fetchColumn() > 0;
    if ($has) {
      $rid = $db->query("SELECT id FROM roles WHERE code='author' LIMIT 1")->fetchColumn();
      if ($rid) return (int)$rid;
    }
  } catch (\Throwable $e) {}
  return 5;
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
  $fn = trim((string)($_POST['first_name'] ?? ''));
  $ln = trim((string)($_POST['last_name'] ?? ''));
  $email = trim((string)($_POST['email'] ?? ''));
  $pass = (string)($_POST['password'] ?? '');

  if ($fn==='' || $ln==='' || $email==='' || $pass==='') {
    $err = $rtl ? 'يرجى تعبئة جميع الحقول' : 'Please fill all fields';
  } else {
    $st=$db->prepare("SELECT COUNT(*) FROM users WHERE email=:e");
    $st->execute([':e'=>$email]);
    if ((int)$st->fetchColumn()>0) {
      $err = $rtl ? 'البريد مستخدم مسبقاً' : 'Email already exists';
    } else {
      $roleId = find_author_role_id($db);
      $hash = password_hash($pass, PASSWORD_BCRYPT);
      $db->prepare("// Pack198.9 server-side validate registration custom fields
    if(function_exists('validate_required_custom_fields_v3')) {
      $missing = validate_required_custom_fields_v3('registration');
      if(!empty($missing)) {
        if(function_exists('flash_set')) {
          $msg = (current_lang()==='ar')
            ? ('الرجاء تعبئة الحقول الإلزامية: ' . implode('، ', $missing))
            : ('Please fill required fields: ' . implode(', ', $missing));
          flash_set('danger', $msg);
        }
        header('Location: ' . base_path('register.php'));
        exit;
      }
    }

INSERT INTO users(role_id,first_name,last_name,email,password_hash,preferred_lang,is_active) VALUES(:r,:f,:l,:e,:p,:pl,1)")
         ->execute([':r'=>$roleId, ':f'=>$fn, ':l'=>$ln, ':e'=>$email, ':p'=>$hash, ':pl'=>($rtl?'ar':'en')]);

      $uid = (int)$db->lastInsertId();
      if(function_exists('save_custom_fields_v3')){ save_custom_fields_v3('registration',$uid); }

      if(function_exists('save_custom_fields')){ save_custom_fields('registration','user',$uid,'custom_fields'); }
      $_SESSION['user_id'] = $uid;
      @session_regenerate_id(true);

      if (function_exists('flash_set')) flash_set('success', $rtl ? 'تم إنشاء الحساب وتسجيل الدخول' : 'Account created and logged in');
      header('Location: ' . base_path('author'));
      exit;
    }
  }
}

header('Content-Type: text/html; charset=utf-8');
?>
<!doctype html>
<html lang="<?= $rtl?'ar':'en' ?>" dir="<?= $rtl?'rtl':'ltr' ?>">
<head>
  <meta charset="utf-8">
  <title><?= $rtl?'إنشاء حساب':'Register' ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{margin:0; font-family:"Cairo",Tahoma,Arial,sans-serif; background:linear-gradient(135deg,#0ea5e9 0%, #22c55e 100%); min-height:100vh; display:flex; align-items:center; justify-content:center}
    .wrap{width:100%; max-width:520px; padding:18px}
    .card{background:rgba(255,255,255,.96); border-radius:18px; box-shadow:0 18px 40px rgba(0,0,0,.18); padding:22px}
    h2{margin:0 0 10px}
    .lbl{font-weight:700; margin:12px 0 6px; display:block}
    input{width:100%; padding:11px 12px; border:1px solid #d1d5db; border-radius:12px; outline:none}
    input:focus{border-color:#0ea5e9; box-shadow:0 0 0 3px rgba(14,165,233,.15)}
    .btn{width:100%; padding:11px 14px; border:0; border-radius:12px; font-weight:800; cursor:pointer; background:#111827; color:#fff; margin-top:14px}
    .err{background:#fee2e2; color:#991b1b; padding:10px 12px; border-radius:12px; margin-top:12px}
    a{color:#0d6efd; text-decoration:none; font-weight:700}
  </style>
</head>
<body>
  <div class="wrap">
    <div class="card">
      <div style="display:flex;justify-content:space-between;align-items:center;gap:10px">
        <h2><?= $rtl?'إنشاء حساب':'Register' ?></h2>
        <a href="<?= htmlspecialchars(base_path('login.php')) ?>"><?= $rtl?'تسجيل الدخول':'Login' ?></a>
      </div>

      <?php if($err): ?>
        <div class="err"><?= htmlspecialchars($err,ENT_QUOTES,'UTF-8') ?></div>
        <script>window.ecToast && window.ecToast('danger', <?= json_encode($err) ?>);</script>
      <?php endif; ?>

      <form method="post">
        <label class="lbl"><?= $rtl?'الاسم الأول':'First name' ?></label>
        <input name="first_name" required>
        <label class="lbl"><?= $rtl?'اسم العائلة':'Last name' ?></label>
        <input name="last_name" required>
        <label class="lbl"><?= $rtl?'البريد الإلكتروني':'Email' ?></label>
        <input name="email" type="email" required>
        <label class="lbl"><?= $rtl?'كلمة المرور':'Password' ?></label>
        <input name="password" type="password" required>
        <button class="btn"><?= $rtl?'إنشاء الحساب':'Create account' ?></button>
      <?= function_exists('render_custom_fields') ? render_custom_fields_v2('registration','user',0) : '' ?>
        <?= function_exists('render_custom_fields_v3') ? render_custom_fields_v3('registration',0) : '' ?>
</form>
    </div>
  </div>
</body>
</html>
