<?php
require_once __DIR__ . 
'/../includes/config.php';
yetkili_mi("admin"); // Sadece adminler erişebilir

$sayfa_baslik = __("edit_user");

$kullanici_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$kullanici_id) {
    $_SESSION['hata'] = __("invalid_user_id");
    header('Location: kullanicilar.php');
    exit();
}

$kullanici = null;
try {
    $stmt = $db->prepare("SELECT id, kullanici_adi, ad_soyad, yetki_seviyesi, aktif FROM kullanicilar WHERE id = ?");
    $stmt->execute([$kullanici_id]);
    $kullanici = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$kullanici) {
        $_SESSION['hata'] = __("user_not_found");
        header('Location: kullanicilar.php');
        exit();
    }
} catch (PDOException $e) {
    error_log("Kullanıcı çekme hatası: " . $e->getMessage());
    $_SESSION['hata'] = __("error_loading_user");
    header('Location: kullanicilar.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!csrf_token_dogrula($_POST['csrf_token'] ?? '')) {
        $_SESSION['hata'] = __("invalid_form_submission");
        header("Location: kullanici_duzenle.php?id=" . $kullanici_id);
        exit();
    }

    $kullanici_adi = temizle($_POST['kullanici_adi'] ?? '');
    $ad_soyad = temizle($_POST['ad_soyad'] ?? '');
    $yetki_seviyesi = temizle($_POST['yetki_seviyesi'] ?? '');
    $aktif = isset($_POST['aktif']) ? 1 : 0;
    $sifre = $_POST['sifre'] ?? '';
    $sifre_tekrar = $_POST['sifre_tekrar'] ?? '';

    $hatalar = [];
    if (empty($kullanici_adi)) $hatalar[] = __("username_required");
    if (empty($ad_soyad)) $hatalar[] = __("full_name_required");
    if (empty($yetki_seviyesi)) $hatalar[] = __("permission_level_required");

    // Şifre değiştirme kontrolü
    if (!empty($sifre)) {
        if (strlen($sifre) < 6) {
            $hatalar[] = __("password_min_length");
        }
        if ($sifre !== $sifre_tekrar) {
            $hatalar[] = __("passwords_do_not_match");
        }
    }

    if (empty($hatalar)) {
        try {
            $sql = "UPDATE kullanicilar SET kullanici_adi = ?, ad_soyad = ?, yetki_seviyesi = ?, aktif = ?";
            $params = [$kullanici_adi, $ad_soyad, $yetki_seviyesi, $aktif];

            if (!empty($sifre)) {
                $hashed_sifre = password_hash($sifre, PASSWORD_DEFAULT);
                $sql .= ", sifre = ?";
                $params[] = $hashed_sifre;
            }

            $sql .= " WHERE id = ?";
            $params[] = $kullanici_id;

            $stmt = $db->prepare($sql);
            $stmt->execute($params);

            $_SESSION['mesaj'] = __("user_updated_successfully");
            header("Location: kullanicilar.php");
            exit();
        } catch (PDOException $e) {
            error_log("Kullanıcı güncelleme hatası: " . $e->getMessage());
            $_SESSION['hata'] = __("error_updating_user");
            header("Location: kullanici_duzenle.php?id=" . $kullanici_id);
            exit();
        }
    } else {
        $_SESSION['form_hatalari_kullanici_duzenle'] = $hatalar;
        $_SESSION['form_verileri_kullanici_duzenle'] = $_POST;
        header("Location: kullanici_duzenle.php?id=" . $kullanici_id);
        exit();
    }
}

$csrf_token = csrf_token_olustur();
$form_hatalari = $_SESSION['form_hatalari_kullanici_duzenle'] ?? [];
$form_verileri = $_SESSION['form_verileri_kullanici_duzenle'] ?? $kullanici;
unset($_SESSION['form_hatalari_kullanici_duzenle'], $_SESSION['form_verileri_kullanici_duzenle']);
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= __("odjoo_management") ?> - <?= temizle($sayfa_baslik) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <h2><i class="bi bi-person-gear"></i> <?= temizle($sayfa_baslik) ?></h2>
        <hr>

        <?php if (!empty($form_hatalari)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <strong><i class="bi bi-exclamation-triangle-fill me-2"></i> <?= __("please_correct_errors") ?>:</strong>
                <ul>
                    <?php foreach ($form_hatalari as $hata): ?>
                        <li><?= htmlspecialchars($hata) ?></li>
                    <?php endforeach; ?>
                </ul>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
            <div class="card shadow-sm">
                <div class="card-body">
                    <div class="mb-3">
                        <label for="kullanici_adi" class="form-label"><?= __("username") ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="kullanici_adi" name="kullanici_adi" value="<?= htmlspecialchars($form_verileri['kullanici_adi'] ?? '', ENT_QUOTES) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="ad_soyad" class="form-label"><?= __("full_name") ?> <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="ad_soyad" name="ad_soyad" value="<?= htmlspecialchars($form_verileri['ad_soyad'] ?? '', ENT_QUOTES) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="yetki_seviyesi" class="form-label"><?= __("permission_level") ?> <span class="text-danger">*</span></label>
                        <select class="form-select" id="yetki_seviyesi" name="yetki_seviyesi" required>
                            <option value="admin" <?= (isset($form_verileri['yetki_seviyesi']) && $form_verileri['yetki_seviyesi'] == 'admin') ? 'selected' : '' ?>><?= __("admin") ?></option>
                            <option value="yonetici" <?= (isset($form_verileri['yetki_seviyesi']) && $form_verileri['yetki_seviyesi'] == 'yonetici') ? 'selected' : '' ?>><?= __("manager") ?></option>
                            <option value="kullanici" <?= (isset($form_verileri['yetki_seviyesi']) && $form_verileri['yetki_seviyesi'] == 'kullanici') ? 'selected' : '' ?>><?= __("user") ?></option>
                            <option value="misafir" <?= (isset($form_verileri['yetki_seviyesi']) && $form_verileri['yetki_seviyesi'] == 'misafir') ? 'selected' : '' ?>><?= __("guest") ?></option>
                        </select>
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="aktif" name="aktif" value="1" <?= (isset($form_verileri['aktif']) && $form_verileri['aktif'] == 1) ? 'checked' : '' ?>>
                        <label class="form-check-label" for="aktif"><?= __("active") ?></label>
                    </div>
                    <div class="mb-3">
                        <label for="sifre" class="form-label"><?= __("new_password_leave_blank") ?></label>
                        <input type="password" class="form-control" id="sifre" name="sifre">
                    </div>
                    <div class="mb-3">
                        <label for="sifre_tekrar" class="form-label"><?= __("confirm_new_password") ?></label>
                        <input type="password" class="form-control" id="sifre_tekrar" name="sifre_tekrar">
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i> <?= __("update_user") ?>
                    </button>
                    <a href="kullanicilar.php" class="btn btn-secondary"><i class="bi bi-arrow-left me-2"></i> <?= __("go_back") ?></a>
                </div>
            </div>
        </form>
    </div>

    <?php include __DIR__ . '/../includes/footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

