<?php
// login_user.php - Benutzeranmeldung
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);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    if (empty($input['email'])) {
        throw new Exception('Email is required');
    }
    
    // Prüfen ob es sich um Apple Sign In handelt
    if (!empty($input['apple_user_id']) && !empty($input['apple_identity_token'])) {
        // Apple Sign In Login
        $stmt = $pdo->prepare("SELECT * FROM users WHERE apple_user_id = ? AND is_active = 1");
        $stmt->execute([$input['apple_user_id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            // Neuer Apple-Benutzer - automatische Registrierung
            $auth_token = bin2hex(random_bytes(32));
            $token_expires = date('Y-m-d H:i:s', strtotime('+30 days'));
            
            $sql = "INSERT INTO users (
                first_name, last_name, email, phone_number, license_plate,
                preferred_dealership_id, is_leasing_vehicle, is_contract_vehicle,
                apple_user_id, auth_token, token_expires_at, email_verified
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $pdo->prepare($sql);
            $result = $stmt->execute([
                $input['email'] ?? 'Apple',
                'User',
                $input['email'],
                '', // Leer für Apple-Benutzer
                '', // Leer für Apple-Benutzer
                null,
                false,
                false,
                $input['apple_user_id'],
                $auth_token,
                $token_expires,
                true
            ]);
            
            if ($result) {
                $user_id = $pdo->lastInsertId();
                $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $user = $stmt->fetch(PDO::FETCH_ASSOC);
            }
        } else {
            // Bestehender Apple-Benutzer - Token aktualisieren
            $auth_token = bin2hex(random_bytes(32));
            $token_expires = date('Y-m-d H:i:s', strtotime('+30 days'));
            
            $stmt = $pdo->prepare("UPDATE users SET auth_token = ?, token_expires_at = ? WHERE id = ?");
            $stmt->execute([$auth_token, $token_expires, $user['id']]);
        }
        
    } else {
        // Normale E-Mail/Passwort-Anmeldung
        if (empty($input['password'])) {
            throw new Exception('Password is required for email login');
        }
        
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND is_active = 1");
        $stmt->execute([$input['email']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            throw new Exception('Invalid email or password');
        }
        
        if (!$user['password_hash'] || !password_verify($input['password'], $user['password_hash'])) {
            throw new Exception('Invalid email or password');
        }
        
        // Token aktualisieren
        $auth_token = bin2hex(random_bytes(32));
        $token_expires = date('Y-m-d H:i:s', strtotime('+30 days'));
        
        $stmt = $pdo->prepare("UPDATE users SET auth_token = ?, token_expires_at = ? WHERE id = ?");
        $stmt->execute([$auth_token, $token_expires, $user['id']]);
    }
    
    if ($user) {
        // Passwort-Hash aus Antwort entfernen
        unset($user['password_hash']);
        
        echo json_encode([
            'success' => true,
            'user' => $user,
            'token' => $auth_token,
            'message' => 'Login successful'
        ]);
    } else {
        throw new Exception('Login failed');
    }
    
} catch (Exception $e) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
