<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD CHECK */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'users', 'create', $pdo);

/* INPUT */
$input = json_decode(file_get_contents('php://input'), true);

if (
    !$input ||
    empty($input['first_name']) ||
    empty($input['last_name']) ||
    empty($input['email']) ||
    empty($input['role']) ||
    empty($input['company_id'])
) {
    json_response(false, 'Missing required fields.', [], 400);
}

$first_name = trim($input['first_name']);
$last_name  = trim($input['last_name']);
$email      = strtolower(trim($input['email']));
$role       = trim($input['role']);
$company_id = (int)$input['company_id'];

/* VALIDATE ROLE FROM DB (NO HARDCODE) */
$stmt = $pdo->prepare("SELECT COUNT(*) FROM roles WHERE role_key = ?");
$stmt->execute([$role]);

if ((int)$stmt->fetchColumn() === 0) {
    json_response(false, 'Invalid role.', [], 400);
}

/* OPTIONAL: Block super_admin creation unless explicit permission */
if ($role === 'super_admin') {
    json_response(false, 'Cannot create super_admin via this endpoint.', [], 403);
}

/* COMPANY VALIDATION */
$stmt = $pdo->prepare("SELECT rsp_id FROM companies WHERE id = ?");
$stmt->execute([$company_id]);
$companyRsp = $stmt->fetchColumn();

if (!$companyRsp) {
    json_response(false, 'Invalid company.', [], 400);
}

/* TENANT ISOLATION */
enforce_rsp_isolation($user, (int)$companyRsp);

/* EMAIL UNIQUENESS */
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
$stmt->execute([$email]);

if ((int)$stmt->fetchColumn() > 0) {
    json_response(false, 'Email already exists.', [], 400);
}

/* PASSWORD */
$temp_password = bin2hex(random_bytes(4));
$password_hash = password_hash($temp_password, PASSWORD_DEFAULT);

/* INSERT */
$stmt = $pdo->prepare("
    INSERT INTO users 
    (first_name, last_name, email, password_hash, role, company_id, status, created_at)
    VALUES (?, ?, ?, ?, ?, ?, 'active', NOW())
");

$stmt->execute([
    $first_name,
    $last_name,
    $email,
    $password_hash,
    $role,
    $company_id
]);

$new_user_id = (int)$pdo->lastInsertId();

/* AUDIT LOG */
log_admin_action(
    $pdo,
    (int)$user['id'],
    'users',
    'create',
    $new_user_id
);

/* RESPONSE */
json_response(true, 'User created successfully.', [
    'user_id' => $new_user_id,
    'temporary_password' => $temp_password
]);