<?php
// =============================================================
//  POST /api/v1/staff/reset_password  { "id": 5 }
//
//  Resets a staff account's password to the same default
//  ('STH@12345') the web page uses, sets password_change_required=1,
//  and sends the same SMS (via Velstack, if a phone is on file) and
//  email notification app/edit_user.php's reset_password action sends —
//  wrapping that logic directly rather than re-deriving it, including
//  its own graceful "password reset but SMS failed" fallback.
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/account_helpers.php';
require_once __DIR__ . '/../../../services/VelstackServiceProvider.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

$account = api_authenticate();
api_require_permission('edit_user');

const DEFAULT_STAFF_PASSWORD = 'STH@12345';

$body = json_decode(file_get_contents('php://input'), true) ?? [];
$userId = (int)($body['id'] ?? 0);
if (!$userId) Api::error(422, 'ValidationError', 'id is required');
if ($userId === $account->getId()) {
    Api::error(403, 'Forbidden', 'Use the change-password flow for your own account');
}

$target = $conn->prepare("SELECT phone, firstname, email FROM users WHERE id = ?");
$target->bind_param('i', $userId);
$target->execute();
$targetRow = $target->get_result()->fetch_assoc();
$target->close();
if (!$targetRow) {
    Api::error(404, 'NotFound', 'Staff account not found');
}

$hash = password_hash(DEFAULT_STAFF_PASSWORD, PASSWORD_BCRYPT);
$stmt = $conn->prepare("UPDATE users SET password = ?, password_change_required = 1 WHERE id = ?");
$stmt->bind_param('si', $hash, $userId);
if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not reset the password. Please try again.');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'reset_password', 'users', $userId);

$smsStatus = 'not_attempted';
if (!empty($targetRow['phone'])) {
    try {
        $svc = new VelstackServiceProvider();
        $msg = "Hello {$targetRow['firstname']}! Your STH NRMS password has been reset. Email: {$targetRow['email']}, New Password: " . DEFAULT_STAFF_PASSWORD . ". Please change on login.";
        $sr = $svc->sendQuickSMS($targetRow['phone'], $msg);
        $smsStatus = ($sr['status_code'] ?? null) == 200 ? 'sent' : 'failed';
    } catch (Throwable $e) {
        error_log('staff/reset_password.php: SMS failed — ' . $e->getMessage());
        $smsStatus = 'failed';
    }
}
if (!empty($targetRow['email'])) {
    sendAccountEmail($targetRow['email'], 'Your STH NRMS Password Has Been Reset', 'Password Reset', [
        "Hello <strong>{$targetRow['firstname']}</strong>,",
        'Your STH NRMS password has been reset by an administrator.',
        'New password: <strong>' . DEFAULT_STAFF_PASSWORD . '</strong>',
        'Please log in and change it immediately.',
    ]);
}

Api::success(['id' => $userId, 'new_password' => DEFAULT_STAFF_PASSWORD, 'sms_status' => $smsStatus]);
