<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

$q = trim($_GET['q'] ?? '');

if (strlen($q) < 2) {
    Response::success('Query too short', []);
}

$databaseName = $db->query('SELECT DATABASE()')->fetchColumn();

/*
|--------------------------------------------------------------------------
| STEP 1: Get all searchable columns
|--------------------------------------------------------------------------
*/
$columnsStmt = $db->prepare("
    SELECT TABLE_NAME, COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = :db
      AND DATA_TYPE IN ('varchar','text','enum','char')
      AND TABLE_NAME NOT LIKE '%sessions%'
      AND TABLE_NAME NOT LIKE '%logs%'
");
$columnsStmt->execute(['db' => $databaseName]);

$tables = [];
while ($row = $columnsStmt->fetch(PDO::FETCH_ASSOC)) {
    $tables[$row['TABLE_NAME']][] = $row['COLUMN_NAME'];
}

/*
|--------------------------------------------------------------------------
| STEP 2: Search each table
|--------------------------------------------------------------------------
*/
$results = [];

foreach ($tables as $table => $columns) {

    // skip very large system tables if needed
    if (in_array($table, ['migrations'])) {
        continue;
    }

    $conditions = [];
    foreach ($columns as $col) {
        $conditions[] = "`$col` LIKE :q";
    }

    if (!$conditions) continue;

    $sql = "
        SELECT *
        FROM `$table`
        WHERE " . implode(' OR ', $conditions) . "
        LIMIT 5
    ";

    try {
        $stmt = $db->prepare($sql);
        $stmt->execute(['q' => "%$q%"]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($rows) {
            $results[$table] = $rows;
        }
    } catch (Throwable $e) {
        // silently skip broken tables
        continue;
    }
}

Response::success('Global search results', $results);
