<?php
/**
 * POST /api/admin/create_admin.php
 * Body (JSON): { email, password, full_name }
 * Admin-only. Creates a brand-new admin account directly - pre-verified
 * (an admin creating another admin is already a trusted action, so there's
 * no need to route through the email verification flow that regular
 * signups go through) and with a personal_profiles row so profile/me.php
 * and profile/update.php work for them immediately.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
require_login();
require_role(['admin']);

$input = get_json_input();
$email = filter_var(trim($input['email'] ?? ''), FILTER_VALIDATE_EMAIL);
$password = (string) ($input['password'] ?? '');
$fullName = trim($input['full_name'] ?? '');

if (!$email) {
    send_error('A valid email address is required.', 422);
}
if (strlen($password) < 8) {
    send_error('Password must be at least 8 characters.', 422);
}
if ($fullName === '') {
    send_error('Full name is required.', 422);
}

$pdo = Database::connect();

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

$passwordHash = password_hash($password, PASSWORD_BCRYPT);

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare(
        'INSERT INTO users (email, password_hash, account_type, email_verified_at) VALUES (?, ?, "admin", NOW())'
    );
    $stmt->execute([$email, $passwordHash]);
    $newAdminId = (int) $pdo->lastInsertId();

    $stmt = $pdo->prepare('INSERT INTO personal_profiles (user_id, full_name) VALUES (?, ?)');
    $stmt->execute([$newAdminId, $fullName]);

    $stmt = $pdo->prepare('INSERT INTO loyalty_points (user_id, points_balance) VALUES (?, 0)');
    $stmt->execute([$newAdminId]);

    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    send_error('Could not create the admin account.', 500, APP_ENV === 'local' ? [$e->getMessage()] : []);
}

send_json(true, 'Admin account created.', ['id' => $newAdminId], 201);
