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

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

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

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

// Basic regex check
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['valid' => false, 'message' => 'Invalid email format']);
    exit;
}

try {
    // Check users table
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $count = $stmt->fetchColumn();

    if ($count > 0) {
        echo json_encode(['valid' => false, 'is_unique' => false, 'message' => 'Email already exists']);
    } else {
        echo json_encode(['valid' => true, 'is_unique' => true, 'message' => 'Email available']);
    }
} catch (Exception $e) {
    echo json_encode(['valid' => false, 'message' => 'Error checking email']);
}
?>