<?php
// =============================================================
//  POST /api/v1/passwords/reset
//
//  Mirrors app/manage_password.php's own reset_password action exactly
//  — resets one account (staff, rotation nurse, or clinical student) to
//  its category's default password and sets password_change_required=1,
//  forcing that user through the change-password flow on next login.
//  Deliberately does NOT send an SMS/email notification: unlike
//  api/v1/staff/reset_password.php (which wraps app/edit_user.php's own
//  reset action, a different desktop page that does notify), the
//  desktop manage_password.php page this endpoint ports has never sent
//  one either — a genuine, pre-existing difference between the two
//  desktop reset flows, not something to paper over here.
//
//  Body: { "category": "staff" | "nurse" | "student", "target_id": 5 }
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';

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

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

// Matches app/manage_password.php's own $table_map and hardcoded
// DEFAULT_STAFF_PASSWORD/DEFAULT_STUDENT_PASSWORD — not yet wired to
// the settings table's default_staff_password/default_student_password
// rows, the same known gap that page's own header comment and
// api/v1/staff/reset_password.php both already carry.
const TABLE_MAP = [
    'staff'   => ['table' => 'users',            'default_pwd' => 'STH@12345'],
    'nurse'   => ['table' => 'rotation_nurses',   'default_pwd' => 'STHstudent123'],
    'student' => ['table' => 'clinical_students', 'default_pwd' => 'STHstudent123'],
];

$body     = Api::body();
$category = (string)($body['category'] ?? '');
$targetId = (int)($body['target_id'] ?? 0);

if (!isset(TABLE_MAP[$category])) Api::error(422, 'ValidationError', 'Invalid category');
if ($targetId <= 0) Api::error(422, 'ValidationError', 'Invalid user');
if ($category === 'staff' && $targetId === $account->getId()) {
    Api::error(403, 'Forbidden', 'You cannot reset your own password here. Use Change Password instead.');
}

$cfg = TABLE_MAP[$category];
$hashed = password_hash($cfg['default_pwd'], PASSWORD_DEFAULT);
$stmt = $conn->prepare("UPDATE `{$cfg['table']}` SET password = ?, password_change_required = 1 WHERE id = ?");
$stmt->bind_param('si', $hashed, $targetId);

if (!$stmt->execute() || $stmt->affected_rows === 0) {
    $stmt->close();
    Api::error(404, 'NotFound', 'Account not found or update failed.');
}
$stmt->close();

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'reset_password', $cfg['table'], $targetId, null, json_encode(['category' => $category]));

Api::success(['id' => $targetId, 'default_password' => $cfg['default_pwd']]);
