<?php

header('Content-Type: application/json');

if (session_status() === PHP_SESSION_NONE) session_start();

require_once '../config.php';



if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    echo json_encode(['success' => false, 'message' => 'Invalid request']);

    exit;

}



$otp         = trim($_POST['otp'] ?? '');

$new_password = $_POST['new_password'] ?? '';

$confirm      = $_POST['confirm_password'] ?? '';

 

if (empty($otp) || empty($new_password)) {

    echo json_encode(['success' => false, 'message' => 'OTP and new password are required']);

    exit;

}



if (strlen($new_password) < 6) {

    echo json_encode(['success' => false, 'message' => 'Password must be at least 6 characters']);

    exit;

}



if ($new_password !== $confirm) {

    echo json_encode(['success' => false, 'message' => 'Passwords do not match']);

    exit;

}



$reset = $_SESSION['pwd_reset'] ?? null;



if (!$reset) {

    echo json_encode(['success' => false, 'message' => 'Session expired. Please request a new OTP.']);

    exit;

}



if (time() > $reset['expires']) {

    unset($_SESSION['pwd_reset']);

    echo json_encode(['success' => false, 'message' => 'OTP has expired. Please request a new one.']);

    exit;

}



if (!password_verify($otp, $reset['otp'])) {

    echo json_encode(['success' => false, 'message' => 'Incorrect OTP. Please check and try again.']);

    exit;

}



try {

    $conn = getDBConnection();

    $hash = password_hash($new_password, PASSWORD_BCRYPT);

    $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");

    $stmt->bind_param('si', $hash, $reset['user_id']);

    $stmt->execute();

    $stmt->close();



    logActivity($conn, $reset['user_id'], 'Password Reset', 'Password reset via OTP');



    unset($_SESSION['pwd_reset']);



    echo json_encode(['success' => true, 'message' => 'Password updated successfully. You can now log in.']);



} catch (Exception $e) {

    error_log('verify_reset_otp: ' . $e->getMessage());

    echo json_encode(['success' => false, 'message' => 'An error occurred. Please try again.']);

}

