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

function normalizePhone($phone) {
    // Remove all non-digit characters
    $phone = preg_replace('/\D/', '', $phone);
    
    // Remove leading 88 or +88
    if (strpos($phone, '88') === 0) {
        $phone = substr($phone, 2);
    }

    // Ensure it starts with 0
    if ($phone[0] !== '0') {
        $phone = '0' . $phone;
    }

    return $phone;
}

if (!isset($_GET['phone']) || empty(trim($_GET['phone']))) {
    echo json_encode(['error' => 'Phone number is required']);
    exit;
}

$inputPhone = normalizePhone(trim($_GET['phone']));

$jsonPath = 'users.json';

if (!file_exists($jsonPath)) {
    echo json_encode(['error' => 'User data not found']);
    exit;
}

$data = json_decode(file_get_contents($jsonPath), true);

if (!isset($data['users']) || !is_array($data['users'])) {
    echo json_encode(['error' => 'Invalid user data']);
    exit;
}

foreach ($data['users'] as $user) {
    if (isset($user['phone'])) {
        $storedPhone = normalizePhone($user['phone']);
        if ($storedPhone === $inputPhone) {
            echo json_encode($user);
            exit;
        }
    }
}

echo json_encode(['error' => 'User not found']);
