<?php
session_start();
require_once 'system/db.php';

if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) {
    header("Location: login.php"); exit;
}

if (!isset($_GET['id'])) { header("Location: blogs.php"); exit; }
$id = intval($_GET['id']);

$post = $db->query("SELECT * FROM blog_posts WHERE id = $id")->fetch(PDO::FETCH_ASSOC);
if (!$post) { header("Location: blogs.php"); exit; }

// Mevcut etiketleri İSİM olarak çek (Tagify için virgülle ayrılmış string lazım değil, array de olur ama value key ile)
$current_tags = $db->query("SELECT t.name as value FROM blog_post_tags pt JOIN blog_tags t ON pt.tag_id = t.id WHERE pt.post_id = $id")->fetchAll(PDO::FETCH_ASSOC);
$current_tags_json = json_encode($current_tags); // JS'ye aktar: [{"value":"php"}, {"value":"kod"}]

// Tüm etiket listesi (Öneri için)
$all_tags_query = $db->query("SELECT name FROM blog_tags ORDER BY name ASC")->fetchAll(PDO::FETCH_COLUMN);
$all_tags_json = json_encode($all_tags_query);

$categories = $db->query("SELECT * FROM blog_categories ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

function seo_url($str) {
    $str = mb_strtolower($str, 'UTF-8');
    $str = str_replace(['ı','ğ','ü','ş','ö','ç'], ['i','g','u','s','o','c'], $str);
    $str = preg_replace('/[^a-z0-9\-]/', '-', $str);
    return trim($str, '-');
}

$mesaj = "";
$mesaj_tur = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST['title']);
    $content = $_POST['content'];
    $short_desc = trim($_POST['short_desc']);
    $status = $_POST['status'];
    $cat_id = intval($_POST['category_id']);
    
    // Tagify verisi
    $tags_input = isset($_POST['tags']) ? $_POST['tags'] : ''; 
    $tags_array = json_decode($tags_input, true);

    $slug = seo_url($title);

    $image_name = $post['image'];
    if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) {
        $target_dir = "assets/images/uploads/";
        $file_ext = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
        $new_image_name = $slug . "-" . time() . "." . $file_ext;
        if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir . $new_image_name)){
            $image_name = $new_image_name;
        }
    }

    if (!empty($title) && !empty($content)) {
        $sql = "UPDATE blog_posts SET title=?, slug=?, category_id=?, short_desc=?, content=?, image=?, status=? WHERE id=?";
        $stmt = $db->prepare($sql);
        $update = $stmt->execute([$title, $slug, $cat_id, $short_desc, $content, $image_name, $status, $id]);

        if ($update) {
            // ETİKETLERİ GÜNCELLE
            // 1. Eskileri sil
            $db->query("DELETE FROM blog_post_tags WHERE post_id = $id");
            
            // 2. Yenileri ekle (Varsa bul, yoksa oluştur)
            if (!empty($tags_array)) {
                $insert_rel = $db->prepare("INSERT INTO blog_post_tags (post_id, tag_id) VALUES (?, ?)");
                
                foreach ($tags_array as $item) {
                    $tag_name = trim($item['value']);
                    if(empty($tag_name)) continue;

                    $check = $db->prepare("SELECT id FROM blog_tags WHERE name = ?");
                    $check->execute([$tag_name]);
                    $existing_tag = $check->fetch(PDO::FETCH_ASSOC);

                    if ($existing_tag) {
                        $tag_id = $existing_tag['id'];
                    } else {
                        $create = $db->prepare("INSERT INTO blog_tags (name) VALUES (?)");
                        $create->execute([$tag_name]);
                        $tag_id = $db->lastInsertId();
                    }
                    $insert_rel->execute([$id, $tag_id]);
                }
            }
            
            $mesaj = "Güncelleme başarılı.";
            $mesaj_tur = "success";
            
            // Verileri tazele
            $post = $db->query("SELECT * FROM blog_posts WHERE id = $id")->fetch(PDO::FETCH_ASSOC);
            $current_tags = $db->query("SELECT t.name as value FROM blog_post_tags pt JOIN blog_tags t ON pt.tag_id = t.id WHERE pt.post_id = $id")->fetchAll(PDO::FETCH_ASSOC);
            $current_tags_json = json_encode($current_tags);
        } else {
            $mesaj = "Hata oluştu.";
            $mesaj_tur = "danger";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="tr" data-theme="light">
<?php include 'inc/header.php'; ?>
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css" rel="stylesheet" type="text/css" />

<body>
    <?php include 'inc/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'inc/navbar.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Yazıyı Düzenle</h6>
                <a href="blogs.php" class="btn btn-outline-primary px-4 py-2 radius-8">Listeye Dön</a>
            </div>

            <?php if($mesaj != ""): ?>
                <div class="alert alert-<?php echo $mesaj_tur; ?> px-3 py-2 radius-8 mb-3"><?php echo $mesaj; ?></div>
            <?php endif; ?>

            <form action="" method="POST" enctype="multipart/form-data">
                <div class="row gy-4">
                    <div class="col-lg-8">
                        <div class="card h-100 p-0 radius-12">
                            <div class="card-body p-24">
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Başlık</label>
                                    <input type="text" name="title" class="form-control radius-8 fw-bold" value="<?php echo htmlspecialchars($post['title']); ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">İçerik</label>
                                    <textarea name="content" id="summernote" required><?php echo $post['content']; ?></textarea>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">Kısa Açıklama</label>
                                    <textarea name="short_desc" class="form-control radius-8" rows="3"><?php echo htmlspecialchars($post['short_desc']); ?></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <div class="card h-100 p-0 radius-12">
                            <div class="card-header border-bottom bg-base py-16 px-24">
                                <h6 class="text-lg fw-semibold mb-0">Detaylar</h6>
                            </div>
                            <div class="card-body p-24">
                                <div class="mb-4">
                                    <label class="form-label fw-semibold">Kategori</label>
                                    <select name="category_id" class="form-control radius-8">
                                        <option value="0">Genel</option>
                                        <?php foreach($categories as $cat): ?>
                                            <option value="<?php echo $cat['id']; ?>" <?php echo ($cat['id'] == $post['category_id']) ? 'selected' : ''; ?>>
                                                <?php echo $cat['name']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="mb-4">
                                    <label class="form-label fw-semibold">Etiketler</label>
                                    <input name="tags" class="form-control radius-8" value='<?php echo $current_tags_json; ?>' placeholder="Etiket ekle...">
                                </div>

                                <div class="mb-4">
                                    <label class="form-label fw-semibold">Durum</label>
                                    <select name="status" class="form-control radius-8">
                                        <option value="published" <?php echo ($post['status'] == 'published') ? 'selected' : ''; ?>>Yayında</option>
                                        <option value="draft" <?php echo ($post['status'] == 'draft') ? 'selected' : ''; ?>>Taslak</option>
                                    </select>
                                </div>

                                <div class="mb-4">
                                    <label class="form-label fw-semibold">Kapak Görseli</label>
                                    <?php if(!empty($post['image'])): ?>
                                        <div class="mb-2"><img src="assets/images/uploads/<?php echo $post['image']; ?>" class="w-100 radius-8" style="max-height:150px; object-fit:cover;"></div>
                                    <?php endif; ?>
                                    <input type="file" name="image" class="form-control radius-8">
                                </div>

                                <button type="submit" class="btn btn-primary w-100 py-2 radius-8 fw-bold">Kaydet</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <?php include 'inc/copyright.php'; ?>
    </main>
    <?php include 'inc/footer.php'; ?>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify"></script>
    <script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.polyfills.min.js"></script>
    
    <script>
        $('#summernote').summernote({
            placeholder: 'İçerik...', tabsize: 2, height: 300,
            toolbar: [['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['para', ['ul', 'ol', 'paragraph']], ['insert', ['link', 'picture']], ['view', ['fullscreen', 'codeview']]]
        });

        // --- TAGIFY ---
        var input = document.querySelector('input[name=tags]');
        var whitelist = <?php echo $all_tags_json; ?>;

        var tagify = new Tagify(input, {
            whitelist: whitelist,
            maxTags: 10,
            dropdown: {
                maxItems: 20,
                classname: "tags-look",
                enabled: 0,
                closeOnSelect: false
            }
        });
    </script>
</body>
</html>