<?php
require_once '../config.php';
$query = trim($_POST['query'] ?? '');
$type = $_POST['type'] ?? 'content';
if (strlen($query) < 2) {
    echo json_encode(['success'=>false, 'message'=>'Mínimo 2 caracteres']);
    exit;
}
$results = [];
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(ROOT_PATH, RecursiveDirectoryIterator::SKIP_DOTS));
$skip = ['vendor','.git','node_modules','backups','logs','cache'];
foreach ($rii as $file) {
    if ($file->isDir()) continue;
    $path = $file->getPathname();
    $rel = str_replace(ROOT_PATH, '', $path);
    $skipDir = false;
    foreach ($skip as $d) if (strpos($rel, $d) !== false) { $skipDir = true; break; }
    if ($skipDir) continue;
    if ($type == 'name') {
        if (stripos($file->getFilename(), $query) !== false) {
            $results[] = ['name'=>$file->getFilename(), 'path'=>$rel, 'size'=>$file->getSize()];
        }
    } else {
        $ext = strtolower($file->getExtension());
        if (!in_array($ext, ['php','js','css','html','txt','json','xml','sql'])) continue;
        $content = @file_get_contents($path);
        if ($content !== false && stripos($content, $query) !== false) {
            $results[] = ['name'=>$file->getFilename(), 'path'=>$rel, 'size'=>$file->getSize()];
        }
    }
    if (count($results) >= 100) break;
}
echo json_encode(['success'=>true, 'results'=>$results]);
?>