<?php
require_once __DIR__ . '/../includes/db.php';
header('Content-Type: application/json');

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

$token = trim($_POST['token'] ?? '');
$password = trim($_POST['password'] ?? '');
$confirm = trim($_POST['confirm'] ?? '');

if (empty($token) || empty($password) || empty($confirm)) {
    echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
    exit;
}

if ($password !== $confirm) {
    echo json_encode(['status' => 'error', 'message' => 'Passwords do not match.']);
    exit;
}

// ✅ Check token validity
$stmt = $pdo->prepare("SELECT id, reset_expires FROM users WHERE reset_token = ?");
$stmt->execute([$token]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid or expired reset token.']);
    exit;
}

if (strtotime($user['reset_expires']) < time()) {
    echo json_encode(['status' => 'error', 'message' => 'Reset token has expired.']);
    exit;
}

// ✅ Update password
$hashed = password_hash($password, PASSWORD_BCRYPT);
$stmt = $pdo->prepare("UPDATE users SET password = ?, pshow = ?, reset_token = NULL, reset_expires = NULL WHERE id = ?");
$stmt->execute([$hashed, $confirm, $user['id']]);

echo json_encode(['status' => 'success', 'message' => 'Password has been reset successfully. You can now login.']);
?>
