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

/*
|--------------------------------------------------------------------------
| İNDİRME DÜZENLEME EKRANI
|--------------------------------------------------------------------------
| download-edit.php
| Okey Platformu İndirme Dosyası Düzenleme Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'İndirme Düzenle';
$pageDescription = 'Okey oyunu indirme dosyası, sürüm ve bağlantı bilgilerini düzenleyin.';

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

$id = (int)($_GET['id'] ?? 0);

$message = '';
$messageType = '';
$download = null;
$columns = [];

function download_edit_columns(PDO $pdo): array
{
    $columns = [];

    try {
        $query = $pdo->query("SHOW COLUMNS FROM downloads");

        while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $columns[] = (string)$row['Field'];
        }
    } catch (Throwable $e) {
        return [];
    }

    return $columns;
}

function download_edit_has(array $columns, string $column): bool
{
    return in_array($column, $columns, true);
}

function download_edit_value(?array $row, array $keys, string $default = ''): string
{
    if (!$row) {
        return $default;
    }

    foreach ($keys as $key) {
        if (isset($row[$key]) && trim((string)$row[$key]) !== '') {
            return (string)$row[$key];
        }
    }

    return $default;
}

function download_edit_upload_file(string $field): array
{
    if (empty($_FILES[$field]['name']) || empty($_FILES[$field]['tmp_name'])) {
        return ['', ''];
    }

    $allowed = ['exe', 'zip', 'rar', 'msi'];
    $ext = strtolower(pathinfo((string)$_FILES[$field]['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
        return ['', ''];
    }

    $uploadDir = __DIR__ . '/../uploads/downloads/';

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $fileName = 'download-' . date('YmdHis') . '-' . bin2hex(random_bytes(5)) . '.' . $ext;
    $target = $uploadDir . $fileName;

    if (move_uploaded_file((string)$_FILES[$field]['tmp_name'], $target)) {
        return [$fileName, '../uploads/downloads/' . $fileName];
    }

    return ['', ''];
}

try {
    if (!isset($pdo) || !($pdo instanceof PDO)) {
        throw new RuntimeException('Veritabanı bağlantısı bulunamadı.');
    }

    if ($id <= 0) {
        throw new RuntimeException('Geçersiz indirme ID.');
    }

    $columns = download_edit_columns($pdo);

    $stmt = $pdo->prepare("SELECT * FROM downloads WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $download = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$download) {
        throw new RuntimeException('İndirme kaydı bulunamadı.');
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $title       = trim((string)($_POST['title'] ?? ''));
        $version     = trim((string)($_POST['version'] ?? ''));
        $fileUrl     = trim((string)($_POST['file_url'] ?? ''));
        $fileSize    = trim((string)($_POST['file_size'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));
        $status      = trim((string)($_POST['status'] ?? 'active'));

        if ($title === '') {
            throw new RuntimeException('İndirme başlığı zorunludur.');
        }

        [$uploadedName, $uploadedUrl] = download_edit_upload_file('file');

        if ($uploadedUrl !== '') {
            $fileUrl = $uploadedUrl;
        }

        $update = [];

        if (download_edit_has($columns, 'title')) {
            $update['title'] = $title;
        }

        if (download_edit_has($columns, 'name')) {
            $update['name'] = $title;
        }

        if (download_edit_has($columns, 'version')) {
            $update['version'] = $version;
        }

        if (download_edit_has($columns, 'file_path')) {
            $update['file_path'] = $fileUrl;
        }

        if (download_edit_has($columns, 'file_url')) {
            $update['file_url'] = $fileUrl;
        }

        if (download_edit_has($columns, 'url')) {
            $update['url'] = $fileUrl;
        }

        if ($uploadedName !== '' && download_edit_has($columns, 'file_name')) {
            $update['file_name'] = $uploadedName;
        }

        if (download_edit_has($columns, 'file_size')) {
            $update['file_size'] = $fileSize;
        }

        if (download_edit_has($columns, 'size')) {
            $update['size'] = $fileSize;
        }

        if (download_edit_has($columns, 'description')) {
            $update['description'] = $description;
        }

        if (download_edit_has($columns, 'status')) {
            $update['status'] = $status;
        }

        if (download_edit_has($columns, 'updated_at')) {
            $update['updated_at'] = date('Y-m-d H:i:s');
        }

        if (!$update) {
            throw new RuntimeException('Güncellenecek uygun kolon bulunamadı.');
        }

        $set = [];

        foreach ($update as $field => $value) {
            $set[] = "`{$field}` = ?";
        }

        $values = array_values($update);
        $values[] = $id;

        $sql = "UPDATE downloads SET " . implode(', ', $set) . " WHERE id = ? LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($values);

        $message = 'İndirme kaydı başarıyla güncellendi.';
        $messageType = 'success';

        $stmt = $pdo->prepare("SELECT * FROM downloads WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
        $download = $stmt->fetch(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $message = $e->getMessage();
    $messageType = 'error';
}
?>

<style>
.download-edit-shell{
    display:grid;
    grid-template-columns:1fr .38fr;
    gap:22px;
}

.download-edit-card{
    padding:28px;
    border-radius:30px;
    background:rgba(255,255,255,.055);
    border:1px solid rgba(255,255,255,.09);
    box-shadow:0 24px 70px rgba(0,0,0,.20);
}

.download-edit-card h2{
    margin:0 0 8px;
    color:#f5b642;
    font-size:24px;
}

.download-edit-card p{
    margin:0 0 22px;
    color:#9aa3b2;
    font-weight:700;
    line-height:1.6;
}

.form-grid{
    display:grid;
    grid-template-columns:repeat(2,1fr);
    gap:18px;
}

.form-group.full{
    grid-column:1 / -1;
}

.form-group label{
    display:block;
    margin-bottom:8px;
    color:#dce3ef;
    font-size:14px;
    font-weight:900;
}

.form-control{
    width:100%;
    height:52px;
    border:1px solid rgba(255,255,255,.12);
    border-radius:16px;
    background:rgba(0,0,0,.25);
    color:#fff;
    padding:0 15px;
    outline:none;
}

textarea.form-control{
    height:auto;
    min-height:140px;
    padding:15px;
    resize:vertical;
}

.form-control:focus{
    border-color:#f5b642;
    box-shadow:0 0 0 4px rgba(245,182,66,.12);
}

input[type="file"].form-control{
    padding:14px;
    height:auto;
}

.form-actions{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    margin-top:22px;
}

.edit-alert{
    margin-bottom:18px;
    padding:15px 18px;
    border-radius:16px;
    font-weight:800;
}

.edit-alert.success{
    background:rgba(0,170,80,.18);
    border:1px solid rgba(0,255,140,.25);
    color:#b9ffd8;
}

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

.file-side{
    display:grid;
    gap:16px;
}

.file-box{
    padding:24px;
    border-radius:28px;
    background:linear-gradient(135deg,rgba(245,182,66,.13),rgba(185,0,0,.10));
    border:1px solid rgba(255,255,255,.09);
}

.file-icon{
    width:74px;
    height:74px;
    border-radius:24px;
    display:flex;
    align-items:center;
    justify-content:center;
    margin-bottom:16px;
    font-size:34px;
    background:linear-gradient(135deg,#f5b642,#b90000);
}

.file-box strong{
    display:block;
    color:#fff;
    font-size:18px;
    margin-bottom:6px;
}

.file-box span{
    display:block;
    color:#9aa3b2;
    font-size:13px;
    font-weight:800;
    line-height:1.6;
    word-break:break-all;
}

.info-box{
    padding:22px;
    border-radius:26px;
    background:rgba(255,255,255,.052);
    border:1px solid rgba(255,255,255,.09);
}

.info-box strong{
    display:block;
    color:#f5b642;
    font-size:18px;
    margin-bottom:8px;
}

.info-box span{
    color:#cbd2df;
    font-size:13px;
    font-weight:700;
    line-height:1.7;
}

@media(max-width:1000px){
    .download-edit-shell{
        grid-template-columns:1fr;
    }

    .form-grid{
        grid-template-columns:1fr;
    }
}
</style>

<section class="download-edit-shell">

    <div class="download-edit-card">
        <h2>İndirme Bilgilerini Düzenle</h2>
        <p>Okey oyunu indirme dosyası, sürüm bilgisi, dosya bağlantısı ve yayın durumunu düzenleyebilirsiniz.</p>

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

        <?php if ($download): ?>
            <form method="post" enctype="multipart/form-data">

                <div class="form-grid">

                    <div class="form-group">
                        <label>Başlık</label>
                        <input type="text" name="title" class="form-control" value="<?= admin_e(download_edit_value($download, ['title', 'name'], '')) ?>" required>
                    </div>

                    <div class="form-group">
                        <label>Sürüm</label>
                        <input type="text" name="version" class="form-control" value="<?= admin_e(download_edit_value($download, ['version'], '')) ?>">
                    </div>

                    <div class="form-group full">
                        <label>Dosya Bağlantısı</label>
                        <input type="text" name="file_url" class="form-control" value="<?= admin_e(download_edit_value($download, ['file_path', 'file_url', 'url'], '')) ?>">
                    </div>

                    <div class="form-group">
                        <label>Yeni Dosya Yükle</label>
                        <input type="file" name="file" class="form-control" accept=".exe,.zip,.rar,.msi">
                    </div>

                    <div class="form-group">
                        <label>Dosya Boyutu</label>
                        <input type="text" name="file_size" class="form-control" value="<?= admin_e(download_edit_value($download, ['file_size', 'size'], '')) ?>">
                    </div>

                    <div class="form-group full">
                        <label>Açıklama</label>
                        <textarea name="description" class="form-control"><?= admin_e(download_edit_value($download, ['description'], '')) ?></textarea>
                    </div>

                    <div class="form-group">
                        <label>Durum</label>
                        <?php $currentStatus = download_edit_value($download, ['status'], 'active'); ?>
                        <select name="status" class="form-control">
                            <option value="active" <?= in_array($currentStatus, ['active', 'aktif', '1'], true) ? 'selected' : '' ?>>Aktif</option>
                            <option value="passive" <?= in_array($currentStatus, ['passive', 'pasif', '0'], true) ? 'selected' : '' ?>>Pasif</option>
                        </select>
                    </div>

                </div>

                <div class="form-actions">
                    <button type="submit" class="admin-btn">Değişiklikleri Kaydet</button>
                    <a href="downloads.php" class="admin-btn admin-btn-dark">Listeye Dön</a>
                </div>

            </form>
        <?php endif; ?>
    </div>

    <aside class="file-side">
        <div class="file-box">
            <div class="file-icon">⬇️</div>

            <strong><?= admin_e(download_edit_value($download, ['title', 'name'], 'İndirme Dosyası')) ?></strong>
            <span><?= admin_e(download_edit_value($download, ['file_path', 'file_url', 'url'], 'Dosya yolu bulunmuyor.')) ?></span>
        </div>

        <div class="info-box">
            <strong>Dosya Güncelleme</strong>
            <span>Yeni dosya yüklenirse mevcut bağlantı yeni yüklenen dosya ile değiştirilir. Dosya seçilmezse mevcut bağlantı korunur.</span>
        </div>

        <div class="info-box">
            <strong>EXE / ZIP Desteği</strong>
            <span>Exe, zip, rar ve msi uzantılı dosyalar yüklenebilir.</span>
        </div>

        <div class="info-box">
            <strong>Sürüm Bilgisi</strong>
            <span>Oyuncuların doğru dosyayı indirmesi için sürüm numarasını güncel tutun.</span>
        </div>
    </aside>

</section>

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