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

/*
|--------------------------------------------------------------------------
| YÖNETİCİ OLUŞTURMA EKRANI
|--------------------------------------------------------------------------
| manager-view.php
| Okey Platformu Yeni Yönetici Oluşturma Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Yeni Yönetici Oluştur';
$pageDescription = 'Okey Platformu için yeni yönetici hesabı oluşturun.';

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

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

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

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

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

    return $columns;
}

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

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

    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $ext = strtolower(pathinfo((string)$_FILES[$field]['name'], PATHINFO_EXTENSION));

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

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

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

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

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

    return '';
}

$columns = [];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($pdo) && $pdo instanceof PDO) {
    $name     = trim((string)($_POST['name'] ?? ''));
    $username = trim((string)($_POST['username'] ?? ''));
    $email    = trim((string)($_POST['email'] ?? ''));
    $phone    = trim((string)($_POST['phone'] ?? ''));
    $password = trim((string)($_POST['password'] ?? ''));
    $role     = trim((string)($_POST['role'] ?? 'admin'));
    $status   = trim((string)($_POST['status'] ?? 'active'));

    if ($name === '' || $username === '' || $password === '') {
        $message = 'Ad soyad, kullanıcı adı ve şifre zorunludur.';
        $messageType = 'error';
    } else {
        try {
            if (manager_view_has($columns, 'username')) {
                $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
                $check->execute([$username]);

                if ((int)$check->fetchColumn() > 0) {
                    throw new RuntimeException('Bu kullanıcı adı zaten kayıtlı.');
                }
            }

            if ($email !== '' && manager_view_has($columns, 'email')) {
                $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
                $check->execute([$email]);

                if ((int)$check->fetchColumn() > 0) {
                    throw new RuntimeException('Bu e-posta adresi zaten kayıtlı.');
                }
            }

            $image = manager_view_upload_image('image');

            $insert = [];

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

            if (manager_view_has($columns, 'username')) {
                $insert['username'] = $username;
            }

            if (manager_view_has($columns, 'email')) {
                $insert['email'] = $email;
            }

            if (manager_view_has($columns, 'phone')) {
                $insert['phone'] = $phone;
            }

            if (manager_view_has($columns, 'password')) {
                $insert['password'] = password_hash($password, PASSWORD_DEFAULT);
            }

            if (manager_view_has($columns, 'role')) {
                $insert['role'] = $role;
            }

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

            if ($image !== '' && manager_view_has($columns, 'image')) {
                $insert['image'] = $image;
            }

            if (manager_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 users (`" . implode('`,`', $fields) . "`) VALUES (" . implode(',', $placeholders) . ")";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(array_values($insert));

            $message = 'Yönetici başarıyla oluşturuldu. 10 saniye sonra yönetici 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=managers.php">
<?php endif; ?>

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

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

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

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

.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){
    .manager-form-shell{
        grid-template-columns:1fr;
    }

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

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

    <div class="manager-form-card">
        <h2>Yeni Yönetici Oluştur</h2>
        <p>Panel erişimi olacak yeni yönetici hesabını buradan 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>Ad Soyad</label>
                        <input type="text" name="name" class="form-control" value="<?= admin_e($_POST['name'] ?? '') ?>" required>
                    </div>

                    <div class="form-group">
                        <label>Kullanıcı Adı</label>
                        <input type="text" name="username" class="form-control" value="<?= admin_e($_POST['username'] ?? '') ?>" required>
                    </div>

                    <div class="form-group">
                        <label>E-Posta</label>
                        <input type="email" name="email" class="form-control" value="<?= admin_e($_POST['email'] ?? '') ?>">
                    </div>

                    <div class="form-group">
                        <label>Telefon</label>
                        <input type="text" name="phone" class="form-control" value="<?= admin_e($_POST['phone'] ?? '') ?>">
                    </div>

                    <div class="form-group">
                        <label>Şifre</label>
                        <input type="password" name="password" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Yönetici Rolü</label>
                        <select name="role" class="form-control">
                            <option value="admin" <?= (($_POST['role'] ?? 'admin') === 'admin') ? 'selected' : '' ?>>Yönetici</option>
                            <option value="superadmin" <?= (($_POST['role'] ?? '') === 'superadmin') ? 'selected' : '' ?>>Süper Yönetici</option>
                            <option value="owner" <?= (($_POST['role'] ?? '') === 'owner') ? 'selected' : '' ?>>Kurucu</option>
                        </select>
                    </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 class="form-group">
                        <label>Yönetici Resmi</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                    </div>

                </div>

                <div class="form-actions">
                    <button type="submit" class="admin-btn">Yöneticiyi Oluştur</button>
                    <a href="managers.php" class="admin-btn admin-btn-dark">Listeye Dön</a>
                </div>

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

    <aside class="side-info">
        <div class="info-box">
            <strong>Yönetici Yetkisi</strong>
            <span>Bu alandan oluşturulan hesaplar admin paneline erişim sağlayabilir.</span>
        </div>

        <div class="info-box">
            <strong>Profil Resmi</strong>
            <span>Yüklenen yönetici görselleri uploads/users klasörüne kaydedilir.</span>
        </div>

        <div class="info-box">
            <strong>Güvenli Şifre</strong>
            <span>Şifreler otomatik olarak hashlenir ve güvenli şekilde kaydedilir.</span>
        </div>
    </aside>

</section>

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