<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';

if (isUserLoggedIn()) { header('Location: /dashboard.php'); exit; }

// Check if registration enabled
if (!getSetting($pdo, 'registration_enabled', '1')) {
    die('<div style="font-family:Arial;padding:40px;text-align:center;"><h2>Registration Disabled</h2><p>New registrations are currently not accepted. Please contact support.</p></div>');
}

$error = ''; $success = '';
$ref = trim($_GET['ref'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) { $error = 'Invalid request.'; goto done; }
    $fname = trim($_POST['first_name'] ?? '');
    $lname = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $pass  = $_POST['password'] ?? '';
    $pass2 = $_POST['confirm_password'] ?? '';
    $dob   = $_POST['date_of_birth'] ?? '';
    $country = trim($_POST['country'] ?? '');
    $atype = $_POST['account_type'] ?? 'savings';
    $refCode = trim($_POST['ref_code'] ?? $ref);

    if (!$fname || !$lname || !$email || !$pass) { $error = 'Please fill in all required fields.'; goto done; }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $error = 'Invalid email address.'; goto done; }
    if (strlen($pass) < 8) { $error = 'Password must be at least 8 characters.'; goto done; }
    if ($pass !== $pass2) { $error = 'Passwords do not match.'; goto done; }

    // Check duplicate
    $chk = $pdo->prepare("SELECT id FROM users WHERE email=? LIMIT 1");
    $chk->execute([$email]);
    if ($chk->fetch()) { $error = 'An account with this email already exists.'; goto done; }

    $accNum = generateAccountNumber();
    // Ensure unique
    while (true) {
        $c2 = $pdo->prepare("SELECT id FROM users WHERE account_number=? LIMIT 1");
        $c2->execute([$accNum]);
        if (!$c2->fetch()) break;
        $accNum = generateAccountNumber();
    }

    $hash = password_hash($pass, PASSWORD_DEFAULT);
    $defaultPin = password_hash('0000', PASSWORD_DEFAULT);

    $pdo->prepare("INSERT INTO users (account_number,first_name,last_name,email,phone,date_of_birth,country,password,pin,account_type,account_status,kyc_status,currency) VALUES (?,?,?,?,?,?,?,?,?,'savings','pending','pending','USD')")->execute([$accNum,$fname,$lname,$email,$phone,$dob,$country,$hash,$defaultPin]);
    $newId = (int)$pdo->lastInsertId();

    // Handle referral
    if ($refCode) {
        $refAdmin = $pdo->prepare("SELECT id FROM admin_users WHERE username=? LIMIT 1");
        $refAdmin->execute([$refCode]);
        $ra = $refAdmin->fetch();
        if ($ra) {
            $pdo->prepare("INSERT INTO activity_logs (user_id,admin_id,action,description) VALUES (?,?,'customer_assigned','Customer assigned via referral link')")->execute([$newId, $ra['id']]);
        }
    }

    logActivity($pdo, $newId, null, 'register', 'New user registration');
    addNotification($pdo, $newId, 'Welcome to Flexi Access Bank!', "Your account ($accNum) has been created. Complete your KYC to unlock full access.", 'success');

    flash('success', 'Account created successfully! Your account number is ' . $accNum . '. Please log in.');
    header('Location: /login.php');
    exit;
}
done:
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Register | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body class="auth-page" style="align-items:flex-start;padding:2rem 0;">
<div class="container">
  <div class="d-flex justify-content-center">
    <div class="auth-card fade-in-up" style="max-width:560px;">
      <div class="auth-logo"><img src="/assets/img/logo.png" alt="<?= SITE_NAME ?>"></div>
      <h2 class="auth-title">Create Your Account</h2>
      <p class="auth-subtitle">Join <?= SITE_NAME ?> today</p>
      <?php if ($error): ?><div class="alert alert-danger py-2 small"><i class="fa fa-exclamation-circle me-1"></i><?= sanitize($error) ?></div><?php endif; ?>
      <form method="POST">
        <?= csrf_field() ?>
        <?php if ($ref): ?><input type="hidden" name="ref_code" value="<?= sanitize($ref) ?>"><?php endif; ?>
        <div class="row g-3">
          <div class="col-6">
            <label class="form-label">First Name <span class="text-danger">*</span></label>
            <input type="text" name="first_name" class="form-control" placeholder="John" required>
          </div>
          <div class="col-6">
            <label class="form-label">Last Name <span class="text-danger">*</span></label>
            <input type="text" name="last_name" class="form-control" placeholder="Doe" required>
          </div>
          <div class="col-12">
            <label class="form-label">Email Address <span class="text-danger">*</span></label>
            <div class="input-group"><span class="input-group-text"><i class="fa fa-envelope"></i></span>
            <input type="email" name="email" class="form-control" placeholder="you@example.com" required></div>
          </div>
          <div class="col-md-6">
            <label class="form-label">Phone</label>
            <input type="text" name="phone" class="form-control" placeholder="+1 234 567 8900">
          </div>
          <div class="col-md-6">
            <label class="form-label">Date of Birth</label>
            <input type="date" name="date_of_birth" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Country</label>
            <select name="country" class="form-select">
              <option value="">Select country</option>
              <option>United States of America</option><option>United Kingdom</option><option>Canada</option>
              <option>Germany</option><option>France</option><option>Nigeria</option><option>South Africa</option>
              <option>Egypt</option><option>India</option><option>Italy</option><option>Singapore</option>
              <option>Other</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Account Type</label>
            <select name="account_type" class="form-select">
              <option value="savings">Savings</option>
              <option value="checking">Checking</option>
              <option value="business">Business</option>
            </select>
          </div>
          <div class="col-12">
            <label class="form-label">Password <span class="text-danger">*</span></label>
            <div class="input-group"><span class="input-group-text"><i class="fa fa-lock"></i></span>
            <input type="password" name="password" id="pwd" class="form-control" placeholder="Min. 8 characters" minlength="8" required>
            <button type="button" class="btn btn-outline-secondary" onclick="const f=document.getElementById('pwd');f.type=f.type==='password'?'text':'password'"><i class="fa fa-eye"></i></button></div>
          </div>
          <div class="col-12">
            <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
            <div class="input-group"><span class="input-group-text"><i class="fa fa-lock"></i></span>
            <input type="password" name="confirm_password" class="form-control" placeholder="Repeat password" required></div>
          </div>
          <div class="col-12">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="terms" required>
              <label class="form-check-label small" for="terms">I agree to the <a href="/#terms" style="color:var(--primary)">Terms & Conditions</a> and <a href="/#privacy" style="color:var(--primary)">Privacy Policy</a></label>
            </div>
          </div>
          <div class="col-12">
            <button class="btn btn-primary w-100 py-2 fw-bold">Create Account <i class="fa fa-arrow-right ms-1"></i></button>
          </div>
        </div>
      </form>
      <hr><p class="text-center small mb-0">Already have an account? <a href="/login.php" style="color:var(--primary)">Sign in</a></p>
    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body></html>
