<?php
// Configuration
$apiBase = "https://apiv4.ordering.co/v400/en/tikram/users";
$apiKey = "QOVNog8sFPkN7tZQ1Vo501_TfygtyTdbh_jDjHXKvZeKkOyo7xBcVqdf3gz8TaI6";
$inputData = json_decode(file_get_contents('php://input'), true);
$email = $inputData['email'] ?? null;
$newPassword = $inputData['password'] ?? null;

if (empty($email) || empty($newPassword)) {
    echo json_encode(['error' => true, 'message' => 'Email and password are required']);
    exit;
}

// Step 1: Find user by email
$limit = 50;
$offset = 0;
$userId = null;
$maxLoops = 50;

do {
    $query = http_build_query([
        'limit' => $limit,
        'offset' => $offset
    ]);

    $url = "$apiBase?$query";

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "accept: application/json",
        "x-api-key: $apiKey"
    ]);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo json_encode(['error' => true, 'message' => 'cURL error: ' . curl_error($ch)]);
        curl_close($ch);
        exit;
    }
    curl_close($ch);

    $data = json_decode($response, true);

    if (!isset($data['result']) || !is_array($data['result'])) {
        echo json_encode(['error' => true, 'message' => 'Invalid API response']);
        exit;
    }

    foreach ($data['result'] as $user) {
        if (isset($user['email']) && strtolower($user['email']) === strtolower($email)) {
            $userId = $user['id'];
            break 2;
        }
    }

    $pagination = $data['pagination'] ?? [];
    $total = $pagination['total'] ?? count($data['result']);
    $offset += $limit;

    if ($offset >= $total) break;
    $maxLoops--;
} while (!$userId && $maxLoops > 0);

if (!$userId) {
    echo json_encode(['error' => true, 'message' => 'User not found']);
    exit;
}

// Step 2: Update user password
$updateUrl = "$apiBase/$userId";

$payload = json_encode([
    "password" => $newPassword,
    "enabled" => true
]);

$ch = curl_init($updateUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "accept: application/json",
    "content-type: application/json",
    "x-api-key: $apiKey"
]);

$updateResponse = curl_exec($ch);
curl_close($ch);

$updateData = json_decode($updateResponse, true);

// Step 3: Return final response
if (isset($updateData['result'])) {
    echo json_encode([
        'error' => false,
        'message' => 'Password updated successfully',
        'user_id' => $userId,
        'email' => $email
    ]);
} else {
    echo json_encode([
        'error' => true,
        'message' => 'Failed to update password',
        'response' => $updateData
    ]);
}
?>
