<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';
require_once __DIR__ . '/../../includes/mailer.php';

apply_cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['full_name', 'email', 'password']);

$email = strtolower(clean_str($input['email']));
$fullName = clean_str($input['full_name']);
$password = (string) $input['password'];
$phone = clean_str($input['phone_number'] ?? '');

if (!is_valid_email($email)) {
    send_error('Invalid email address.', 422);
}
if (strlen($password) < 8) {
    send_error('Password must be at least 8 characters.', 422);
}

$pdo = getDbConnection();

// Require a verified (used) OTP for this email in the last 30 minutes —
// prevents registering an unverified email directly through this endpoint.
$otpCheck = $pdo->prepare(
    'SELECT id FROM email_otps WHERE email = :email AND is_used = 1 AND created_at > (NOW() - INTERVAL 30 MINUTE)
     ORDER BY id DESC LIMIT 1'
);
$otpCheck->execute([':email' => $email]);
if (!$otpCheck->fetch()) {
    send_error('Please verify your email with the OTP before registering.', 422);
}

$existing = $pdo->prepare('SELECT id FROM users WHERE email = :email');
$existing->execute([':email' => $email]);
if ($existing->fetch()) {
    send_error('An account with this email already exists.', 409);
}

$trialDays = (int) ($pdo->query('SELECT default_trial_days FROM app_settings WHERE id = 1')->fetchColumn() ?: 2);
$hash = password_hash($password, PASSWORD_DEFAULT);
$licenseKey = 'TRIAL-' . strtoupper(bin2hex(random_bytes(3)));

$stmt = $pdo->prepare(
    'INSERT INTO users (full_name, email, password_hash, phone_number, role, license_key,
                         validity_days, is_blocked, is_email_verified, activated_at)
     VALUES (:full_name, :email, :hash, :phone, "USER", :license, :validity, 0, 1, NOW())'
);
$stmt->execute([
    ':full_name' => $fullName,
    ':email'     => $email,
    ':hash'      => $hash,
    ':phone'     => $phone,
    ':license'   => $licenseKey,
    ':validity'  => $trialDays,
]);

$userId = (int) $pdo->lastInsertId();
$token = create_user_session($userId);

$html = '<div style="font-family:sans-serif;padding:24px;">'
    . '<h2>Welcome to AI Auto Reply Marketing!</h2>'
    . '<p>Hi ' . htmlspecialchars($fullName) . ', your account is ready. '
    . 'Your ' . $trialDays . '-day free trial has started.</p>'
    . '<p>License key: <strong>' . $licenseKey . '</strong></p>'
    . '</div>';
[$sent, ] = send_mail_via_settings($email, $fullName, 'Welcome to AI Auto Reply Marketing', $html);
if (!$sent) {
    error_log('Welcome email failed for ' . $email);
}

$userRow = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$userRow->execute([':id' => $userId]);
$user = $userRow->fetch();
unset($user['password_hash'], $user['reset_token'], $user['verification_token']);

send_success(['token' => $token, 'user' => $user], 'Account created.', 201);
