<?php
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/csrf.php';
$pdo = require __DIR__ . '/../app/config/database.php';

session_boot();

if (is_post()) {
  csrf_verify();
  try {
    $full_name = trim($_POST['full_name'] ?? '');
    $email = strtolower(trim($_POST['email'] ?? ''));
    $password = $_POST['password'] ?? '';

    if (strlen($full_name) < 3) throw new Exception('Full name is too short');
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) throw new Exception('Invalid email');
    if (strlen($password) < 6) throw new Exception('Password must be at least 6 characters');

    $hash = password_hash($password, PASSWORD_DEFAULT);

    $pdo->beginTransaction();

    $stmt = $pdo->prepare("INSERT INTO users (full_name, email, password_hash) VALUES (?,?,?)");
    $stmt->execute([$full_name, $email, $hash]);
    $userId = (int)$pdo->lastInsertId();

    // Create default Savings account
    $accountNo = 'AB' . str_pad((string)$userId, 8, '0', STR_PAD_LEFT);
    $pdo->prepare("INSERT INTO accounts (user_id, account_no, account_type, currency) VALUES (?,?, 'savings', 'GHS')")
        ->execute([$userId, $accountNo]);

    // Create crypto wallets (BTC/ETH/USDT)
    $assets = $pdo->query("SELECT id FROM crypto_assets WHERE enabled=1")->fetchAll();
    $w = $pdo->prepare("INSERT INTO crypto_wallets (user_id, asset_id, balance) VALUES (?,?,0)");
    foreach ($assets as $a) $w->execute([$userId, (int)$a['id']]);

    $pdo->commit();

    flash('ok', 'Account created. Please login to continue.');
    redirect('login.php');

  } catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    flash('err', $e->getMessage());
  }
}

$title = 'Open Astrabank Account';
include __DIR__ . '/../views/partials/head.php';
include __DIR__ . '/../views/partials/nav_website.php';
?>

<div class="container py-5" style="max-width:680px">
  <div class="card ab-card p-4">
    <h2 class="fw-bold mb-1">Open an account</h2>
    <div class="ab-muted mb-4">Create your Astrabank online banking profile.</div>

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

    <form method="post">
      <?= csrf_field() ?>
      <div class="mb-3">
        <label class="form-label">Full name</label>
        <input name="full_name" class="form-control" required>
      </div>
      <div class="mb-3">
        <label class="form-label">Email</label>
        <input name="email" type="email" class="form-control" required>
      </div>
      <div class="mb-3">
        <label class="form-label">Password</label>
        <input name="password" type="password" class="form-control" required>
        <div class="form-text">At least 6 characters.</div>
      </div>
      <button class="btn ab-btn text-white w-100">Create account</button>
    </form>

    <div class="mt-3 text-center">
      <a href="login.php">Already have an account? Login</a>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../views/partials/foot.php'; ?>
