<?php
require_once 'config.php';
require_once 'functions.php';

$query = isset($_GET['q']) ? trim($_GET['q']) : '';
$results = [];
$total_results = 0;

if (!empty($query)) {
    $results = globalSearch($query);
    $total_results = count($results['clients']) + count($results['protocols']) + count($results['offers']) + count($results['documents']);
}
?>

<!DOCTYPE html>
<html lang="bg">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Търсене - Протоколи за влагане на материали</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
       body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
        }

     
        .search-container {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }

        .search-form {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
        }

        .search-input {
            flex: 1;
            padding: 1rem;
            border: 2px solid #e1e5e9;
            border-radius: 5px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .search-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 2rem;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: transform 0.2s ease;
        }

        .search-btn:hover {
            transform: translateY(-2px);
        }

        .search-info {
            color: #666;
            font-size: 0.9rem;
        }

        .results-section {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }

        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid #667eea;
            padding-bottom: 0.5rem;
        }

        .results-header h3 {
            color: #667eea;
            margin: 0;
        }

        .results-count {
            background: #667eea;
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .result-item {
            padding: 1rem;
            border: 1px solid #e1e5e9;
            border-radius: 5px;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }

        .result-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transform: translateY(-1px);
        }

        .result-title {
            font-weight: 600;
            color: #333;
            margin-bottom: 0.5rem;
        }

        .result-details {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }

        .result-actions {
            display: flex;
            gap: 0.5rem;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            transition: transform 0.2s ease;
        }

        .btn:hover {
            transform: translateY(-1px);
        }

        .btn-info {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
        }

        .no-results {
            text-align: center;
            color: #666;
            font-style: italic;
            padding: 2rem;
        }

        .highlight {
            background-color: #fff3cd;
            padding: 0.1rem 0.2rem;
            border-radius: 2px;
        }

        @media (max-width: 768px) {
            .nav ul {
                flex-direction: column;
            }
            
            .search-form {
                flex-direction: column;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .results-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }
            
            .result-actions {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
    <div class="container">


<?php
include_once 'header.php';
?>

        <div class="search-container">
            <form method="GET" class="search-form">
                <input type="text" 
                       name="q" 
                       value="<?php echo htmlspecialchars($query); ?>" 
                       placeholder="Търсете по име, телефон, адрес..." 
                       class="search-input"
                       autofocus>
                <button type="submit" class="search-btn">Търси</button>
            </form>
            <div class="search-info">
                Можете да търсите по име на клиент, телефон, адрес, номер на оферта, име на документ и др.
            </div>
        </div>

        <?php if (!empty($query)): ?>
            <div class="results-section">
                <div class="results-header">
                    <h3>Резултати от търсенето</h3>
                    <span class="results-count"><?php echo $total_results; ?> резултата</span>
                </div>

                <?php if ($total_results == 0): ?>
                    <div class="no-results">
                        Няма намерени резултати за "<?php echo htmlspecialchars($query); ?>"
                    </div>
                <?php else: ?>
                    
                    <!-- Clients Results -->
                    <?php if (!empty($results['clients'])): ?>
                        <div class="results-header">
                            <h3>Клиенти</h3>
                            <span class="results-count"><?php echo count($results['clients']); ?></span>
                        </div>
                        <?php foreach ($results['clients'] as $client): ?>
                            <div class="result-item">
                                <div class="result-title"><?php echo htmlspecialchars($client['name']); ?></div>
                                <div class="result-details">
                                    <strong>Адрес:</strong> <?php echo htmlspecialchars($client['address']); ?><br>
                                    <strong>Телефон:</strong> <?php echo htmlspecialchars($client['phone']); ?><br>
                                    <strong>Имейл:</strong> <?php echo htmlspecialchars($client['email']); ?>
                                </div>
                                <div class="result-actions">
                                    <a href="client_dossier.php?id=<?php echo $client['id']; ?>" class="btn btn-info">Досие</a>
                                    <a href="edit_client.php?id=<?php echo $client['id']; ?>" class="btn">Редактирай</a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

                    <!-- Protocols Results -->
                    <?php if (!empty($results['protocols'])): ?>
                        <div class="results-header">
                            <h3>Протоколи</h3>
                            <span class="results-count"><?php echo count($results['protocols']); ?></span>
                        </div>
                        <?php foreach ($results['protocols'] as $protocol): ?>
                            <div class="result-item">
                                <div class="result-title">Протокол #<?php echo $protocol['id']; ?></div>
                                <div class="result-details">
                                    <strong>Възложител:</strong> <?php echo htmlspecialchars($protocol['issuer']); ?><br>
                                    <strong>Изпълнител:</strong> <?php echo htmlspecialchars($protocol['executor']); ?><br>
                                    <strong>Дата:</strong> <?php echo date('d.m.Y', strtotime($protocol['protocol_date'])); ?>
                                </div>
                                <div class="result-actions">
                                    <a href="view_protocol.php?id=<?php echo $protocol['id']; ?>" class="btn">Преглед</a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

                    <!-- Offers Results -->
                    <?php if (!empty($results['offers'])): ?>
                        <div class="results-header">
                            <h3>Оферти</h3>
                            <span class="results-count"><?php echo count($results['offers']); ?></span>
                        </div>
                        <?php foreach ($results['offers'] as $offer): ?>
                            <div class="result-item">
                                <div class="result-title"><?php echo htmlspecialchars($offer['offer_number']); ?></div>
                                <div class="result-details">
                                    <strong>Издател:</strong> <?php echo htmlspecialchars($offer['issuer']); ?><br>
                                    <strong>Получател:</strong> <?php echo htmlspecialchars($offer['recipient']); ?><br>
                                    <strong>Дата:</strong> <?php echo date('d.m.Y', strtotime($offer['offer_date'])); ?><br>
                                    <strong>Сума:</strong> <?php echo number_format($offer['total_amount'], 2); ?> лв.
                                </div>
                                <div class="result-actions">
                                    <a href="view_offer.php?id=<?php echo $offer['id']; ?>" class="btn">Преглед</a>
                                    <a href="edit_offer.php?id=<?php echo $offer['id']; ?>" class="btn">Редактирай</a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

                    <!-- Documents Results -->
                    <?php if (!empty($results['documents'])): ?>
                        <div class="results-header">
                            <h3>Документи</h3>
                            <span class="results-count"><?php echo count($results['documents']); ?></span>
                        </div>
                        <?php foreach ($results['documents'] as $document): ?>
                            <div class="result-item">
                                <div class="result-title"><?php echo htmlspecialchars($document['document_name']); ?></div>
                                <div class="result-details">
                                    <strong>Клиент:</strong> <?php echo htmlspecialchars($document['client_name']); ?><br>
                                    <strong>Тип:</strong> <?php echo htmlspecialchars($document['document_type']); ?><br>
                                    <strong>Качен на:</strong> <?php echo date('d.m.Y H:i', strtotime($document['uploaded_at'])); ?>
                                </div>
                                <div class="result-actions">
                                    <a href="client_dossier.php?id=<?php echo $document['client_id']; ?>" class="btn btn-info">Досие на клиента</a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // Auto-focus search input and select text if there's a query
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.querySelector('.search-input');
            if (searchInput && searchInput.value) {
                searchInput.select();
            }
        });

        // Highlight search terms in results
        function highlightSearchTerms() {
            const query = '<?php echo addslashes($query); ?>';
            if (!query) return;
            
            const terms = query.split(' ').filter(term => term.length > 2);
            const resultItems = document.querySelectorAll('.result-item');
            
            resultItems.forEach(item => {
                let html = item.innerHTML;
                terms.forEach(term => {
                    const regex = new RegExp(`(${term})`, 'gi');
                    html = html.replace(regex, '<span class="highlight">$1</span>');
                });
                item.innerHTML = html;
            });
        }
        
        // Call highlight function after page load
        document.addEventListener('DOMContentLoaded', highlightSearchTerms);
    </script>
</body>
</html>
