<?php
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/seed_chart.php';
require_once __DIR__ . '/../app/db_tools.php';
require_once __DIR__ . '/../app/audit.php';

session_start();
if (!empty($_SESSION['user_id'])) { header("Location: " . url("/index.php")); exit; }

$err = '';
$ok = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $company = trim($_POST['company_name'] ?? '');
  $currency = trim($_POST['currency'] ?? 'EGP');
  $taxFileNo = trim($_POST['tax_file_no'] ?? '');
  $commercialRegisterNo = trim($_POST['commercial_register_no'] ?? '');
  $phone1 = trim($_POST['phone1'] ?? '');
  $phone2 = trim($_POST['phone2'] ?? '');
  $name = trim($_POST['name'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $pass = (string)($_POST['password'] ?? '');

  if (!$company || !$name || !$email || !$pass) $err = "من فضلك أكمل جميع البيانات";
  else {
    $pdo = db();
    ensure_company_profile_columns($pdo);
    ensure_audit_tables($pdo);
    $manageTx = !$pdo->inTransaction();
    if ($manageTx) $pdo->beginTransaction();
    try {
      $stmt = $pdo->prepare("INSERT INTO companies (name, currency, tax_file_no, commercial_register_no, phone1, phone2) VALUES (?, ?, ?, ?, ?, ?)");
      $stmt->execute([$company, $currency, $taxFileNo ?: null, $commercialRegisterNo ?: null, $phone1 ?: null, $phone2 ?: null]);
      $cid = (int)$pdo->lastInsertId();

      $hash = password_hash($pass, PASSWORD_DEFAULT);
      $stmt = $pdo->prepare("INSERT INTO users (company_id, name, email, password_hash, role) VALUES (?,?,?,?, 'owner')");
      $stmt->execute([$cid, $name, $email, $hash]);

      seed_default_chart($pdo, $cid);

      if ($manageTx) $pdo->commit();
      audit_log($pdo, ['company_id'=>$cid,'user_id'=>null,'module'=>'auth','action'=>'REGISTER_COMPANY','entity_type'=>'company','entity_id'=>(string)$cid,'description'=>'إنشاء شركة جديدة ومالك النظام']);
      $ok = "تم إنشاء الشركة بنجاح. يمكنك تسجيل الدخول الآن.";
    } catch (Throwable $e) {
      if ($manageTx && $pdo->inTransaction()) $pdo->rollBack();
      $err = "حدث خطأ: " . $e->getMessage();
    }
  }
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>إنشاء شركة - Arqaamy ERP</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<link rel="icon" type="image/png" href="<?= h(url('/assets/img/favicon.png')) ?>">
<style>
body{ background:#0f172a; min-height:100vh; display:grid; place-items:center; }
.cardx{ border:0; border-radius:18px; box-shadow:0 20px 60px rgba(2,6,23,.45); }
</style>
</head>
<body>
<div class="container" style="max-width: 720px;">
  <div class="card cardx">
    <div class="card-body p-4 p-md-5">
      <div class="d-flex align-items-center gap-2 mb-3">
        <div class="rounded-4 p-3" style="background: rgba(15,23,42,.08);">
          <img src="<?= h(url('/assets/img/favicon.png')) ?>" alt="Arqaamy ERP" style="width:54px;height:54px;border-radius:16px;object-fit:cover;">
        </div>
        <div>
          <div class="fw-bold fs-4">إنشاء شركة جديدة</div>
          <div class="text-secondary small">سيتم إنشاء شجرة حسابات افتراضية تلقائيًا</div>
        </div>
      </div>

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

      <form method="post" class="row g-3">
        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
        <div class="col-12 col-md-8">
          <label class="form-label">اسم الشركة</label>
          <input class="form-control" name="company_name" required>
        </div>
        <div class="col-12 col-md-4">
          <label class="form-label">العملة</label>
          <select class="form-select" name="currency">
            <option value="EGP">EGP</option>
            <option value="USD">USD</option>
            <option value="SAR">SAR</option>
            <option value="AED">AED</option>
            <option value="EUR">EUR</option>
          </select>
        </div>

        <div class="col-12 col-md-6">
          <label class="form-label">رقم الملف الضريبي</label>
          <input class="form-control" name="tax_file_no">
        </div>
        <div class="col-12 col-md-6">
          <label class="form-label">رقم السجل التجاري</label>
          <input class="form-control" name="commercial_register_no">
        </div>
        <div class="col-12 col-md-6">
          <label class="form-label">رقم الشركة 1</label>
          <input class="form-control" name="phone1">
        </div>
        <div class="col-12 col-md-6">
          <label class="form-label">رقم الشركة 2</label>
          <input class="form-control" name="phone2">
        </div>

        <div class="col-12 col-md-6">
          <label class="form-label">اسم المالك</label>
          <input class="form-control" name="name" required>
        </div>
        <div class="col-12 col-md-6">
          <label class="form-label">البريد الإلكتروني</label>
          <input class="form-control" name="email" type="email" required>
        </div>
        <div class="col-12">
          <label class="form-label">كلمة المرور</label>
          <input class="form-control" name="password" type="password" required>
        </div>

        <div class="col-12">
          <button class="btn btn-dark w-100">
            <i class="bi bi-check2-circle"></i> إنشاء الشركة
          </button>
        </div>

        <div class="col-12 text-center">
          <a href="<?= url('/auth/login.php') ?>" class="text-decoration-none">رجوع لتسجيل الدخول</a>
        </div>
      </form>
    </div>
  </div>
</div>
</body>
</html>
