<?php
/**
 * Search User by Email with Auto-Pagination (Updated for actual API response)
 * API Endpoint: GET /api/find-user.php?email=user@example.com
 */


class UserSearchAPI {
    private $apiBaseUrl = 'https://apiv4.ordering.co/v400/en/tikram/users';
    private $apiKey = 'khSS9lf0WfcizXyoL7sCf8Y4-H_iWbIxVNaba7gZngTzf30wobNx-o5PfnGDThG4';
    private $limit = 500;
    private $maxPages = 500; // Prevent infinite loops

    /**
     * Search for user by email across all pages
     */
    public function searchUserByEmail($email) {
        if (empty($email)) {
            return $this->errorResponse('Email parameter is required', 400);
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $this->errorResponse('Invalid email format', 400);
        }

        $offset = 0;
        $currentPage = 1;

        while ($currentPage <= $this->maxPages) {
            try {
                // Fetch users at current page
                $response = $this->fetchUsersFromAPI($offset);

                // Check if API call was successful
                if ($response['error']) {
                    return $this->errorResponse(
                        $response['message'] ?? 'API Error',
                        500
                    );
                }

                $users = $response['result'];
                $pagination = $response['pagination'];

                // Search for user in current batch
                foreach ($users as $user) {
                    if (strcasecmp($user['email'], $email) === 0) {
                        return $this->successResponse($user, $offset, $currentPage, $pagination);
                    }
                }

                // Check if there's a next page
                if ($currentPage >= $pagination['total_pages']) {
                    return $this->errorResponse(
                        'User not found with email: ' . $email,
                        404
                    );
                }

                // Move to next page
                $offset += $this->limit;
                $currentPage++;

            } catch (Exception $e) {
                return $this->errorResponse($e->getMessage(), 500);
            }
        }

        return $this->errorResponse(
            'Search exceeded maximum pages. User not found.',
            404
        );
    }

    /**
     * Fetch users from external API
     */
    private function fetchUsersFromAPI($offset) {
        $url = $this->apiBaseUrl . '?params=email,cellphone,country_phone_code&limit='
               . $this->limit . '&offset=' . $offset;

        $ch = curl_init($url);

        // Set cURL options
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'X-API-Key: ' . $this->apiKey
            ]
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);

        curl_close($ch);

        // Handle cURL errors
        if ($curlError) {
            throw new Exception('cURL Error: ' . $curlError);
        }

        // Handle HTTP errors
        if ($httpCode !== 200) {
            throw new Exception("API returned HTTP $httpCode");
        }

        // Decode JSON response
        $data = json_decode($response, true);

        if (!$data) {
            throw new Exception('Invalid JSON response from API');
        }

        return $data;
    }

    /**
     * Success response
     */
    private function successResponse($user, $offset, $currentPage, $pagination) {
        return [
            'success' => true,
            'status_code' => 200,
            'data' => [
                'user' => $user,
                'pagination' => [
                    'offset' => $offset,
                    'current_page' => $currentPage,
                    'total_pages' => $pagination['total_pages'],
                    'total_users' => $pagination['total'],
                    'page_size' => $pagination['page_size']
                ]
            ]
        ];
    }

    /**
     * Error response
     */
    private function errorResponse($message, $statusCode = 400) {
        http_response_code($statusCode);
        return [
            'success' => false,
            'status_code' => $statusCode,
            'error' => $message,
            'timestamp' => date('Y-m-d H:i:s')
        ];
    }
}

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

$email = $_GET['email'] ?? null;

$searcher = new UserSearchAPI();
$result = $searcher->searchUserByEmail($email);

echo json_encode($result, JSON_PRETTY_PRINT);
?>
