<?php

$baseUrl = "http://localhost/shopnest/php-api-server/api";
$email = "itsabhishek421@gmail.com";
$newPassword = "newpassword123";

function callApi($method, $url, $data = null) {
    echo "Testing $method $url...\n";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    if ($data) {
        $json = json_encode($data);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    }
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    echo "HTTP Code: $httpCode\n";
    echo "Response: $response\n\n";
    return json_decode($response, true);
}

// 1. Forgot Password
$res = callApi('POST', "$baseUrl/auth/forgot-password", ['email' => $email]);
if (!isset($res['data']['token'])) {
    die("FAILED: Forgot password did not return a token.\n");
}
$token = $res['data']['token'];

// 2. Reset Password
$res = callApi('POST', "$baseUrl/auth/reset-password", [
    'token' => $token,
    'new_password' => $newPassword,
    'confirm_password' => $newPassword
]);
if (!($res['success'] ?? false)) {
    die("FAILED: Reset password failed.\n");
}

// 3. Verify Login with new password
$res = callApi('POST', "$baseUrl/auth/login", [
    'email' => $email,
    'password' => $newPassword
]);
if (!($res['success'] ?? false)) {
    die("FAILED: Login with new password failed.\n");
}

echo "SUCCESS: Forgot/Reset password API verified successfully!\n";
