<?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';
}

assetmanager_require_user();

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

$operatorId = (int)($_SESSION['assetmanagerOperatorId'] ?? 0);
$clientnumber = (int)($_SESSION['assetmanagerClientnumber'] ?? 0);
if ($operatorId <= 0 || $clientnumber <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Only Asset Manager operators can update this password here.']);
}

$current = enrep_request_string('current_password', '', 255);
$new = enrep_request_string('new_password', '', 255);
$confirm = enrep_request_string('confirm_password', '', 255);

if ($current === '' || $new === '' || $confirm === '') {
    assetmanager_json_response(['success' => false, 'message' => 'Enter the current password and the new password.']);
}
if ($new !== $confirm) {
    assetmanager_json_response(['success' => false, 'message' => 'The new passwords do not match.']);
}
if (strlen($new) < 8) {
    assetmanager_json_response(['success' => false, 'message' => 'The new password must be at least 8 characters.']);
}

$stmt = $con->prepare("SELECT password_hash FROM assetmanager_users WHERE id=? AND tenant_key=? AND clientnumber=? AND status_key='active' LIMIT 1");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Password check could not be prepared.']);
}
$stmt->bind_param('isi', $operatorId, $tenant, $clientnumber);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$row || !password_verify($current, (string)($row['password_hash'] ?? ''))) {
    assetmanager_json_response(['success' => false, 'message' => 'Current password is incorrect.']);
}

$hash = password_hash($new, PASSWORD_DEFAULT);
$now = date('Y-m-d H:i:s');
$stmt = $con->prepare("UPDATE assetmanager_users SET password_hash=?, updated_at=? WHERE id=? AND tenant_key=? AND clientnumber=?");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Password update could not be prepared.']);
}
$stmt->bind_param('ssisi', $hash, $now, $operatorId, $tenant, $clientnumber);
$ok = $stmt->execute();
$stmt->close();

assetmanager_json_response(['success' => $ok, 'message' => $ok ? 'Password updated.' : 'Password could not be updated.']);
