<?php

namespace App\Controllers;

use App\Config\Database;
use App\Utils\View;

class SearchController
{
    public function search()
    {
        $query = $_GET['q'] ?? '';
        $results = [];

        if (!empty($query)) {
            $conn = Database::getInstance()->getConnection();
            $term = "%$query%";

            // Search Clients
            $stmt = $conn->prepare("SELECT id, name, 'client' as type FROM clients WHERE name LIKE :term OR email LIKE :term OR asn LIKE :term");
            $stmt->execute(['term' => $term]);
            $results['clients'] = $stmt->fetchAll();

            // Search Servers
            $stmt = $conn->prepare("SELECT id, name, 'server' as type FROM servers WHERE name LIKE :term OR ip_v4 LIKE :term");
            $stmt->execute(['term' => $term]);
            $results['servers'] = $stmt->fetchAll();

            // Search Orders (Title, Content, or Linked Domain)
            $stmt = $conn->prepare("SELECT DISTINCT o.id, o.title as name, 'order' as type 
                                  FROM orders o 
                                  LEFT JOIN order_items oi ON o.id = oi.order_id 
                                  LEFT JOIN domains d ON oi.domain_id = d.id 
                                  WHERE o.title LIKE :term 
                                  OR o.content LIKE :term 
                                  OR d.name LIKE :term");
            $stmt->execute(['term' => $term]);
            $results['orders'] = $stmt->fetchAll();

            // Search Domains
            $stmt = $conn->prepare("SELECT id, name, 'domain' as type FROM domains WHERE name LIKE :term");
            $stmt->execute(['term' => $term]);
            $results['domains'] = $stmt->fetchAll();
        }

        View::render('layouts.admin', [
            'title' => 'Resultados da Busca',
            'content' => __DIR__ . '/../../resources/views/admin/search/results.php',
            'query' => $query,
            'results' => $results
        ]);
    }
}
