<?php
/**
 * Admin User Management API
 * Verwaltung von Benutzerfreischaltungen und Rechnungsprüfung
 */

session_start();
require_once '../config/database.php';

// Nur für eingeloggte Admins
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Nicht autorisiert']);
    exit;
}

$db = new Database();
$conn = $db->getConnection();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

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

try {
    switch ($method) {
        case 'GET':
            handleGetRequest($action, $conn);
            break;
        case 'POST':
            handlePostRequest($action, $conn);
            break;
        case 'PUT':
            handlePutRequest($action, $conn);
            break;
        default:
            throw new Exception('Methode nicht unterstützt');
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

function handleGetRequest($action, $conn) {
    switch ($action) {
        case 'pending_users':
            getPendingUsers($conn);
            break;
        case 'user_details':
            getUserDetails($conn);
            break;
        case 'verification_documents':
            getVerificationDocuments($conn);
            break;
        case 'notifications':
            getNotifications($conn);
            break;
        default:
            throw new Exception('Unbekannte Aktion');
    }
}

function handlePostRequest($action, $conn) {
    switch ($action) {
        case 'approve_user':
            approveUser($conn);
            break;
        case 'reject_user':
            rejectUser($conn);
            break;
        case 'upload_document':
            uploadVerificationDocument($conn);
            break;
        default:
            throw new Exception('Unbekannte Aktion');
    }
}

function handlePutRequest($action, $conn) {
    switch ($action) {
        case 'update_user_status':
            updateUserStatus($conn);
            break;
        default:
            throw new Exception('Unbekannte Aktion');
    }
}

/**
 * Alle ausstehenden Benutzer abrufen
 */
function getPendingUsers($conn) {
    $stmt = $conn->prepare("
        SELECT 
            u.id, u.first_name, u.last_name, u.email, u.phone_number, 
            u.license_plate, u.status, u.created_at,
            a.name as dealership_name,
            COUNT(vd.id) as document_count,
            MAX(vd.upload_date) as last_document_upload
        FROM users u
        LEFT JOIN autohaus a ON u.preferred_dealership_id = a.id
        LEFT JOIN verification_documents vd ON u.id = vd.user_id
        WHERE u.status IN ('pending', 'rejected')
        GROUP BY u.id
        ORDER BY u.created_at DESC
    ");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'users' => $users]);
}

/**
 * Detaillierte Benutzerinformationen abrufen
 */
function getUserDetails($conn) {
    $user_id = $_GET['user_id'] ?? null;
    if (!$user_id) {
        throw new Exception('Benutzer-ID erforderlich');
    }
    
    // Benutzerdaten
    $stmt = $conn->prepare("
        SELECT 
            u.*, a.name as dealership_name,
            au.username as approved_by_name,
            ru.username as rejected_by_name
        FROM users u
        LEFT JOIN autohaus a ON u.preferred_dealership_id = a.id
        LEFT JOIN admin_users au ON u.approved_by = au.id
        LEFT JOIN admin_users ru ON u.rejected_by = ru.id
        WHERE u.id = ?
    ");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        throw new Exception('Benutzer nicht gefunden');
    }
    
    // Verifikationsdokumente
    $stmt = $conn->prepare("
        SELECT vd.*, au.username as reviewed_by_name
        FROM verification_documents vd
        LEFT JOIN admin_users au ON vd.reviewed_by = au.id
        WHERE vd.user_id = ?
        ORDER BY vd.upload_date DESC
    ");
    $stmt->execute([$user_id]);
    $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Benachrichtigungen
    $stmt = $conn->prepare("
        SELECT * FROM user_notifications 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 10
    ");
    $stmt->execute([$user_id]);
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true, 
        'user' => $user,
        'documents' => $documents,
        'notifications' => $notifications
    ]);
}

/**
 * Verifikationsdokumente abrufen
 */
function getVerificationDocuments($conn) {
    $user_id = $_GET['user_id'] ?? null;
    if (!$user_id) {
        throw new Exception('Benutzer-ID erforderlich');
    }
    
    $stmt = $conn->prepare("
        SELECT vd.*, au.username as reviewed_by_name
        FROM verification_documents vd
        LEFT JOIN admin_users au ON vd.reviewed_by = au.id
        WHERE vd.user_id = ?
        ORDER BY vd.upload_date DESC
    ");
    $stmt->execute([$user_id]);
    $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'documents' => $documents]);
}

/**
 * Benutzer freischalten
 */
function approveUser($conn) {
    $input = json_decode(file_get_contents('php://input'), true);
    $user_id = $input['user_id'] ?? null;
    $admin_notes = $input['admin_notes'] ?? '';
    
    if (!$user_id) {
        throw new Exception('Benutzer-ID erforderlich');
    }
    
    $admin_id = $_SESSION['admin_user_id'];
    
    $conn->beginTransaction();
    
    try {
        // Benutzer freischalten
        $stmt = $conn->prepare("
            UPDATE users 
            SET status = 'approved', 
                approved_by = ?, 
                approved_at = NOW(),
                admin_notes = ?,
                rejected_by = NULL,
                rejected_at = NULL,
                rejection_reason = NULL
            WHERE id = ?
        ");
        $stmt->execute([$admin_id, $admin_notes, $user_id]);
        
        // Benachrichtigung erstellen
        $stmt = $conn->prepare("
            INSERT INTO user_notifications (user_id, type, title, message)
            VALUES (?, 'account_approved', 'Account freigeschaltet', 'Ihr Account wurde erfolgreich freigeschaltet. Sie können sich jetzt anmelden.')
        ");
        $stmt->execute([$user_id]);
        
        $conn->commit();
        
        echo json_encode(['success' => true, 'message' => 'Benutzer erfolgreich freigeschaltet']);
        
    } catch (Exception $e) {
        $conn->rollBack();
        throw $e;
    }
}

/**
 * Benutzer ablehnen
 */
function rejectUser($conn) {
    $input = json_decode(file_get_contents('php://input'), true);
    $user_id = $input['user_id'] ?? null;
    $rejection_reason = $input['rejection_reason'] ?? '';
    $admin_notes = $input['admin_notes'] ?? '';
    
    if (!$user_id) {
        throw new Exception('Benutzer-ID erforderlich');
    }
    
    if (empty($rejection_reason)) {
        throw new Exception('Ablehnungsgrund erforderlich');
    }
    
    $admin_id = $_SESSION['admin_user_id'];
    
    $conn->beginTransaction();
    
    try {
        // Benutzer ablehnen
        $stmt = $conn->prepare("
            UPDATE users 
            SET status = 'rejected', 
                rejected_by = ?, 
                rejected_at = NOW(),
                rejection_reason = ?,
                admin_notes = ?,
                approved_by = NULL,
                approved_at = NULL
            WHERE id = ?
        ");
        $stmt->execute([$admin_id, $rejection_reason, $admin_notes, $user_id]);
        
        // Benachrichtigung erstellen
        $stmt = $conn->prepare("
            INSERT INTO user_notifications (user_id, type, title, message)
            VALUES (?, 'account_rejected', 'Account abgelehnt', ?)
        ");
        $stmt->execute([$user_id, "Ihr Account wurde abgelehnt. Grund: " . $rejection_reason]);
        
        $conn->commit();
        
        echo json_encode(['success' => true, 'message' => 'Benutzer abgelehnt']);
        
    } catch (Exception $e) {
        $conn->rollBack();
        throw $e;
    }
}

/**
 * Verifikationsdokument hochladen
 */
function uploadVerificationDocument($conn) {
    $user_id = $_POST['user_id'] ?? null;
    $document_type = $_POST['document_type'] ?? 'invoice';
    
    if (!$user_id) {
        throw new Exception('Benutzer-ID erforderlich');
    }
    
    if (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Keine Datei hochgeladen');
    }
    
    $file = $_FILES['document'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
    $max_size = 5 * 1024 * 1024; // 5MB
    
    if (!in_array($file['type'], $allowed_types)) {
        throw new Exception('Dateityp nicht erlaubt. Nur JPG, PNG, GIF und PDF erlaubt.');
    }
    
    if ($file['size'] > $max_size) {
        throw new Exception('Datei zu groß. Maximum 5MB erlaubt.');
    }
    
    // Upload-Verzeichnis erstellen
    $upload_dir = '../uploads/verification_documents/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    // Eindeutigen Dateinamen generieren
    $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $file_name = 'doc_' . $user_id . '_' . time() . '_' . uniqid() . '.' . $file_extension;
    $file_path = $upload_dir . $file_name;
    
    if (!move_uploaded_file($file['tmp_name'], $file_path)) {
        throw new Exception('Fehler beim Hochladen der Datei');
    }
    
    // In Datenbank speichern
    $stmt = $conn->prepare("
        INSERT INTO verification_documents 
        (user_id, document_type, file_name, file_path, file_size, mime_type)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $user_id,
        $document_type,
        $file['name'],
        $file_path,
        $file['size'],
        $file['type']
    ]);
    
    // Benachrichtigung erstellen
    $stmt = $conn->prepare("
        INSERT INTO user_notifications (user_id, type, title, message)
        VALUES (?, 'document_uploaded', 'Dokument hochgeladen', 'Ihr Verifikationsdokument wurde erfolgreich hochgeladen und wird geprüft.')
    ");
    $stmt->execute([$user_id]);
    
    echo json_encode(['success' => true, 'message' => 'Dokument erfolgreich hochgeladen']);
}

/**
 * Benachrichtigungen abrufen
 */
function getNotifications($conn) {
    $user_id = $_GET['user_id'] ?? null;
    if (!$user_id) {
        throw new Exception('Benutzer-ID erforderlich');
    }
    
    $stmt = $conn->prepare("
        SELECT * FROM user_notifications 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 20
    ");
    $stmt->execute([$user_id]);
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'notifications' => $notifications]);
}

/**
 * Benutzerstatus aktualisieren
 */
function updateUserStatus($conn) {
    $input = json_decode(file_get_contents('php://input'), true);
    $user_id = $input['user_id'] ?? null;
    $status = $input['status'] ?? null;
    
    if (!$user_id || !$status) {
        throw new Exception('Benutzer-ID und Status erforderlich');
    }
    
    $allowed_statuses = ['pending', 'approved', 'rejected', 'suspended'];
    if (!in_array($status, $allowed_statuses)) {
        throw new Exception('Ungültiger Status');
    }
    
    $stmt = $conn->prepare("UPDATE users SET status = ? WHERE id = ?");
    $stmt->execute([$status, $user_id]);
    
    echo json_encode(['success' => true, 'message' => 'Status aktualisiert']);
}
?>
