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

/*
|--------------------------------------------------------------------------
| İNDİRME OLUŞTURMA EKRANI
|--------------------------------------------------------------------------
| download-view.php
| Okey Platformu Yeni İndirme Dosyası Oluşturma Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Yeni İndirme Oluştur';
$pageDescription = 'Okey oyunu için EXE dosyası, sürüm ve indirme bağlantısı oluşturun.';

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

$message = '';
$messageType = '';
$isCreated = false;

function download_view_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_view_has(array $columns, string $column): bool
{
    return in_array($column, $columns, true);
}

function download_view_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 ['', ''];
}

$columns = [];

try {
    if (isset($pdo) && $pdo instanceof PDO) {
        $columns = download_view_columns($pdo);
    }
} catch (Throwable $e) {
    $message = 'Downloads tablosu okunamadı.';
    $messageType = 'error';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($pdo) && $pdo instanceof PDO) {
    $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 === '') {
        $message = 'İndirme başlığı zorunludur.';
        $messageType = 'error';
    } else {
        try {
            [$uploadedName, $uploadedUrl] = download_view_upload_file('file');

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

            $insert = [];

            if (download_view_has($columns, 'title')) {
                $insert['title'] = $title;
            }

            if (download_view_has($columns, 'name')) {
                $insert['name'] = $title;
            }

            if (download_view_has($columns, 'version')) {
                $insert['version'] = $version;
            }

            if (download_view_has($columns, 'file_path')) {
                $insert['file_path'] = $fileUrl;
            }

            if (download_view_has($columns, 'file_url')) {
                $insert['file_url'] = $fileUrl;
            }

            if (download_view_has($columns, 'url')) {
                $insert['url'] = $fileUrl;
            }

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

            if (download_view_has($columns, 'file_size')) {
                $insert['file_size'] = $fileSize;
            }

            if (download_view_has($columns, 'size')) {
                $insert['size'] = $fileSize;
            }

            if (download_view_has($columns, 'description')) {
                $insert['description'] = $description;
            }

            if (download_view_has($columns, 'status')) {
                $insert['status'] = $status;
            }

            if (download_view_has($columns, 'download_count')) {
                $insert['download_count'] = 0;
            }

            if (download_view_has($columns, 'created_at')) {
                $insert['created_at'] = date('Y-m-d H:i:s');
            }

            if (!$insert) {
                throw new RuntimeException('Kayıt için uygun kolon bulunamadı.');
            }

            $fields = array_keys($insert);
            $placeholders = array_fill(0, count($fields), '?');

            $sql = "INSERT INTO downloads (`" . implode('`,`', $fields) . "`) VALUES (" . implode(',', $placeholders) . ")";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(array_values($insert));

            $message = 'İndirme kaydı başarıyla oluşturuldu. 10 saniye sonra indirme yönetimine yönlendiriliyorsunuz.';
            $messageType = 'success';
            $isCreated = true;

            $_POST = [];
        } catch (Throwable $e) {
            $message = $e->getMessage();
            $messageType = 'error';
        }
    }
}
?>

<?php if ($isCreated): ?>
    <meta http-equiv="refresh" content="10;url=downloads.php">
<?php endif; ?>

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

.download-form-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-form-card h2{
    margin:0 0 8px;
    color:#f5b642;
    font-size:24px;
}

.download-form-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;
}

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

.info-box{
    padding:22px;
    border-radius:26px;
    background:linear-gradient(135deg,rgba(245,182,66,.13),rgba(185,0,0,.10));
    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;
}

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

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

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

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

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

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

    <div class="download-form-card">
        <h2>Yeni İndirme Oluştur</h2>
        <p>Oyun EXE dosyası, sürüm bilgisi ve indirme bağlantısı oluşturabilirsiniz.</p>

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

        <?php if (!$isCreated): ?>
            <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($_POST['title'] ?? '') ?>" required>
                    </div>

                    <div class="form-group">
                        <label>Sürüm</label>
                        <input type="text" name="version" class="form-control" value="<?= admin_e($_POST['version'] ?? '') ?>" placeholder="v1.0.0">
                    </div>

                    <div class="form-group full">
                        <label>Dosya Bağlantısı</label>
                        <input type="text" name="file_url" class="form-control" value="<?= admin_e($_POST['file_url'] ?? '') ?>" placeholder="../uploads/downloads/oyun.exe">
                    </div>

                    <div class="form-group">
                        <label>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($_POST['file_size'] ?? '') ?>" placeholder="125 MB">
                    </div>

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

                    <div class="form-group">
                        <label>Durum</label>
                        <select name="status" class="form-control">
                            <option value="active" <?= (($_POST['status'] ?? 'active') === 'active') ? 'selected' : '' ?>>Aktif</option>
                            <option value="passive" <?= (($_POST['status'] ?? '') === 'passive') ? 'selected' : '' ?>>Pasif</option>
                        </select>
                    </div>

                </div>

                <div class="form-actions">
                    <button type="submit" class="admin-btn">İndirme Kaydını Oluştur</button>
                    <a href="downloads.php" class="admin-btn admin-btn-dark">Listeye Dön</a>
                </div>

            </form>
        <?php else: ?>
            <div class="form-actions">
                <a href="downloads.php" class="admin-btn">Hemen İndirme Yönetimine Dön</a>
            </div>
        <?php endif; ?>
    </div>

    <aside class="side-info">
        <div class="info-box">
            <strong>EXE Dosya Yönetimi</strong>
            <span>Oyun kurulum dosyası doğrudan yüklenebilir veya harici indirme bağlantısı girilebilir.</span>
        </div>

        <div class="info-box">
            <strong>Yükleme Klasörü</strong>
            <span>Yüklenen dosyalar uploads/downloads klasörüne kaydedilir.</span>
        </div>

        <div class="info-box">
            <strong>Sürüm Takibi</strong>
            <span>Her indirme kaydına sürüm numarası ekleyerek oyunculara güncel dosya sunabilirsiniz.</span>
        </div>
    </aside>

</section>

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