<?php
/*
|--------------------------------------------------------------------------
| RadyoHost.BiZ / Profesyonel Radyo Hosting ve Web Tasarım Hizmetleri
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| REKLAM VE SPONSOR YÖNETİM EKRANI
|--------------------------------------------------------------------------
| ads.php
| Okey Platformu Reklam ve Sponsor Kart Listeleme Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Reklam ve Sponsor Yönetimi';
$pageDescription = 'Okey Platformu ana sayfa reklam ve sponsor alanlarını kart görünümüyle yönetin.';

require_once __DIR__ . '/includes/admin-layout.php';

if (!function_exists('admin_e')) {
    function admin_e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

$ads = [];
$message = '';
$error = '';

$stats = [
    'total'   => 0,
    'active'  => 0,
    'passive' => 0,
    'today'   => 0,
];

$columns = [];
$tableExists = false;

function ad_value(array $ad, array $keys, string $default = '-'): string
{
    foreach ($keys as $key) {
        if (isset($ad[$key]) && trim((string)$ad[$key]) !== '') {
            return (string)$ad[$key];
        }
    }

    return $default;
}

function ad_image(array $ad): string
{
    $image = ad_value($ad, ['image', 'image_path', 'banner'], '');

    if ($image === '' || $image === '-') {
        return '../assets/images/no-image.png';
    }

    $image = trim(str_replace('\\', '/', $image));

    if (str_starts_with($image, 'http://') || str_starts_with($image, 'https://')) {
        return $image;
    }

    $imageName = basename($image);

    $paths = [
        [
            'disk' => __DIR__ . '/../uploads/ads/' . $imageName,
            'url'  => '../uploads/ads/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/site/' . $imageName,
            'url'  => '../uploads/site/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/' . $imageName,
            'url'  => '../uploads/' . $imageName,
        ],
    ];

    foreach ($paths as $path) {
        if (is_file($path['disk'])) {
            return $path['url'];
        }
    }

    return '../assets/images/no-image.png';
}

function ad_status_class(string $status): string
{
    $status = strtolower($status);
    return in_array($status, ['active', 'aktif', '1'], true) ? 'active' : 'passive';
}

try {
    if (isset($pdo) && $pdo instanceof PDO) {
        try {
            $checkTable = $pdo->query("SHOW TABLES LIKE 'site_ads'");
            $tableExists = (bool)$checkTable->fetchColumn();
        } catch (Throwable $e) {
            $tableExists = false;
        }

        if ($tableExists) {
            $columnQuery = $pdo->query("SHOW COLUMNS FROM site_ads");

            while ($row = $columnQuery->fetch(PDO::FETCH_ASSOC)) {
                $columns[] = (string)$row['Field'];
            }

            if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
                $deleteId = (int)$_POST['delete_id'];

                if ($deleteId > 0) {
                    $deleteStmt = $pdo->prepare("DELETE FROM site_ads WHERE id = :id LIMIT 1");
                    $deleteStmt->execute(['id' => $deleteId]);

                    $message = 'Reklam kaydı başarıyla silindi.';
                }
            }

            $stats['total'] = (int)$pdo->query("
                SELECT COUNT(*)
                FROM site_ads
            ")->fetchColumn();

            if (in_array('status', $columns, true)) {
                $stats['active'] = (int)$pdo->query("
                    SELECT COUNT(*)
                    FROM site_ads
                    WHERE status = 'active'
                ")->fetchColumn();

                $stats['passive'] = (int)$pdo->query("
                    SELECT COUNT(*)
                    FROM site_ads
                    WHERE status = 'passive'
                ")->fetchColumn();
            }

            if (in_array('created_at', $columns, true)) {
                $stats['today'] = (int)$pdo->query("
                    SELECT COUNT(*)
                    FROM site_ads
                    WHERE DATE(created_at) = CURDATE()
                ")->fetchColumn();
            }

            $orderSql = in_array('sort_order', $columns, true)
                ? "ORDER BY sort_order ASC, id DESC"
                : "ORDER BY id DESC";

            $ads = $pdo->query("
                SELECT *
                FROM site_ads
                {$orderSql}
                LIMIT 100
            ")->fetchAll(PDO::FETCH_ASSOC);
        }
    }
} catch (Throwable $e) {
    error_log('Reklam ve sponsor yönetimi hatası: ' . $e->getMessage());
    $error = 'Reklam kayıtları alınırken sistem hatası oluştu.';
}
?>

<style>
.ad-stats{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:18px;
    margin-bottom:24px;
}

.ad-stat{
    position:relative;
    overflow:hidden;
    padding:24px;
    border-radius:28px;
    background:rgba(255,255,255,.055);
    border:1px solid rgba(255,255,255,.09);
    box-shadow:0 22px 64px rgba(0,0,0,.18);
}

.ad-stat:after{
    content:attr(data-icon);
    position:absolute;
    right:18px;
    bottom:8px;
    font-size:54px;
    opacity:.12;
}

.ad-stat span{
    display:block;
    color:#9aa3b2;
    font-size:13px;
    font-weight:900;
}

.ad-stat strong{
    display:block;
    margin-top:12px;
    color:#f5b642;
    font-size:38px;
}

.ad-toolbar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:16px;
    margin-bottom:22px;
    padding:22px;
    border-radius:28px;
    background:rgba(255,255,255,.052);
    border:1px solid rgba(255,255,255,.09);
}

.ad-toolbar h2{
    margin:0;
    color:#f5b642;
    font-size:22px;
}

.ad-toolbar p{
    margin:7px 0 0;
    color:#9aa3b2;
    font-size:13px;
    font-weight:700;
}

.alert{
    margin-bottom:20px;
    padding:16px 18px;
    border-radius:20px;
    font-weight:900;
    line-height:1.6;
}

.alert.success{
    color:#b8ffd7;
    background:rgba(0,170,80,.14);
    border:1px solid rgba(0,255,140,.22);
}

.alert.error,
.db-warning{
    margin-bottom:20px;
    padding:18px 20px;
    border-radius:22px;
    color:#ffdada;
    background:rgba(185,0,0,.15);
    border:1px solid rgba(255,80,80,.25);
    font-weight:800;
}

.db-warning code{
    color:#f5b642;
}

.ads-grid{
    display:grid;
    grid-template-columns:repeat(3,1fr);
    gap:22px;
}

.ad-card{
    position:relative;
    overflow:hidden;
    border-radius:30px;
    background:
        radial-gradient(circle at top right,rgba(245,182,66,.15),transparent 36%),
        linear-gradient(145deg,rgba(255,255,255,.075),rgba(255,255,255,.035));
    border:1px solid rgba(245,182,66,.18);
    box-shadow:0 24px 72px rgba(0,0,0,.25);
    transition:.25s;
}

.ad-card:hover{
    transform:translateY(-7px);
    border-color:rgba(245,182,66,.55);
    box-shadow:0 34px 95px rgba(0,0,0,.45);
}

.ad-card:before{
    content:"";
    position:absolute;
    inset:0;
    background:
        radial-gradient(circle at 12% 12%,rgba(245,182,66,.13),transparent 34%),
        radial-gradient(circle at 88% 8%,rgba(185,0,0,.13),transparent 34%);
    pointer-events:none;
    z-index:1;
}

.ad-card-image{
    position:relative;
    height:178px;
    overflow:hidden;
    background:#070911;
}

.ad-card-image img{
    width:100%;
    height:100%;
    display:block;
    object-fit:cover;
    filter:saturate(1.08) contrast(1.05);
    transition:.35s;
}

.ad-card:hover .ad-card-image img{
    transform:scale(1.06);
}

.ad-card-image:after{
    content:"";
    position:absolute;
    inset:0;
    background:linear-gradient(180deg,rgba(0,0,0,.04),rgba(0,0,0,.74));
}

.ad-card-label{
    position:absolute;
    left:16px;
    top:15px;
    z-index:3;
    display:inline-flex;
    align-items:center;
    gap:7px;
    min-height:32px;
    padding:0 12px;
    border-radius:999px;
    background:rgba(0,0,0,.56);
    border:1px solid rgba(245,182,66,.32);
    color:#f5b642;
    font-size:11px;
    font-weight:1000;
    text-transform:uppercase;
    backdrop-filter:blur(8px);
}

.ad-card-body{
    position:relative;
    z-index:2;
    padding:20px;
}

.ad-card-title{
    margin:0 0 10px;
    color:#fff;
    font-size:20px;
    line-height:1.25;
    font-weight:1000;
}

.ad-card-desc{
    min-height:72px;
    margin:0 0 18px;
    color:#aeb7c7;
    font-size:13px;
    font-weight:750;
    line-height:1.7;
}

.ad-card-meta{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:10px;
    margin-bottom:18px;
}

.ad-card-order{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-height:34px;
    padding:0 11px;
    border-radius:999px;
    color:#ffd47d;
    background:rgba(245,182,66,.11);
    border:1px solid rgba(245,182,66,.22);
    font-size:12px;
    font-weight:900;
}

.badge{
    display:inline-flex;
    padding:8px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:900;
    background:rgba(245,182,66,.13);
    color:#ffd47d;
    border:1px solid rgba(245,182,66,.28);
}

.badge.active{
    background:rgba(0,170,80,.16);
    color:#b8ffd7;
    border-color:rgba(0,255,140,.25);
}

.badge.passive{
    background:rgba(185,0,0,.18);
    color:#ffdada;
    border-color:rgba(255,80,80,.30);
}

.ad-button-lines{
    display:grid;
    gap:8px;
    margin-bottom:18px;
}

.ad-button-line{
    display:flex;
    justify-content:space-between;
    gap:12px;
    padding:10px 12px;
    border-radius:16px;
    background:rgba(0,0,0,.20);
    border:1px solid rgba(255,255,255,.07);
    color:#cfd6e3;
    font-size:12px;
    font-weight:800;
}

.ad-button-line b{
    color:#f5b642;
}

.ad-actions{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
}

.action-link,
.action-delete{
    flex:1;
    min-height:40px;
    border-radius:14px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    text-decoration:none;
    border:1px solid rgba(255,255,255,.10);
    font-size:12px;
    font-weight:1000;
    cursor:pointer;
    transition:.2s;
}

.action-link{
    color:#111;
    background:linear-gradient(135deg,#f5b642,#ffcf6a);
}

.action-detail{
    color:#fff;
    background:rgba(255,255,255,.07);
}

.action-delete{
    color:#fff;
    background:linear-gradient(135deg,#8e0000,#e91515);
    border-color:rgba(255,80,80,.28);
}

.action-link:hover,
.action-delete:hover{
    transform:translateY(-2px);
}

.delete-form{
    flex:1;
    margin:0;
}

.empty-ad{
    grid-column:1 / -1;
    padding:34px;
    border-radius:28px;
    text-align:center;
    color:#9aa3b2;
    font-weight:800;
    background:rgba(255,255,255,.045);
    border:1px solid rgba(255,255,255,.09);
}

@media(max-width:1180px){
    .ads-grid{
        grid-template-columns:repeat(2,1fr);
    }
}

@media(max-width:1000px){
    .ad-stats{
        grid-template-columns:repeat(2,1fr);
    }

    .ad-toolbar{
        flex-direction:column;
        align-items:flex-start;
    }
}

@media(max-width:680px){
    .ads-grid{
        grid-template-columns:1fr;
    }
}

@media(max-width:560px){
    .ad-stats{
        grid-template-columns:1fr;
    }

    .ad-card-image{
        height:160px;
    }

    .ad-actions{
        flex-direction:column;
    }

    .delete-form{
        width:100%;
    }
}
</style>

<section class="ad-stats">
    <div class="ad-stat" data-icon="📣">
        <span>Toplam Reklam</span>
        <strong><?= admin_e((string)$stats['total']) ?></strong>
    </div>

    <div class="ad-stat" data-icon="✅">
        <span>Aktif Reklam</span>
        <strong><?= admin_e((string)$stats['active']) ?></strong>
    </div>

    <div class="ad-stat" data-icon="⏸️">
        <span>Pasif Reklam</span>
        <strong><?= admin_e((string)$stats['passive']) ?></strong>
    </div>

    <div class="ad-stat" data-icon="🆕">
        <span>Bugün Eklenen</span>
        <strong><?= admin_e((string)$stats['today']) ?></strong>
    </div>
</section>

<?php if ($message): ?>
    <section class="alert success">
        <?= admin_e($message) ?>
    </section>
<?php endif; ?>

<?php if ($error): ?>
    <section class="alert error">
        <?= admin_e($error) ?>
    </section>
<?php endif; ?>

<?php if (!$tableExists): ?>
    <section class="db-warning">
        <strong>site_ads</strong> tablosu bulunamadı. Reklam yönetimi için önce veritabanında <code>site_ads</code> tablosunu oluşturmalısınız.
    </section>
<?php endif; ?>

<section class="ad-toolbar">
    <div>
        <h2>Reklam ve Sponsor Listesi</h2>
        <p>Ana sayfadaki reklam ve sponsor kartlarını buradan premium kart görünümüyle yönetebilirsiniz.</p>
    </div>

    <a href="ad-view.php" class="admin-btn">+ Yeni Reklam Oluştur</a>
</section>

<section class="ads-grid">
    <?php if ($tableExists && $ads): ?>
        <?php foreach ($ads as $ad): ?>
            <?php
            $status = ad_value($ad, ['status'], 'active');
            $statusClass = ad_status_class($status);
            $adId = (int)($ad['id'] ?? 0);
            ?>
            <article class="ad-card">
                <div class="ad-card-image">
                    <img src="<?= admin_e(ad_image($ad)) ?>" alt="Reklam">
                    <span class="ad-card-label">📣 Reklam Kartı</span>
                </div>

                <div class="ad-card-body">
                    <h3 class="ad-card-title">
                        <?= admin_e(ad_value($ad, ['title'], 'Reklam Başlığı')) ?>
                    </h3>

                    <p class="ad-card-desc">
                        <?= admin_e(ad_value($ad, ['description', 'summary'], 'Açıklama yok')) ?>
                    </p>

                    <div class="ad-card-meta">
                        <span class="badge <?= admin_e($statusClass) ?>">
                            <?= admin_e($status) ?>
                        </span>

                        <span class="ad-card-order">
                            Sıra: <?= admin_e(ad_value($ad, ['sort_order'], '0')) ?>
                        </span>
                    </div>

                    <div class="ad-button-lines">
                        <div class="ad-button-line">
                            <b>Buton 1</b>
                            <span><?= admin_e(ad_value($ad, ['button_text', 'btn_text'], 'Buton')) ?></span>
                        </div>

                        <div class="ad-button-line">
                            <b>Buton 2</b>
                            <span><?= admin_e(ad_value($ad, ['second_button_text'], 'Buton')) ?></span>
                        </div>
                    </div>

                    <div class="ad-actions">
                        <a href="ad-edit.php?id=<?= $adId ?>" class="action-link">
                            Düzenle
                        </a>

                        <a href="ad-view.php?id=<?= $adId ?>" class="action-link action-detail">
                            Detay
                        </a>

                        <form method="post" class="delete-form" onsubmit="return confirm('Bu reklam kaydını silmek istiyor musunuz?');">
                            <input type="hidden" name="delete_id" value="<?= $adId ?>">
                            <button type="submit" class="action-delete">
                                Sil
                            </button>
                        </form>
                    </div>
                </div>
            </article>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="empty-ad">
            Henüz reklam veya sponsor kaydı bulunamadı.
        </div>
    <?php endif; ?>
</section>

<?php require_once __DIR__ . '/includes/admin-footer.php'; ?>