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

/*
|--------------------------------------------------------------------------
| YÖNETİCİ DÜZENLEME EKRANI
|--------------------------------------------------------------------------
| manager-edit.php
| Okey Platformu Yönetici Bilgileri Düzenleme Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Yönetici Düzenle';
$pageDescription = 'Okey Platformu yönetici hesabını düzenleyin.';

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

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

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

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

function manager_edit_value(?array $user, string $key, string $default = ''): string
{
    if (!$user) {
        return $default;
    }

    return isset($user[$key]) ? (string)$user[$key] : $default;
}

function manager_edit_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 '';
}

function manager_edit_image(?array $user): string
{
    $image = manager_edit_value($user, 'image', '');

    if ($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/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';
}

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

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

    $columns = manager_edit_columns($pdo);

    $stmt = $pdo->prepare("
        SELECT *
        FROM users
        WHERE id = ?
        AND role IN ('admin','superadmin','super_admin','owner')
        LIMIT 1
    ");
    $stmt->execute([$id]);
    $manager = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$manager) {
        throw new RuntimeException('Yönetici kaydı bulunamadı.');
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $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 === '') {
            throw new RuntimeException('Ad soyad ve kullanıcı adı zorunludur.');
        }

        if (manager_edit_has($columns, 'username')) {
            $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? AND id != ?");
            $check->execute([$username, $id]);

            if ((int)$check->fetchColumn() > 0) {
                throw new RuntimeException('Bu kullanıcı adı başka bir hesapta kullanılıyor.');
            }
        }

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

            if ((int)$check->fetchColumn() > 0) {
                throw new RuntimeException('Bu e-posta başka bir hesapta kullanılıyor.');
            }
        }

        $update = [];

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

        if (manager_edit_has($columns, 'username')) {
            $update['username'] = $username;
        }

        if (manager_edit_has($columns, 'email')) {
            $update['email'] = $email;
        }

        if (manager_edit_has($columns, 'phone')) {
            $update['phone'] = $phone;
        }

        if ($password !== '' && manager_edit_has($columns, 'password')) {
            $update['password'] = password_hash($password, PASSWORD_DEFAULT);
        }

        if (manager_edit_has($columns, 'role')) {
            $update['role'] = $role;
        }

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

        $image = manager_edit_upload_image('image');

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

        if (manager_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 users SET " . implode(', ', $set) . " WHERE id = ? LIMIT 1";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($values);

        $message = 'Yönetici bilgileri başarıyla güncellendi.';
        $messageType = 'success';

        $stmt = $pdo->prepare("
            SELECT *
            FROM users
            WHERE id = ?
            AND role IN ('admin','superadmin','super_admin','owner')
            LIMIT 1
        ");
        $stmt->execute([$id]);
        $manager = $stmt->fetch(PDO::FETCH_ASSOC);
    }
} catch (Throwable $e) {
    $message = $e->getMessage();
    $messageType = 'error';
}
?>

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

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

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

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

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

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

.profile-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);
    text-align:center;
}

.profile-image{
    width:120px;
    height:120px;
    margin:0 auto 15px;
    padding:4px;
    border-radius:50%;
    background:linear-gradient(135deg,#f5b642,#b90000);
}

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

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

.profile-box span{
    display:block;
    color:#9aa3b2;
    font-size:13px;
    font-weight:800;
}

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

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

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

    <div class="manager-edit-card">
        <h2>Yönetici Bilgilerini Düzenle</h2>
        <p>Yönetici hesabının temel bilgilerini, yetki rolünü, durumunu ve profil resmini düzenleyebilirsiniz.</p>

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

        <?php if ($manager): ?>
            <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(manager_edit_value($manager, 'name')) ?>" required>
                    </div>

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

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

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

                    <div class="form-group">
                        <label>Yeni Şifre</label>
                        <input type="password" name="password" class="form-control" placeholder="Boş bırakılırsa değişmez">
                    </div>

                    <div class="form-group">
                        <label>Yönetici Rolü</label>
                        <?php $currentRole = manager_edit_value($manager, 'role', 'admin'); ?>
                        <select name="role" class="form-control">
                            <option value="admin" <?= $currentRole === 'admin' ? 'selected' : '' ?>>Yönetici</option>
                            <option value="superadmin" <?= in_array($currentRole, ['superadmin', 'super_admin'], true) ? 'selected' : '' ?>>Süper Yönetici</option>
                            <option value="owner" <?= $currentRole === 'owner' ? 'selected' : '' ?>>Kurucu</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Durum</label>
                        <?php $currentStatus = manager_edit_value($manager, '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 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">Değişiklikleri Kaydet</button>
                    <a href="managers.php" class="admin-btn admin-btn-dark">Listeye Dön</a>
                </div>

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

    <aside class="profile-side">
        <div class="profile-box">
            <div class="profile-image">
                <img src="<?= admin_e(manager_edit_image($manager)) ?>" alt="Yönetici">
            </div>

            <strong><?= admin_e(manager_edit_value($manager, 'name', 'Yönetici')) ?></strong>
            <span><?= admin_e(manager_edit_value($manager, 'email', 'E-posta yok')) ?></span>
        </div>

        <div class="info-box">
            <strong>Şifre Değişimi</strong>
            <span>Yeni şifre alanı boş bırakılırsa mevcut şifre korunur.</span>
        </div>

        <div class="info-box">
            <strong>Profil Resmi</strong>
            <span>Yeni resim yüklerseniz mevcut yönetici resmi güncellenir.</span>
        </div>

        <div class="info-box">
            <strong>Yetki Kontrolü</strong>
            <span>Yönetici rolünü değiştirirken panel erişim yetkilerini dikkatli kullanın.</span>
        </div>
    </aside>

</section>

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