<?php
// check_user_exists.php - Prüft ob User bereits existiert
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

require_once 'config.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $check_type = $input['check_type'] ?? null; // 'email', 'license_plate', 'apple_id'
    $value = $input['value'] ?? null;
    
    if (!$check_type || !$value) {
        throw new Exception('check_type and value are required');
    }
    
    $exists = false;
    $user_data = null;
    
    switch ($check_type) {
        case 'email':
            $stmt = $pdo->prepare("SELECT id, email, status FROM users WHERE email = ?");
            $stmt->execute([$value]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            $exists = $user_data !== false;
            break;
            
        case 'license_plate':
            $stmt = $pdo->prepare("SELECT id, email, license_plate, status FROM users WHERE license_plate = ?");
            $stmt->execute([$value]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            $exists = $user_data !== false;
            break;
            
        case 'apple_id':
            $stmt = $pdo->prepare("SELECT id, email, apple_user_id, status FROM users WHERE apple_user_id = ?");
            $stmt->execute([$value]);
            $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
            $exists = $user_data !== false;
            break;
            
        default:
            throw new Exception('Invalid check_type. Use: email, license_plate, or apple_id');
    }
    
    echo json_encode([
        'success' => true,
        'exists' => $exists,
        'user_data' => $user_data,
        'check_type' => $check_type,
        'value' => $value
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
