<?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';

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

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

try {
    // Önce kargo tablosunu kontrol et
    $tablolar = ['yurtici', 'kargolar', 'kargo'];
    $bulunanTablo = null;
    
    foreach ($tablolar as $tablo) {
        try {
            $test = $db->query("SELECT 1 FROM $tablo LIMIT 1");
            $bulunanTablo = $tablo;
            break;
        } catch (Exception $e) {
            continue;
        }
    }
    
    if (!$bulunanTablo) {
        echo '<tr><td colspan="7" class="text-center py-4" style="color:#f00;">Kargo tablosu bulunamadı (yurtici/kargolar)</td></tr>';
        exit;
    }
    
    if ($k_rol === 'admin') {
        $q = $db->query("SELECT * FROM $bulunanTablo ORDER BY id DESC LIMIT 100");
    } else {
        $q = $db->prepare("SELECT * FROM $bulunanTablo WHERE ekleyen = ? ORDER BY id DESC LIMIT 100");
        $q->execute([$kul_id]);
    }
    $kargolar = $q->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    echo '<tr><td colspan="7" class="text-center py-4" style="color:#f00;">Hata: ' . htmlspecialchars($e->getMessage()) . '</td></tr>';
    exit;
}

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

foreach ($kargolar as $k) {
    $id = htmlspecialchars($k['id'] ?? '-');
    $durum = htmlspecialchars($k['durum'] ?? '-');
    $gonderen = htmlspecialchars($k['gonderen'] ?? '-');
    $teslimalan = htmlspecialchars($k['teslimalan'] ?? '-');
    $teslimbirimi = htmlspecialchars($k['teslimbirimi'] ?? '-');
    
    $link = !empty($dom_yurtici) ? 'https://' . $dom_yurtici . '/' . $id : '#';
    
    echo '<tr>';
    echo '<td><a href="' . $link . '" target="_blank" class="btn-link-go">Linke Git</a></td>';
    echo '<td>' . $id . '</td>';
    echo '<td><span class="badge badge-info">' . $durum . '</span></td>';
    echo '<td>' . $gonderen . '</td>';
    echo '<td>' . $teslimalan . '</td>';
    echo '<td>' . $teslimbirimi . '</td>';
    echo '<td><button class="btn btn-sm btn-danger" onclick="silKargo(\'' . $id . '\')"><i class="fa fa-trash"></i></button></td>';
    echo '</tr>';
}
?>
