<?php
require_once __DIR__ . '/functions.php';

$tenant = enrep_tenant_segment($_POST['tenant'] ?? $_GET['tenant'] ?? null);
if ($tenant !== '' && !defined('CONFIG_LOADED')) {
    require_once '../../' . $tenant . '/config.php';
}

enrep_require_admin();

$con = $GLOBALS['con'] ?? null;
if (!$con instanceof mysqli) {
    assetmanager_json_response(['success' => false, 'message' => 'Tenant database connection unavailable.']);
}
$con->set_charset('utf8mb4');

if (!assetmanager_table_exists($con, 'assetmanager_users')) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset Manager operator table is not installed yet.']);
}

$clientnumber = enrep_request_int('clientnumber', 0);
$operatorId = enrep_request_int('operator_id', 0);
$mode = enrep_request_enum('mode', ['create', 'update_status'], 'create');
assetmanager_json_require_client_access($con, $clientnumber);

$now = date('Y-m-d H:i:s');

if ($mode === 'update_status') {
    $status = enrep_request_enum('status_key', ['active', 'disabled'], 'active');
    $stmt = $con->prepare("UPDATE assetmanager_users SET status_key=?, updated_at=? WHERE id=? AND tenant_key=? AND clientnumber=?");
    if (!$stmt) {
        assetmanager_json_response(['success' => false, 'message' => 'Operator status could not be prepared.']);
    }
    $stmt->bind_param('ssisi', $status, $now, $operatorId, $tenant, $clientnumber);
    $ok = $stmt->execute();
    $stmt->close();
    assetmanager_json_response(['success' => $ok, 'message' => $ok ? 'Operator status updated.' : 'Operator status could not be updated.']);
}

$name = enrep_request_string('operator_name', '', 160);
$email = strtolower(enrep_request_string('operator_email', '', 190));
$password = enrep_request_string('operator_password', '', 255);
$role = enrep_request_enum('role_key', ['operator', 'manager'], 'operator');

if ($name === '' || $email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    assetmanager_json_response(['success' => false, 'message' => 'Operator name and a valid email are required.']);
}
if (strlen($password) < 8) {
    assetmanager_json_response(['success' => false, 'message' => 'Operator password must be at least 8 characters.']);
}

$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$prefsJson = assetmanager_encode_json([]);
$status = 'active';

$stmt = $con->prepare("
    INSERT INTO assetmanager_users
        (tenant_key, clientnumber, name, email, password_hash, role_key, status_key, preferences_json, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Operator could not be prepared. Check the operator schema update has been installed.']);
}
$stmt->bind_param('sissssssss', $tenant, $clientnumber, $name, $email, $passwordHash, $role, $status, $prefsJson, $now, $now);
$ok = $stmt->execute();
$error = $stmt->errno === 1062 ? 'An operator with that email already exists for this client.' : 'Operator could not be created.';
$operatorId = $ok ? (int)$stmt->insert_id : 0;
$stmt->close();

if ($ok) {
    assetmanager_audit($con, $tenant, $clientnumber, assetmanager_actor_user_id(), 'operator', $operatorId, 'create', [], [
        'name' => $name,
        'email' => $email,
        'role_key' => $role,
    ]);
}

assetmanager_json_response(['success' => $ok, 'operator_id' => $operatorId, 'message' => $ok ? 'Operator created.' : $error]);
