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

if (FORCE_HTTPS && empty($_SERVER['HTTPS'])) {
  header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
  exit;
}

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

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $email = trim($_POST['email'] ?? '');
  $pass  = (string)($_POST['password'] ?? '');

  if (!$email || !$pass) $err = "من فضلك أدخل البريد وكلمة المرور";
  else {
    $pdo = db();
    ensure_audit_tables($pdo);
    ensure_user_profile_columns($pdo);
    $stmt = $pdo->prepare("SELECT u.*, c.name AS company_name FROM users u JOIN companies c ON c.id=u.company_id WHERE u.email=? LIMIT 1");
    $stmt->execute([$email]);
    $u = $stmt->fetch();
    if (!$u || !(int)$u['is_active'] || !password_verify($pass, $u['password_hash'])) {
      $err = "بيانات الدخول غير صحيحة";
    } else {
      $_SESSION['user_id'] = (int)$u['id'];
      $_SESSION['company_id'] = (int)$u['company_id'];
      $_SESSION['user_name'] = $u['name'];
      $_SESSION['user_role'] = $u['role'];
      $_SESSION['company_name'] = $u['company_name'];
      $_SESSION['theme_mode'] = ($u['theme_mode'] ?? 'light') === 'dark' ? 'dark' : 'light';
      audit_log($pdo, ['company_id'=>(int)$u['company_id'],'user_id'=>(int)$u['id'],'module'=>'auth','action'=>'LOGIN','entity_type'=>'user','entity_id'=>(string)$u['id'],'description'=>'تسجيل دخول ناجح']);
      header("Location: " . url("/index.php"));
      exit;
    }
  }
}
?>
<!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: 520px;">
  <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">Arqaamy ERP</div>
          <div class="text-secondary small">من أي مكان</div>
        </div>
      </div>

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

      <form method="post">
        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
        <div class="mb-3">
          <label class="form-label">البريد الإلكتروني</label>
          <input class="form-control" name="email" type="email" required>
        </div>
        <div class="mb-3">
          <label class="form-label">كلمة المرور</label>
          <input class="form-control" name="password" type="password" required>
        </div>

        <button class="btn btn-dark w-100">
          <i class="bi bi-box-arrow-in-left"></i> دخول
        </button>

        <div class="text-center mt-3">
          <a href="<?= url('/auth/register.php') ?>" class="text-decoration-none">إنشاء شركة جديدة</a>
        </div>
      </form>
    </div>
  </div>

  <div class="text-center mt-3" style="color: rgba(226,232,240,.75);">
    <small>© <?= date('Y') ?> Arqaamy ERP</small>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
