<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/*declare(strict_types=1);*/


require_once __DIR__ . '/../system/bootstrap.php';
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/response.php';
require_once __DIR__ . '/../system/audit.php';

$actor = require_auth($pdo);

/* =========================
   PERMISSION (rank-based)
   ========================= */

if ($actor['role_rank'] > 5) {
    error_forbidden('You are not allowed to create users');
}

/* =========================
   INPUT
   ========================= */

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

if (!is_array($input)) {
    error_bad_request('Invalid JSON');
}

$email      = trim((string)($input['email'] ?? ''));
$firstName  = trim((string)($input['first_name'] ?? ''));
$lastName   = trim((string)($input['last_name'] ?? ''));
$roleKey    = trim((string)($input['role_key'] ?? ''));
$companyId  = (int)($input['company_id'] ?? 0);

if ($email === '' || $roleKey === '' || $companyId <= 0) {
    error_bad_request('Email, role and company are required');
}

/* =========================
   FETCH TARGET ROLE RANK
   ========================= */

$stmt = $pdo->prepare("
    SELECT id, rank
    FROM roles
    WHERE role_key = :role_key
    LIMIT 1
");
$stmt->execute(['role_key' => $roleKey]);
$targetRole = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$targetRole) {
    error_bad_request('Invalid role');
}

$targetRank = (int)$targetRole['rank'];
$roleId = (int)$targetRole['id'];

/* Cannot assign equal or higher */
if ($actor['role_rank'] >= $targetRank) {
    error_forbidden('Cannot assign equal or higher role');
}

/* =========================
   VALIDATE COMPANY + PRODUCT
   ========================= */

$stmt = $pdo->prepare("
    SELECT id, rsp_id, product_id
    FROM companies
    WHERE id = :company_id
      AND deleted_at IS NULL
    LIMIT 1
");
$stmt->execute(['company_id' => $companyId]);
$company = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$company) {
    error_bad_request('Invalid company');
}

/* Product isolation */
if (!$actor['is_global'] && (int)$company['product_id'] !== $actor['product_id']) {
    error_forbidden('Product mismatch');
}

/* RSP isolation */
if ($actor['role_key'] === 'rsp_admin') {
    if ((int)$company['rsp_id'] !== $actor['company_id']) {
        error_forbidden('Cannot create outside your RSP');
    }
}

/* =========================
   DUPLICATE EMAIL CHECK
   ========================= */

$stmt = $pdo->prepare("
    SELECT id
    FROM users
    WHERE email = :email
    LIMIT 1
");
$stmt->execute(['email' => $email]);

if ($stmt->fetchColumn()) {
    error_bad_request('User with this email already exists');
}

/* =========================
   PASSWORD
   ========================= */

$password = trim((string)($input['password'] ?? ''));

if ($password === '') {
    error_bad_request('Password is required');
}

$passwordHash = password_hash($password, PASSWORD_DEFAULT);

/* =========================
   CREATE USER
   ========================= */

$stmt = $pdo->prepare("
    INSERT INTO users (
        email,
        first_name,
        last_name,
        password_hash,
        role_id,
        role_key,
        role,
        company_id,
        status,
        email_verified,
        created_at
    ) VALUES (
        :email,
        :first_name,
        :last_name,
        :password_hash,
        :role_id,
        :role_key,
        :role,
        :company_id,
        'active',
        1,
        NOW()
    )
");

$stmt->execute([
    'email'         => $email,
    'first_name'    => $firstName,
    'last_name'     => $lastName,
    'password_hash' => $passwordHash,
    'role_id'       => $roleId,
    'role_key'      => $roleKey,
    'role'          => $roleKey,
    'company_id'    => $companyId
]);

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

/* =========================
   AUDIT
   ========================= */

audit_log(
    $pdo,
    $actor,
    'create',
    'user',
    $newUserId,
    [
        'email'      => $email,
        'role_key'   => $roleKey,
        'company_id' => $companyId
    ]
);

/* =========================
   RESPONSE
   ========================= */

success('User created', [
    'user_id' => $newUserId
]);
