<?php

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/mail.php';

header('Content-Type: application/json');

// Collect input
$firstname = trim($_POST['firstname'] ?? '');
$lastname  = trim($_POST['lastname'] ?? '');
$email     = trim($_POST['email'] ?? '');
$phone     = trim($_POST['phone'] ?? '');
$password  = $_POST['password'] ?? '';
$account_type = trim($_POST['account_type'] ?? '');
$currency  = trim($_POST['currency'] ?? '');
$gender    = trim($_POST['gender'] ?? '');
$country   = trim($_POST['country'] ?? '');
$dob       = trim($_POST['dob'] ?? '');
$address   = trim($_POST['address'] ?? '');
$tpin      = trim($_POST['tpin'] ?? '');

if (!$firstname || !$lastname || !$email || !$password || !$account_type || !$currency || !$tpin || !$country) {
    echo json_encode(['status' => 'error', 'message' => 'All required fields must be filled.']);
    exit;
}

// Check if email exists
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);

if ($stmt->fetch()) {
    echo json_encode(['status' => 'error', 'message' => 'Email already exists.']);
    exit;
}

// Generate system fields
$fullname = "$firstname $lastname";
$hashed   = password_hash($password, PASSWORD_DEFAULT);
$verify_code = bin2hex(random_bytes(16));
$account_number = rand(1000000000, 9999999999);
$pin_code = rand(10000, 99999);
$status = 'pending';
$is_verified = 0;
$account_balance = 0.00;

// Insert into database
$stmt = $pdo->prepare("
    INSERT INTO users 
    (firstname, lastname, email, phone, password, pshow, verification_code, is_verified, status, 
     pin_code, account_number, account_type, account_balance, currency, address, gender, country, dob, created_at, transfer_pin)
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?)
");

$stmt->execute([
    $firstname, $lastname, $email, $phone, $hashed, $password, $verify_code, $is_verified, $status,
    $pin_code, $account_number, $account_type, $account_balance, $currency, $address,
    $gender, $country, $dob, $tpin
]);

// Send emails
$verify_url = "https://intlbmellon.com/verify?code=$verify_code";

$userEmail = $email;
$userMailSent = sendMail($userEmail, "Verify Your Bmellonglobal Account", "
<div style='font-family: Arial, sans-serif; background:#f5f6fa; max-width:600px; margin:auto; padding:20px; border-radius:8px;'>
  <div style='background:#a43931; color:white; text-align:center; padding:15px; border-radius:8px;'>
      <h2>Account Registration</h2>
  </div>
  <div style='background:#fff; padding:20px; border-radius:8px; margin-top:15px;'>
      <p>Hello $firstname,</p>
      <p>Thank you for registering with <b>Bmellonglobal</b>.<br>
      Please verify your account using the link below:</p>
      <p><a href='$verify_url'>$verify_url</a></p>

      <p><b>Account Number:</b> $account_number<br>
         <b>Currency:</b> $currency<br>
         <b>Account Type:</b> $account_type<br>
         <b>Transfer Pin:</b> $tpin<br>
         <b>Status:</b> Pending Verification</p>
  </div>
  <div style='text-align:center; padding:10px; color:#888; font-size:13px;'>
      Bmellonglobal Bank � Secure Digital Banking
  </div>
</div>
");

// Admin alert
$adminEmail = "contact@intlbmellon.com";

$adminMailSent = sendMail($adminEmail, "New User Registration on Bmellonglobal", "
<div style='font-family: Arial, sans-serif; background:#f5f6fa; max-width:600px; margin:auto; padding:20px; border-radius:8px;'>
  <div style='background:#a43931; color:white; text-align:center; padding:15px; border-radius:8px;'>
      <h2>New User Registration Alert</h2>
  </div>
  <div style='background:#fff; padding:20px; border-radius:8px; margin-top:15px;'>
      <p>A new user has registered on <b>Bmellonglobal</b>.</p>

      <p><b>Full Name:</b> $fullname<br>
         <b>Email:</b> $email<br>
         <b>Phone:</b> $phone<br>
         <b>Account Number:</b> $account_number<br>
         <b>Currency:</b> $currency<br>
         <b>Account Type:</b> $account_type<br>
         <b>Status:</b> Pending Customer Unit Verification</p>

      <p>Verification: <a href='$verify_url'>$verify_url</a></p>
  </div>
  <div style='text-align:center; padding:10px; color:#888; font-size:13px;'>
      Bmellonglobal Bank � Secure Digital Banking
  </div>
</div>
");

if ($userMailSent) {
    echo json_encode([
        'status' => 'success',
        'message' => 'Registration successful! Please check your email for verification.',
        'email' => $email,
        'verify_url_fallback' => $verify_url
    ]);
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Registration saved but email could not be sent.'
    ]);
}

?>
