<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';

apply_cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['email', 'otp', 'new_password']);

$email = strtolower(clean_str($input['email']));
$otp = clean_str($input['otp']);
$newPassword = (string) $input['new_password'];

if (strlen($newPassword) < 8) {
    send_error('Password must be at least 8 characters.', 422);
}

$pdo = getDbConnection();

// Dev-mode bypass (see config/constants.php) - same fixed code as verify_otp.php,
// skips the password_resets row lookup entirely and goes straight to the update.
if (DEV_MODE_OTP_ENABLED && $otp === DEV_MODE_OTP_CODE) {
    $hash = password_hash($newPassword, PASSWORD_DEFAULT);
    $upd = $pdo->prepare("UPDATE users SET password_hash = :hash WHERE email = :email AND role = 'USER'");
    $upd->execute([':hash' => $hash, ':email' => $email]);
    send_success(null, 'Password reset successfully (dev mode). Please log in with your new password.');
}

$stmt = $pdo->prepare(
    'SELECT id, attempts FROM password_resets
     WHERE email = :email AND otp = :otp AND is_used = 0 AND expires_at > NOW()
     ORDER BY id DESC LIMIT 1'
);
$stmt->execute([':email' => $email, ':otp' => $otp]);
$row = $stmt->fetch();

if (!$row) {
    // Track a failed attempt against the most recent OTP row for this email,
    // if one exists, to enforce the attempt cap.
    $latest = $pdo->prepare('SELECT id, attempts FROM password_resets WHERE email = :email ORDER BY id DESC LIMIT 1');
    $latest->execute([':email' => $email]);
    $latestRow = $latest->fetch();
    if ($latestRow) {
        $inc = $pdo->prepare('UPDATE password_resets SET attempts = attempts + 1 WHERE id = :id');
        $inc->execute([':id' => $latestRow['id']]);
    }
    send_error('Invalid or expired code.', 401);
}

$pdo->beginTransaction();
try {
    $mark = $pdo->prepare('UPDATE password_resets SET is_used = 1 WHERE id = :id');
    $mark->execute([':id' => $row['id']]);

    $hash = password_hash($newPassword, PASSWORD_DEFAULT);
    $upd = $pdo->prepare("UPDATE users SET password_hash = :hash WHERE email = :email AND role = 'USER'");
    $upd->execute([':hash' => $hash, ':email' => $email]);

    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    send_error('Failed to reset password.', 500);
}

send_success(null, 'Password reset successfully. Please log in with your new password.');
