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

/*
|--------------------------------------------------------------------------
| OKEY YÖNETİCİLERİ YÖNETİM EKRANI
|--------------------------------------------------------------------------
| okey-managers.php
| Ana Sayfada Gösterilecek Okey Yönetim Kadrosu Listeleme Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Okey Yöneticileri';
$pageDescription = 'Ana sayfada görünecek okey yönetim kadrosunu, görev ünvanlarını ve görünürlük durumlarını yönetin.';

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

$managers = [];
$message = '';
$messageType = '';

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

try {
    if (isset($pdo) && $pdo instanceof PDO) {

        if (isset($_GET['delete']) && (int)$_GET['delete'] > 0) {
            $deleteId = (int)$_GET['delete'];

            $stmt = $pdo->prepare("DELETE FROM okey_managers WHERE id = ? LIMIT 1");
            $stmt->execute([$deleteId]);

            $message = 'Okey yöneticisi başarıyla silindi.';
            $messageType = 'success';
        }

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

        $stats['active'] = (int)$pdo->query("
            SELECT COUNT(*)
            FROM okey_managers
            WHERE status IN ('active','aktif','1')
        ")->fetchColumn();

        $stats['titles'] = (int)$pdo->query("
            SELECT COUNT(*)
            FROM okey_manager_titles
            WHERE status IN ('active','aktif','1')
        ")->fetchColumn();

        $stmt = $pdo->query("
            SELECT 
                m.*,
                t.title_name,
                t.icon AS title_icon
            FROM okey_managers m
            LEFT JOIN okey_manager_titles t ON t.id = m.title_id
            ORDER BY m.sort_order ASC, m.id DESC
            LIMIT 200
        ");

        $managers = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
} catch (Throwable $e) {
    $message = 'İşlem sırasında sistem hatası oluştu.';
    $messageType = 'error';
    error_log('Okey yöneticileri listeleme / silme hatası: ' . $e->getMessage());
}

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

    return $default;
}

function okey_manager_image(array $manager): string
{
    $image = okey_manager_value($manager, ['image', 'avatar', 'photo'], '');

    if ($image === '' || $image === '-') {
        return '../assets/images/admin-default.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/managers/' . $imageName,
            'url'  => '../uploads/managers/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/manager/' . $imageName,
            'url'  => '../uploads/manager/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/users/' . $imageName,
            'url'  => '../uploads/users/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/user/' . $imageName,
            'url'  => '../uploads/user/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/' . $imageName,
            'url'  => '../uploads/' . $imageName,
        ],
    ];

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

    return '../assets/images/admin-default.png';
}

function okey_manager_status_class(string $status): string
{
    $status = strtolower($status);

    return in_array($status, ['active', 'aktif', '1'], true) ? 'active' : 'passive';
}
?>

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

.okey-manager-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);
}

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

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

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

.okey-manager-alert{
    padding:15px 18px;
    border-radius:18px;
    font-weight:900;
    margin-bottom:18px;
}

.okey-manager-alert.success{
    background:rgba(0,150,70,.20);
    border:1px solid rgba(0,255,120,.30);
    color:#d8ffe8;
}

.okey-manager-alert.error{
    background:rgba(185,0,0,.20);
    border:1px solid rgba(255,80,80,.30);
    color:#ffdede;
}

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

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

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

.okey-manager-table-wrap{
    overflow:auto;
    border-radius:28px;
    border:1px solid rgba(255,255,255,.09);
    background:rgba(255,255,255,.045);
    box-shadow:0 24px 70px rgba(0,0,0,.18);
}

.okey-manager-table{
    width:100%;
    min-width:980px;
    border-collapse:collapse;
}

.okey-manager-table th,
.okey-manager-table td{
    padding:16px;
    border-bottom:1px solid rgba(255,255,255,.07);
    text-align:left;
    color:#d7dce6;
    font-size:14px;
    vertical-align:middle;
}

.okey-manager-table th{
    color:#f5b642;
    background:rgba(0,0,0,.22);
    font-weight:900;
}

.okey-manager-info{
    display:flex;
    align-items:center;
    gap:12px;
}

.okey-manager-avatar{
    position:relative;
    width:52px;
    height:52px;
    border-radius:50%;
    padding:2px;
    background:linear-gradient(135deg,#f5b642,#b90000);
    flex:0 0 auto;
}

.okey-manager-avatar img{
    width:100%;
    height:100%;
    border-radius:50%;
    object-fit:cover;
    background:#111;
}

.okey-manager-info strong{
    display:block;
    color:#fff;
    margin-bottom:4px;
}

.okey-manager-info span{
    color:#9aa3b2;
    font-size:12px;
}

.badge{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:7px 11px;
    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);
}

.action-group{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
}

.action-link{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-height:36px;
    padding:0 12px;
    border-radius:12px;
    text-decoration:none;
    color:#fff;
    background:rgba(255,255,255,.07);
    border:1px solid rgba(255,255,255,.10);
    font-size:12px;
    font-weight:900;
}

.action-link:hover{
    color:#f5b642;
    border-color:#f5b642;
}

.action-link.danger{
    color:#ffdede;
    background:rgba(185,0,0,.20);
    border-color:rgba(255,80,80,.28);
}

.action-link.danger:hover{
    color:#fff;
    background:linear-gradient(135deg,#b90000,#ff5d5d);
    border-color:rgba(255,80,80,.55);
}

.empty-okey-manager{
    padding:30px;
    text-align:center;
    color:#9aa3b2;
    font-weight:800;
}

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

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

@media(max-width:560px){
    .okey-manager-stats{
        grid-template-columns:1fr;
    }
}
</style>

<section class="okey-manager-stats">
    <div class="okey-manager-stat" data-icon="👑">
        <span>Toplam Okey Yöneticisi</span>
        <strong><?= admin_e((string)$stats['total']) ?></strong>
    </div>

    <div class="okey-manager-stat" data-icon="✅">
        <span>Aktif Yönetici</span>
        <strong><?= admin_e((string)$stats['active']) ?></strong>
    </div>

    <div class="okey-manager-stat" data-icon="🏷️">
        <span>Aktif Ünvan</span>
        <strong><?= admin_e((string)$stats['titles']) ?></strong>
    </div>
</section>

<?php if ($message !== ''): ?>
    <div class="okey-manager-alert <?= admin_e($messageType) ?>">
        <?= admin_e($message) ?>
    </div>
<?php endif; ?>

<section class="okey-manager-toolbar">
    <div>
        <h2>Okey Yönetim Kadrosu</h2>
        <p>Ana sayfadaki yöneticiler bölümünde görünecek resimli yönetim kadrosunu buradan yönetin.</p>
    </div>

    <a href="okey-manager-view.php" class="admin-btn">+ Yeni Okey Yöneticisi Oluştur</a>
</section>

<section class="okey-manager-table-wrap">
    <table class="okey-manager-table">
        <thead>
            <tr>
                <th>Yönetici</th>
                <th>Rumuz</th>
                <th>Okey Yönetim Adı</th>
                <th>Görev Ünvanı</th>
                <th>Durum</th>
                <th>Sıra</th>
                <th>İşlem</th>
            </tr>
        </thead>

        <tbody>
            <?php if ($managers): ?>
                <?php foreach ($managers as $manager): ?>
                    <?php
                    $status = okey_manager_value($manager, ['status'], 'active');
                    $statusClass = okey_manager_status_class($status);

                    $titleIcon = okey_manager_value($manager, ['title_icon'], '👑');
                    $titleName = okey_manager_value($manager, ['title_name'], 'Okey Yöneticisi');
                    ?>
                    <tr>
                        <td>
                            <div class="okey-manager-info">
                                <div class="okey-manager-avatar">
                                    <img src="<?= admin_e(okey_manager_image($manager)) ?>" alt="Okey Yöneticisi">
                                </div>

                                <div>
                                    <strong><?= admin_e(okey_manager_value($manager, ['display_name'], 'Okey Yöneticisi')) ?></strong>
                                    <span><?= admin_e($titleName) ?></span>
                                </div>
                            </div>
                        </td>

                        <td><?= admin_e(okey_manager_value($manager, ['username'], '-')) ?></td>

                        <td><?= admin_e(okey_manager_value($manager, ['display_name'], '-')) ?></td>

                        <td>
                            <span class="badge">
                                <?= admin_e($titleIcon) ?> <?= admin_e($titleName) ?>
                            </span>
                        </td>

                        <td>
                            <span class="badge <?= admin_e($statusClass) ?>">
                                <?= admin_e($status) ?>
                            </span>
                        </td>

                        <td><?= admin_e(okey_manager_value($manager, ['sort_order'], '0')) ?></td>

                        <td>
                            <div class="action-group">
                                <a href="okey-manager-edit.php?id=<?= (int)($manager['id'] ?? 0) ?>" class="action-link">Düzenle</a>
                                <a href="okey-manager-view.php?id=<?= (int)($manager['id'] ?? 0) ?>" class="action-link">Detay</a>
                                <a href="okey-managers.php?delete=<?= (int)($manager['id'] ?? 0) ?>"
                                   class="action-link danger"
                                   onclick="return confirm('Bu okey yöneticisini silmek istediğine emin misin?');">
                                    Sil
                                </a>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="7">
                        <div class="empty-okey-manager">
                            Henüz okey yöneticisi oluşturulmadı.
                        </div>
                    </td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</section>

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