<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

// Accept either mph_v3 style fields (new_password + confirm_password) or simple 'password'
$token = isset($_POST['token']) ? trim($_POST['token']) : '';
$password = '';
if (isset($_POST['password'])) $password = trim($_POST['password']);
elseif (isset($_POST['new_password']) && isset($_POST['confirm_password'])) {
    $np = trim($_POST['new_password']);
    $cp = trim($_POST['confirm_password']);
    if ($np !== $cp) {
        echo json_encode(['success' => false, 'message' => 'Passwords do not match.']);
        exit;
    }
    $password = $np;
}

if ($token === '' || $password === '') {
    echo json_encode(['success' => false, 'message' => 'Missing token or password']);
    exit;
}

// basic password validation
if (strlen($password) < 8 || !preg_match('/[a-zA-Z]/', $password) || !preg_match('/[0-9]/', $password)) {
    echo json_encode(['success' => false, 'message' => 'Password must be at least 8 chars and include letters and numbers']);
    exit;
}

require __DIR__ . '/db_config.php';

// Ensure users table has reset columns (best-effort: create columns if missing by inspecting information_schema)
$dbName = isset($DB_NAME) ? $DB_NAME : ( $conn->query("SELECT DATABASE() as db")->fetch_object()->db ?? '' );
if ($dbName) {
    $colCheck = $conn->prepare("SELECT COUNT(*) as cnt FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'users' AND COLUMN_NAME = ?");
    if ($colCheck) {
        $col = 'reset_token';
        $colCheck->bind_param('ss', $dbName, $col);
        $colCheck->execute();
        $r = $colCheck->get_result()->fetch_assoc();
        if (empty($r) || (int)$r['cnt'] === 0) {
            $conn->query("ALTER TABLE `users` ADD COLUMN `reset_token` VARCHAR(255) NULL DEFAULT NULL");
        }
        $col = 'reset_expiry';
        $colCheck->bind_param('ss', $dbName, $col);
        $colCheck->execute();
        $r2 = $colCheck->get_result()->fetch_assoc();
        if (empty($r2) || (int)$r2['cnt'] === 0) {
            $conn->query("ALTER TABLE `users` ADD COLUMN `reset_expiry` DATETIME NULL DEFAULT NULL");
        }
        $colCheck->close();
    }
}

// Find matching token in users table
$stmt = $conn->prepare("SELECT id, reset_expiry FROM users WHERE reset_token = ? LIMIT 1");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'DB error: prepare failed']);
    exit;
}
$stmt->bind_param('s', $token);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();

if (!$row) {
    echo json_encode(['success' => false, 'message' => 'Invalid or expired token']);
    $conn->close();
    exit;
}

$expiry = $row['reset_expiry'] ?? null;
if (empty($expiry) || strtotime($expiry) < time()) {
    echo json_encode(['success' => false, 'message' => 'Token expired']);
    $conn->close();
    exit;
}

$userId = (int)$row['id'];
// Hash or store plain password depending on configuration
$pwHash = password_hash($password, PASSWORD_DEFAULT);
$storeVal = $pwHash;
if (isset($STORE_PLAINTEXT_PASSWORDS) && $STORE_PLAINTEXT_PASSWORDS === true) {
    $storeVal = $password;
}
$upd = $conn->prepare("UPDATE users SET password_hash = ?, reset_token = NULL, reset_expiry = NULL WHERE id = ?");
if (!$upd) {
    echo json_encode(['success' => false, 'message' => 'DB error: prepare update']);
    $conn->close();
    exit;
}
$upd->bind_param('si', $storeVal, $userId);
$ok = $upd->execute();
$upd->close();
$conn->close();

if ($ok) echo json_encode(['success' => true, 'message' => 'Password updated successfully']);
else echo json_encode(['success' => false, 'message' => 'Failed to update password']);

