<?php
/**
 * Krempl PostgreSQL Search Test Interface
 * Search for devices and show matching ersatzteile
 */

require_once __DIR__ . '/core/postgres/KremplDB.php';

$search_term = isset($_GET['q']) ? trim($_GET['q']) : '';
$results = [];
$search_time = 0;
$error_message = '';
$show_shop_items = isset($_GET['shop_items']) && $_GET['shop_items'] === '1';

try {
    // Connect to both PostgreSQL and MySQL if shop items are requested
    $db = new KremplDB($show_shop_items);

    if ($search_term !== '') {
        $start_time = microtime(true);
        $results = $db->searchGeraete($search_term, 20);

        // If shop items requested, replace ersatzteile with actual shop items
        if ($show_shop_items) {
            foreach ($results as &$device) {
                $device['shop_items'] = $db->getAvailableItemsForGeraet($device['geraet_id'], 200);
            }
            unset($device);
        }

        $search_time = (microtime(true) - $start_time) * 1000; // Convert to milliseconds
    }
} catch (Exception $e) {
    $error_message = $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Krempl PostgreSQL Search Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        h1 {
            color: #333;
            margin-bottom: 20px;
        }

        .search-box {
            margin-bottom: 30px;
        }

        .search-input {
            width: 100%;
            padding: 12px 15px;
            font-size: 16px;
            border: 2px solid #ddd;
            border-radius: 4px;
            transition: border-color 0.3s;
        }

        .search-input:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .search-btn {
            padding: 10px 20px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
            white-space: nowrap;
        }

        .search-btn:hover {
            background: #45a049;
        }

        #shopItemsToggle {
            cursor: pointer;
            width: 18px;
            height: 18px;
        }

        .search-info {
            color: #666;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .device-card {
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            margin-bottom: 20px;
            background: #fafafa;
            overflow: hidden;
        }

        .device-card.collapsed .ersatzteile-section {
            display: none;
        }

        .device-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            padding: 15px;
            margin-bottom: 0;
            border-bottom: 2px solid #e0e0e0;
        }

        .score-badge {
            cursor: pointer;
            transition: all 0.2s;
            user-select: none;
        }

        .score-badge:hover {
            opacity: 0.9;
            transform: scale(1.02);
        }

        .toggle-arrow {
            display: inline-block;
            margin-left: 8px;
            transition: transform 0.3s;
            font-size: 10px;
        }

        .device-card.collapsed .toggle-arrow {
            transform: rotate(-90deg);
        }

        .device-info {
            flex: 1;
        }

        .device-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .device-title a {
            color: #333;
            text-decoration: none;
            transition: color 0.2s;
        }

        .device-title a:hover {
            color: #4CAF50;
            text-decoration: underline;
        }

        .device-details {
            color: #666;
            font-size: 14px;
        }

        .device-details span {
            display: inline-block;
            margin-right: 15px;
        }

        .score-badge {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 14px;
        }

        .score-100 { background: #4CAF50; color: white; }
        .score-95 { background: #66BB6A; color: white; }
        .score-90 { background: #81C784; color: white; }
        .score-80 { background: #FFC107; color: white; }
        .score-75 { background: #FFD54F; color: #333; }
        .score-60 { background: #FFE082; color: #333; }
        .score-default { background: #BDBDBD; color: white; }

        .ersatzteile-section {
            padding: 15px;
        }

        .ersatzteile-title {
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
            margin-top: 10px;
            font-size: 14px;
        }

        .ersatzteile-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 4px;
            overflow: hidden;
        }

        .ersatzteile-table th {
            background: #f0f0f0;
            padding: 8px;
            text-align: left;
            font-size: 13px;
            font-weight: 600;
            color: #555;
        }

        .ersatzteile-table td {
            padding: 8px;
            border-top: 1px solid #e0e0e0;
            font-size: 13px;
        }

        .ersatzteile-table tr:hover {
            background: #f9f9f9;
        }

        .navision-id {
            font-weight: bold;
            color: #1976D2;
        }

        .no-results {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .match-type {
            display: inline-block;
            font-size: 11px;
            padding: 2px 6px;
            background: #e0e0e0;
            border-radius: 3px;
            color: #666;
            margin-left: 8px;
        }

        .error-message {
            background: #ffebee;
            border: 1px solid #ef5350;
            color: #c62828;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }

        .error-message strong {
            display: block;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Krempl PostgreSQL Search Test</h1>

        <div class="search-box">
            <form method="GET" action="" id="searchForm">
                <input
                    type="text"
                    name="q"
                    class="search-input"
                    placeholder="Gerätesuche (z.B. AWB 921 PH, ZCS 2100B, 2100B)"
                    value="<?php echo htmlspecialchars($search_term); ?>"
                    autofocus
                />
                <div style="margin-top: 10px; display: flex; align-items: center; gap: 15px;">
                    <button type="submit" class="search-btn">Suchen</button>
                    <label style="font-size: 14px; cursor: pointer; display: flex; align-items: center; gap: 5px;">
                        <input type="checkbox" name="shop_items" value="1" <?php echo $show_shop_items ? 'checked' : ''; ?> id="shopItemsToggle" onchange="document.getElementById('searchForm').submit();">
                        <span>Nur verfügbare Shop-Artikel (MySQL)</span>
                    </label>
                </div>
            </form>
        </div>

        <?php if ($error_message): ?>
            <div class="error-message">
                <strong>Fehler bei der Datenbankverbindung:</strong>
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>

        <?php if ($search_term !== '' && !$error_message): ?>
            <div class="search-info">
                <?php if (count($results) > 0): ?>
                    <strong><?php echo count($results); ?> Geräte</strong> gefunden für "<?php echo htmlspecialchars($search_term); ?>"
                    (<?php echo number_format($search_time, 0); ?> ms)
                <?php else: ?>
                    Keine Ergebnisse für "<?php echo htmlspecialchars($search_term); ?>"
                <?php endif; ?>
            </div>

            <?php foreach ($results as $device): ?>
                <?php
                    $score = (int)$device['score'];
                    $score_class = 'score-default';
                    if ($score >= 100) $score_class = 'score-100';
                    elseif ($score >= 95) $score_class = 'score-95';
                    elseif ($score >= 90) $score_class = 'score-90';
                    elseif ($score >= 80) $score_class = 'score-80';
                    elseif ($score >= 75) $score_class = 'score-75';
                    elseif ($score >= 60) $score_class = 'score-60';
                ?>

                <div class="device-card collapsed" id="device-<?php echo $device['geraet_id']; ?>">
                    <div class="device-header">
                        <div class="device-info">
                            <div class="device-title">
                                <a href="geraet.php?id=<?php echo $device['geraet_id']; ?>&q=<?php echo urlencode($search_term); ?><?php echo $show_shop_items ? '&shop_items=1' : ''; ?>" style="color: #333; text-decoration: none;">
                                    <?php echo htmlspecialchars($device['modell_bezeichnung']); ?>
                                </a>
                                <span class="match-type"><?php echo htmlspecialchars($device['match_type']); ?></span>
                            </div>
                            <div class="device-details">
                                <span><strong>Marke:</strong> <?php echo htmlspecialchars($device['marke']); ?></span>
                                <span><strong>Typ:</strong> <?php echo htmlspecialchars($device['typ']); ?></span>
                                <span><strong>Nr:</strong> <?php echo htmlspecialchars($device['nr']); ?></span>
                                <span><strong>ID:</strong> <?php echo htmlspecialchars($device['geraet_id']); ?></span>
                            </div>
                        </div>
                        <div>
                            <span class="score-badge <?php echo $score_class; ?>" onclick="toggleDevice(<?php echo $device['geraet_id']; ?>)">
                                Score: <?php echo $score; ?>
                                <span class="toggle-arrow">▼</span>
                            </span>
                        </div>
                    </div>

                    <?php if ($show_shop_items && isset($device['shop_items'])): ?>
                        <!-- Show available shop items -->
                        <?php if (count($device['shop_items']) > 0): ?>
                            <div class="ersatzteile-section">
                                <div class="ersatzteile-title">
                                    Verfügbare Shop-Artikel:
                                    <span style="background: #4CAF50; color: white; padding: 3px 10px; border-radius: 12px; font-weight: bold; margin-left: 5px;">
                                        <?php echo count($device['shop_items']); ?> verfügbar
                                    </span>
                                </div>
                                <table class="ersatzteile-table">
                                    <thead>
                                        <tr>
                                            <th>Artikel-Nr</th>
                                            <th>Artikelname</th>
                                            <th>Navision-ID</th>
                                            <th>Lagerbestand</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($device['shop_items'] as $item): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($item['number']); ?></td>
                                                <td><?php echo htmlspecialchars($item['name']); ?></td>
                                                <td class="navision-id"><?php echo htmlspecialchars($item['matched_navision_id']); ?></td>
                                                <td><?php echo (int)$item['inventory']; ?> Stück</td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="ersatzteile-section">
                                <div class="ersatzteile-title" style="color: #999;">
                                    Keine verfügbaren Shop-Artikel gefunden
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <!-- Show all Krempl ersatzteile -->
                        <?php if (count($device['ersatzteile']) > 0): ?>
                            <div class="ersatzteile-section">
                                <div class="ersatzteile-title">
                                    Passende Ersatzteile (Krempl):
                                    <span style="background: #2196F3; color: white; padding: 3px 10px; border-radius: 12px; font-weight: bold; margin-left: 5px;">
                                        <?php echo count($device['ersatzteile']); ?> gesamt
                                    </span>
                                </div>
                                <table class="ersatzteile-table">
                                    <thead>
                                        <tr>
                                            <th>Navision ID</th>
                                            <th>Krempl ID</th>
                                            <th>Originalnummer</th>
                                            <th>Marke</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($device['ersatzteile'] as $ers): ?>
                                            <tr>
                                                <td class="navision-id"><?php echo htmlspecialchars($ers['navision_id']); ?></td>
                                                <td><?php echo htmlspecialchars($ers['krempl_id']); ?></td>
                                                <td><?php echo htmlspecialchars($ers['originalnummer']); ?></td>
                                                <td><?php echo htmlspecialchars($ers['marke']); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="ersatzteile-section">
                                <div class="ersatzteile-title" style="color: #999;">
                                    Keine Ersatzteile gefunden
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>

            <?php if (count($results) === 0): ?>
                <div class="no-results">
                    Keine Geräte gefunden für "<?php echo htmlspecialchars($search_term); ?>"
                </div>
            <?php endif; ?>

        <?php else: ?>
            <div class="no-results">
                Gib einen Suchbegriff ein (z.B. "AWB 921 PH", "ZCS 2100B", "2100B")
            </div>
        <?php endif; ?>
    </div>

    <script>
        function toggleDevice(deviceId) {
            const card = document.getElementById('device-' + deviceId);
            if (card) {
                card.classList.toggle('collapsed');
            }
        }
    </script>
</body>
</html>
