<?php
session_start();
require_once '../dashboard/includes/config.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Invalid request method']);
    exit;
}

if (!isset($_POST['email']) || empty(trim($_POST['email']))) {
    echo json_encode(['error' => 'Email is required']);
    exit;
}

$email = trim($_POST['email']);

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['error' => 'Invalid email format']);
    exit;
}

// Check if email already exists in database
$email = mysqli_real_escape_string($conn, $email);
$check_query = "SELECT id FROM users WHERE email = '$email' LIMIT 1";
$result = mysqli_query($conn, $check_query);

if ($result && mysqli_num_rows($result) > 0) {
    echo json_encode(['exists' => true, 'message' => 'Email already registered']);
} else {
    echo json_encode(['exists' => false, 'message' => 'Email available']);
}
?>