<?php
$path = "../../";
include("../../map.php");
include("../../secure.php");

// --- 1. GİRİŞ VE SORGU HAZIRLIĞI ---
$searchKey = isset($_GET['key']) ? trim($_GET['key']) : '';
if (empty($searchKey)) {
    exit; // Boş arama yapılmasın
}

// SQL Injection için basit önlem (Mevcut yapı korundu, prepared statement'a geçilmedi)
$safeKey = mysqli_real_escape_string($conn, $searchKey);
$v3SafeKey = v3e($searchKey);

// Genel Arama Clause'u
$clause = "(ne LIKE '%$safeKey%' OR id LIKE '%$safeKey%' OR t1 LIKE '%$safeKey%' OR t2='$v3SafeKey' OR t4 LIKE '%$safeKey%' OR t5 LIKE '%$safeKey%' OR n2 LIKE '%$safeKey%' OR n4 LIKE '%$safeKey%' OR n17 LIKE '%$safeKey%')";

// ID ile arama yapılıyorsa (örn: id1234)
if (substr($searchKey, 0, 2) == "id") {
    $sor = " id=" . substr($searchKey, -4);
} else {
    $sor = " $clause";
}

// Müşteri listesini önbelleğe al (İsim eşleşmeleri için)
$clients = [];
$sqlc = mysqli_query($conn, "SELECT id, t1 FROM t5 ORDER BY t1 ASC");
while ($rsc = mysqli_fetch_assoc($sqlc)) {
    $clients[$rsc['id']] = $rsc['t1'];
}

// Helper: Müşteri adı bulucu
function getClientName($id, $clients) {
    return isset($clients[$id]) ? $clients[$id] : 'Misafir';
}

// --- 2. VERİ TOPLAMA (DATA AGGREGATION) ---
$results = [];

// A) SABİT MENÜLER VE AYARLAR (Admin/Yönetici Kontrollü)
if (($_SESSION["kim"] == "Admin" or ($_SESSION["kim"] == "yonetici" and $_SESSION["y3_ayar"] == 1))) {
    if (stripos($searchKey, 'ayar') !== false) {
        $results[] = [
            'type' => 'link',
            'url' => '?ne=ayarlar&islem=ayarlar',
            'icon' => 'fa-solid fa-sliders',
            'category' => ctranslate("Ayarlar"),
            'title' => ctranslate("Genel Ayarlar"),
            'date' => ''
        ];
    }
    if (stripos($searchKey, 'slide') !== false) {
        $results[] = [
            'type' => 'link',
            'url' => '?ne=ayarlar&islem=ayarlar#&tab-slide',
            'icon' => 'fa-solid fa-sliders',
            'category' => ctranslate("Ayarlar"),
            'title' => ctranslate("Slider"),
            'date' => ''
        ];
    }
}

// Tanımlar
if (($_SESSION["kim"] == "Admin" or ($_SESSION["kim"] == "yonetici" and $_SESSION["y3_tanim"] == 1))) {
    if (stripos($searchKey, 'tanım') !== false) {
        $results[] = [
            'type' => 'modal',
            'url' => 'modules/public/defination.php?ne=ayarlar&islem=tanimlar',
            'width' => '50%',
            'title_attr' => ctranslate("Tanımlar"),
            'icon' => 'fa-solid fa-sliders',
            'category' => ctranslate("Ayarlar"),
            'title' => ctranslate("Tanımlar"),
            'date' => ''
        ];
    }
}

// Yedekleme (Backup)
if (($_SESSION["kim"] == "Admin" or ($_SESSION["kim"] == "yonetici" and $_SESSION["y3_backup"] == 1))) {
    if (stripos($searchKey, 'backup') !== false or stripos($searchKey, 'yedek') !== false) {
        $results[] = [
            'type' => 'modal',
            'url' => "modules/public/backup{$ver}.php",
            'width' => '50%',
            'title_attr' => ctranslate("Backup"),
            'icon' => 'fa-solid fa-sliders',
            'category' => ctranslate("Ayarlar"),
            'title' => ctranslate("Backup"),
            'date' => ''
        ];
    }
}

// B) KATEGORİLER
if (($_SESSION["kim"] == "Admin") or ($_SESSION["kim"] == "yonetici" and $_SESSION["y9"] <> 0)) {
    $sql = mysqli_query($conn, "SELECT ne, Cat_ID, Cat_" . $_SESSION['lang'] . " as CatName, c1 FROM kategoriler WHERE Cat_" . $_SESSION['lang'] . " LIKE '%$safeKey%' ORDER BY Cat_" . $_SESSION['lang'] . " ASC");
    while ($row = mysqli_fetch_assoc($sql)) {
        // Hedef URL belirleme
        $targetNe = "sayfa"; $targetIslem = "sayfa";
        if ($row["ne"][0] == "u") { $targetNe = "kayit"; $targetIslem = "kayitlar"; }
        elseif ($row["ne"][0] == "h") { $targetNe = "haber"; }
        elseif ($row["ne"][0] == "k") { $targetNe = "uye"; $targetIslem = "uyeler"; }
        
        $results[] = [
            'type' => 'link',
            'url' => "?ne=$targetNe&islem=$targetIslem&grupID=" . $row["Cat_ID"],
            'icon' => 'fa fa-list',
            'category' => ctranslate("Kategori"),
            'title' => $row["CatName"],
            'meta_right' => '#' . $row["Cat_ID"],
            'date' => '...'
        ];
    }
}

// C) İÇERİKLER (Sayfa, Haber, vb.)
$contentSql = mysqli_query($conn, "SELECT id, t1, ne, s2, ts1, ts3 FROM " . $_SESSION['lang'] . " WHERE (ne NOT IN ('kayit','form','ayarlar')) AND $sor $luye ORDER BY t1 ASC");
while ($row = mysqli_fetch_assoc($contentSql)) {
    // Kategori etiketi belirleme
    $catLabel = "";
    if ($row["ne"] == "haber") $catLabel = $t22s[0];
    elseif ($row["ne"] == "sayfa") $catLabel = $t21s[0];
    elseif ($row["ne"] == "msayfa") $catLabel = $n8s[0];
    else {
        // Özel modül adı
        $xmCheck = mysqli_query($conn, "SELECT n1 FROM genel WHERE ne='xmodules' AND n2='" . $row["ne"] . "'");
        if ($rscm = mysqli_fetch_assoc($xmCheck)) $catLabel = $rscm["n1"];
    }

    $dateStr = ($row["ts3"] != "" && $row["ts3"] != "0000-00-00 00:00:00") ? $row["ts3"] : $row["ts1"];
    
    $results[] = [
        'type' => 'modal',
        'url' => "modules/pages/page.php?ne=" . $row["ne"] . "&islem=dsayfa&id=" . $row["id"],
        'width' => '93%',
        'title_attr' => "#" . $row["id"],
        'icon' => 'fa fa-file',
        'category' => $catLabel,
        'title' => kisalt($row["t1"], 50),
        'meta_right' => '#' . $row["id"],
        'date' => dtarih($dateStr, "gg ka yy")
    ];
}

// D) ÜRÜNLER (Katalog)
if ($m14 == 1 and (($_SESSION["kim"] == "Admin") or ($_SESSION["kim"] == "yonetici" and $_SESSION["y0"] <> 0))) {
    if (stripos($searchKey, 'ürünler') !== false) {
         // Genel ürün listesi kısayolu
         $kcount = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM ".$_SESSION['lang']." WHERE ne='kayit' $lkayit"));
         $results[] = [
            'type' => 'link',
            'url' => '?ne=kayit&islem=kayitlar',
            'icon' => 'fa fa-cubes',
            'category' => ctranslate("Katalog"),
            'title' => ctranslate($t24),
            'badge' => $kcount,
            'date' => ''
         ];
    }

    // Ürün Arama
    $prodSql = mysqli_query($conn, "SELECT * FROM " . $_SESSION['lang'] . " WHERE ne='kayit' AND $sor $luye ORDER BY t1 ASC");
    while ($row = mysqli_fetch_assoc($prodSql)) {
        // Stok Durumu ve Renkler
        $iconClass = "text-muted"; $iconTitle = translate("Pasif");
        if ($f7 == 0) {
            if ($row["s13"] == 1) { $iconClass = "text-success"; $iconTitle = translate("Aktif"); }
        } else {
            if ($row["s13"] == 1 && $row["s5"] == 1) { $iconClass = "text-warning"; $iconTitle = translate("Kritik Stok"); }
            elseif ($row["s13"] == 1 && $row["s5"] < 1) { $iconClass = "text-danger"; $iconTitle = translate("Stokta Yok"); }
            elseif ($row["s13"] == 1 && $row["s5"] > 1) { $iconClass = "text-success"; $iconTitle = translate("Stokta Var"); }
        }

        $priceInfo = ($e5 == 1) ? price($row["id"], "pb1") . " " . $ikpb : "";
        
        $results[] = [
            'type' => 'modal',
            'url' => "modules/products/product.php?ne=" . $row["ne"] . "&islem=d" . $row["ne"] . "&id=" . $row["id"],
            'width' => '93%',
            'title_attr' => "#" . $row["id"],
            'icon' => "fa fa-cubes $iconClass",
            'icon_title' => $iconTitle,
            'category' => $t24s[0],
            'title' => kisalt($row["t1"], 50),
            'meta_right' => '#' . $row["id"],
            'date' => $priceInfo
        ];
    }
}

// E) ÜYELER (Clients/Users)
if (stripos($searchKey, 'üyeler') !== false and (($_SESSION["kim"] == "Admin") or ($_SESSION["kim"] == "yonetici" and $_SESSION["y1_uyeler"] <> 0))) {
     // Üye Listesi Kısayolu
     $ucount = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM t5 WHERE ne='uye' $luye"));
     $results[] = [
        'type' => 'link',
        'url' => '?ne=uye&islem=uyeler',
        'icon' => 'fa fa-users',
        'category' => ctranslate($t25),
        'title' => ctranslate($t25),
        'badge' => $ucount,
        'date' => ''
     ];
}
// Üye Arama
$userSql = mysqli_query($conn, "SELECT id, t1, ne, n17 FROM t5 WHERE $sor $luye ORDER BY t1 ASC");
while ($row = mysqli_fetch_assoc($userSql)) {
    $jsi = json_decode($row["n17"], true);
    $companyName = isset($jsi["ifirma"]) ? kisalt($jsi["ifirma"], 20) : '';
    
    $results[] = [
        'type' => 'modal',
        'url' => "modules/clients/client.php?ne=uye&islem=duye&id=" . $row["id"],
        'width' => '93%',
        'title_attr' => "#" . $row["id"],
        'icon' => 'fa fa-user',
        'category' => $t25s[0],
        'title' => $row["t1"],
        'meta_right' => '#' . $row["id"],
        'date' => $companyName
    ];
}

// F) E-TİCARET (Siparişler)
if ($m16 == 1 and ($_SESSION["kim"] == "Admin" or ($_SESSION["kim"] == "yonetici" and $_SESSION["y2_siparis"] == 1))) {
    // Sipariş Arama
    $orderSql = mysqli_query($conn, "SELECT id, t4, s1, ts1 FROM eticaret WHERE ne='siparis' AND (ne LIKE '%$safeKey%' OR t4 LIKE '%$safeKey%' OR n11 LIKE '%$safeKey%') ORDER BY t4 ASC");
    while ($row = mysqli_fetch_assoc($orderSql)) {
        $results[] = [
            'type' => 'modal',
            'url' => "modules/ecommerce/ecommerce_order.php?ne=eticaret&islem=siparis&id=" . $row["id"],
            'width' => '93%',
            'title_attr' => "#" . $row["id"],
            'icon' => 'fa fa-user',
            'category' => $sdil[5], // Siparişler
            'title' => getClientName($row["s1"], $clients),
            'meta_right' => '#' . $row["t4"],
            'date' => dtarih($row["ts1"], "gg ka yy time")
        ];
    }
}

// --- 3. GÖRÜNÜM (VIEW RENDER) ---
?>

<script>
    jQuery(document).ready(function () {
        // Modal logic (korundu ve temizlendi)
        jQuery(".mfrm").on("click", function () {
            var el = jQuery(this);
            var target = el.data("target"),
                theModal = jQuery(target),
                title = el.data("title"),
                width = el.data("width"),
                frmSRC = el.data("url"),
                refSRC = el.data("ref");

            theModal.fadeIn().addClass("in");
            theModal.find(".v3-modal-title").text(title);
            
            <?php if ($mobile == "") { ?>
                if (width !== undefined) { theModal.css("width", width); }
            <?php } ?>

            if (refSRC !== undefined) { 
                theModal.find(".mcbtn").attr("onclick", "location.href='" + refSRC + "'"); 
            }
            theModal.find("iframe").attr("src", frmSRC);
            theModal.find(".close").on("click", function () { 
                theModal.find("iframe").attr("src", "about:blank"); 
            });
        });
    });
</script>

<style>
    /* Daha modern ve temiz CSS */
    .v3-search-list .v3-list-group-item {
        border-bottom: 1px solid #eee !important;
        padding: 8px 15px;
        transition: background-color 0.2s;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .v3-search-list .v3-list-group-item:hover {
        background-color: #fcf8e3; /* Warning Light */
    }
    .v3-item-left {
        display: flex;
        flex-direction: column;
        width: 70%;
    }
    .v3-item-right {
        text-align: right;
        width: 30%;
        font-size: 0.85em;
        color: #666;
    }
    .v3-item-category {
        font-size: 0.8em;
        color: #999;
        text-transform: uppercase;
        margin-bottom: 2px;
    }
    .v3-item-title {
        font-weight: 600;
        font-size: 1em;
        color: #333;
    }
    .v3-item-title i {
        margin-right: 5px;
        width: 16px;
        text-align: center;
    }
    .v3-badge {
        background: #d9534f;
        color: #fff;
        padding: 1px 6px;
        border-radius: 4px;
        font-size: 0.75em;
        margin-left: 5px;
    }
    .v3-no-result {
        text-align: center;
        color: #999;
        padding: 10px;
    }
</style>

<ul class="v3-search-list list-group" id="search-list" style="<?php if($searchKey==""){?>display:none;<?php }?>">
    <?php 
    $totalRecords = count($results);
    
    if ($totalRecords > 0) {
        foreach ($results as $item) { 
            // Modal mı yoksa yeni pencere linki mi?
            $classStr = "v3-list-group-item";
            $attrStr = "";
            
            if ($item['type'] == 'modal') {
                $classStr .= " mfrm";
                $attrStr .= ' data-toggle="modal" data-target="#myModal"';
                $attrStr .= ' data-url="' . $item['url'] . '"';
                $attrStr .= ' data-title="' . (isset($item['title_attr']) ? $item['title_attr'] : $item['title']) . '"';
                if (isset($item['width'])) $attrStr .= ' data-width="' . $item['width'] . '"';
            } else {
                $attrStr .= ' onclick="window.open(\'' . $item['url'] . '\',\'_blank\');" style="cursor:pointer;"';
            }
    ?>
        <li class="<?php echo $classStr; ?>" <?php echo $attrStr; ?>>
            <div class="v3-item-left">
                <span class="v3-item-category">
                    <?php echo $item['category']; ?>
                </span>
                <span class="v3-item-title" title="<?php echo strip_tags($item['title']); ?>">
                    <i class="<?php echo $item['icon']; ?>" title="<?php echo isset($item['icon_title']) ? $item['icon_title'] : ''; ?>"></i> 
                    <?php echo $item['title']; ?>
                    <?php if (isset($item['badge'])) { ?>
                        <span class="v3-badge"><?php echo $item['badge']; ?></span>
                    <?php } ?>
                </span>
            </div>
            
            <div class="v3-item-right">
                <?php if (isset($item['meta_right'])) { ?>
                    <div><?php echo $item['meta_right']; ?></div>
                <?php } ?>
                <div><?php echo $item['date']; ?></div>
            </div>
        </li>
    <?php 
        } 
    } 
    ?>

    <li class="v3-list-group-item" style="background: #e9e9e9; min-height: 30px;">
        <div style="width:100%; text-align:center; color:#555;">
            <?php if ($totalRecords > 0) { ?>
                <i class="fa fa-check"></i> <?php echo "$totalRecords " . translate("Kayıt Bulundu"); ?>
            <?php } else { ?>
                <i class="fa fa-ban"></i> <?php echo ctranslate("Kayıt Bulunamadı"); ?>
            <?php } ?>
        </div>
    </li>
</ul>