<?php
/**
 * API-Endpunkt für Admin-Aktionen auf Verifikationsdokumenten
 * Genehmigen/Ablehnen von Dokumenten
 */

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

// Check if user is logged in as admin
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Nicht autorisiert']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? null;
$document_id = $input['document_id'] ?? null;

if (!$action || !$document_id) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Aktion und Dokument-ID erforderlich']);
    exit;
}

$admin_id = $_SESSION['admin_user_id'];

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    $conn->beginTransaction();
    
    if ($action === 'approve') {
        $notes = $input['notes'] ?? 'Dokument genehmigt';
        
        // Approve document
        $stmt = $conn->prepare("
            UPDATE verification_documents 
            SET status = 'approved',
                reviewed_by = ?,
                reviewed_at = NOW(),
                admin_notes = ?
            WHERE id = ?
        ");
        $stmt->execute([$admin_id, $notes, $document_id]);
        
        // Get user ID for notification
        $stmt = $conn->prepare("SELECT user_id FROM verification_documents WHERE id = ?");
        $stmt->execute([$document_id]);
        $doc = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($doc) {
            // Prüfe ob user existiert und logge Details
            $stmt = $conn->prepare("SELECT id, first_name, last_name FROM users WHERE id = ?");
            $stmt->execute([$doc['user_id']]);
            $userExists = $stmt->fetch(PDO::FETCH_ASSOC);
            
            error_log("Document user_id: " . $doc['user_id']);
            error_log("User exists: " . ($userExists ? 'YES' : 'NO'));
            if ($userExists) {
                error_log("User details: " . json_encode($userExists));
            }
            
            if ($userExists) {
                // Create notification for user (optional) - DEAKTIVIERT BEI PROBLEMEN
                try {
                    // Prüfe ob user_notifications Tabelle existiert
                    $stmt = $conn->query("SHOW TABLES LIKE 'user_notifications'");
                    $tableExists = $stmt->fetch();
                    
                    if ($tableExists) {
                        error_log("Creating notification for user_id: " . $doc['user_id']);
                        
                        // Zusätzliche Prüfung: Stelle sicher, dass user_id wirklich existiert
                        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM users WHERE id = ?");
                        $stmt->execute([$doc['user_id']]);
                        $userCount = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($userCount['count'] > 0) {
                            $stmt = $conn->prepare("
                                INSERT INTO user_notifications (user_id, type, title, message)
                                VALUES (?, 'document_approved', 'Dokument genehmigt', 'Ihr Verifikationsdokument wurde genehmigt.')
                            ");
                            $stmt->execute([$doc['user_id']]);
                            error_log("Notification created successfully");
                        } else {
                            error_log("User count check failed for user_id: " . $doc['user_id']);
                        }
                    } else {
                        error_log("user_notifications table does not exist");
                    }
                } catch (Exception $e) {
                    error_log('Error creating notification: ' . $e->getMessage());
                    error_log('Stack trace: ' . $e->getTraceAsString());
                    // Fortfahren ohne Benachrichtigung
                }
            } else {
                error_log('User not found for notification: ' . $doc['user_id']);
            }
        
        // Update user status if all documents are approved
        $stmt = $conn->prepare("
            SELECT COUNT(*) as total_docs,
                   COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_docs
            FROM verification_documents 
            WHERE user_id = ? AND status IN ('approved', 'rejected')
        ");
        $stmt->execute([$doc['user_id']]);
        $docStats = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($docStats['total_docs'] > 0 && $docStats['approved_docs'] == $docStats['total_docs']) {
            // All documents approved, update user status
            $stmt = $conn->prepare("
                UPDATE users 
                SET status = 'approved', 
                    approved_by = ?, 
                    approved_at = NOW(),
                    admin_notes = CONCAT(IFNULL(admin_notes, ''), '\nAlle Dokumente genehmigt: ', NOW())
                WHERE id = ?
            ");
            $stmt->execute([$admin_id, $doc['user_id']]);
        }
        }
        
    } elseif ($action === 'reject') {
        $reason = $input['reason'] ?? 'Kein Grund angegeben';
        
        // Reject document
        $stmt = $conn->prepare("
            UPDATE verification_documents 
            SET status = 'rejected',
                reviewed_by = ?,
                reviewed_at = NOW(),
                admin_notes = ?
            WHERE id = ?
        ");
        $stmt->execute([$admin_id, $reason, $document_id]);
        
        // Get user ID for notification
        $stmt = $conn->prepare("SELECT user_id FROM verification_documents WHERE id = ?");
        $stmt->execute([$document_id]);
        $doc = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($doc) {
            // Prüfe ob user existiert und logge Details
            $stmt = $conn->prepare("SELECT id, first_name, last_name FROM users WHERE id = ?");
            $stmt->execute([$doc['user_id']]);
            $userExists = $stmt->fetch(PDO::FETCH_ASSOC);
            
            error_log("Document user_id: " . $doc['user_id']);
            error_log("User exists: " . ($userExists ? 'YES' : 'NO'));
            if ($userExists) {
                error_log("User details: " . json_encode($userExists));
            }
            
            if ($userExists) {
                // Create notification for user (optional) - DEAKTIVIERT BEI PROBLEMEN
                try {
                    // Prüfe ob user_notifications Tabelle existiert
                    $stmt = $conn->query("SHOW TABLES LIKE 'user_notifications'");
                    $tableExists = $stmt->fetch();
                    
                    if ($tableExists) {
                        error_log("Creating notification for user_id: " . $doc['user_id']);
                        
                        // Zusätzliche Prüfung: Stelle sicher, dass user_id wirklich existiert
                        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM users WHERE id = ?");
                        $stmt->execute([$doc['user_id']]);
                        $userCount = $stmt->fetch(PDO::FETCH_ASSOC);
                        
                        if ($userCount['count'] > 0) {
                            $stmt = $conn->prepare("
                                INSERT INTO user_notifications (user_id, type, title, message)
                                VALUES (?, 'document_rejected', 'Dokument abgelehnt', ?)
                            ");
                            $stmt->execute([$doc['user_id'], "Ihr Verifikationsdokument wurde abgelehnt. Grund: " . $reason]);
                            error_log("Notification created successfully");
                        } else {
                            error_log("User count check failed for user_id: " . $doc['user_id']);
                        }
                    } else {
                        error_log("user_notifications table does not exist");
                    }
                } catch (Exception $e) {
                    error_log('Error creating notification: ' . $e->getMessage());
                    error_log('Stack trace: ' . $e->getTraceAsString());
                    // Fortfahren ohne Benachrichtigung
                }
            } else {
                error_log('User not found for notification: ' . $doc['user_id']);
            }
        
        // Update user status to pending if document is rejected
        $stmt = $conn->prepare("
            UPDATE users 
            SET status = 'pending',
                admin_notes = CONCAT(IFNULL(admin_notes, ''), '\nDokument abgelehnt: ', NOW(), ' - ', ?)
            WHERE id = ?
        ");
        $stmt->execute([$reason, $doc['user_id']]);
        }
        
    } else {
        throw new Exception('Unbekannte Aktion');
    }
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Aktion erfolgreich ausgeführt'
    ]);
    
} catch (Exception $e) {
    $conn->rollBack();
    error_log('Error processing document action: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Fehler beim Verarbeiten der Aktion: ' . $e->getMessage()
    ]);
}
?>
