<?php
require_once '../config/cors.php';
require_once '../config/db.php';

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

$phone = $_GET['phone'] ?? '';

if (empty($phone)) {
    echo json_encode(['valid' => false, 'message' => 'Phone required']);
    exit;
}

// Basic PH regex
if (!preg_match('/^(09|\+639)\d{9}$/', $phone)) {
    echo json_encode(['valid' => false, 'message' => 'Invalid PH phone format']);
    exit;
}

try {
    // Check if the number exists in ANY phone-related column
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE 
        phone_number = ? OR 
        viber_number = ? OR 
        telegram_number = ? OR 
        emergency_contact_number = ?");
    $stmt->execute([$phone, $phone, $phone, $phone]);
    $count = $stmt->fetchColumn();

    if ($count > 0) {
        echo json_encode(['valid' => true, 'is_unique' => false, 'message' => 'This number is already registered to another account']);
    } else {
        echo json_encode(['valid' => true, 'is_unique' => true, 'message' => 'Phone available']);
    }
} catch (Exception $e) {
    echo json_encode(['valid' => false, 'message' => 'Database error']);
}
?>