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

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

// KATEGORİLERİ ÇEK
$categories = $db->query("SELECT * FROM blog_categories ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

// TÜM ETİKETLERİ ÇEK (Öneri sistemi için)
$tags_query = $db->query("SELECT name FROM blog_tags ORDER BY name ASC")->fetchAll(PDO::FETCH_COLUMN);
$tags_json = json_encode($tags_query); // JS'ye aktarmak için JSON formatı

// SEO Fonksiyonu
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'dan gelen veri JSON formatındadır: [{"value":"teknoloji"}, {"value":"yeni"}]
    $tags_input = isset($_POST['tags']) ? $_POST['tags'] : ''; 
    $tags_array = json_decode($tags_input, true); 

    $slug = seo_url($title);

    // Görsel Yükleme
    $image_name = "";
    if (isset($_FILES["image"]) && $_FILES["image"]["error"] == 0) {
        $target_dir = "assets/images/uploads/";
        if (!file_exists($target_dir)) { mkdir($target_dir, 0777, true); }
        $file_ext = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
        $image_name = $slug . "-" . time() . "." . $file_ext;
        move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir . $image_name);
    }

    if (!empty($title) && !empty($content)) {
        // 1. Yazıyı Kaydet
        $sql = "INSERT INTO blog_posts (title, slug, category_id, short_desc, content, image, status) VALUES (:title, :slug, :cat, :desc, :cont, :img, :stat)";
        $stmt = $db->prepare($sql);
        $result = $stmt->execute([
            'title' => $title, 'slug' => $slug, 'cat' => $cat_id, 'desc' => $short_desc, 
            'cont' => $content, 'img' => $image_name, 'stat' => $status
        ]);
        
        $post_id = $db->lastInsertId();

        // 2. ETİKETLERİ İŞLE
        if ($result && !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;

                // Etiket var mı kontrol et
                $check = $db->prepare("SELECT id FROM blog_tags WHERE name = ?");
                $check->execute([$tag_name]);
                $existing_tag = $check->fetch(PDO::FETCH_ASSOC);

                if ($existing_tag) {
                    // Varsa ID'sini al
                    $tag_id = $existing_tag['id'];
                } else {
                    // Yoksa YENİ OLUŞTUR ve ID'sini al
                    $create = $db->prepare("INSERT INTO blog_tags (name) VALUES (?)");
                    $create->execute([$tag_name]);
                    $tag_id = $db->lastInsertId();
                }

                // İlişkiyi kaydet
                $insert_rel->execute([$post_id, $tag_id]);
            }
        }

        if ($result) {
            $mesaj = "Yazı başarıyla yayınlandı!";
            $mesaj_tur = "success";
        } else {
            $mesaj = "Hata oluştu.";
            $mesaj_tur = "danger";
        }
    } else {
        $mesaj = "Başlık ve İçerik zorunludur.";
        $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">Yeni Yazı Ekle</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" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-semibold">İçerik</label>
                                    <textarea name="content" id="summernote" required></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"></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['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" placeholder="Etiket yazıp Enter'a basın...">
                                    <small class="text-secondary-light">Mevcut etiketleri seçebilir veya yenisini yazıp Enter'a basarak ekleyebilirsiniz.</small>
                                </div>

                                <div class="mb-4">
                                    <label class="form-label fw-semibold">Durum</label>
                                    <select name="status" class="form-control radius-8">
                                        <option value="published">Yayında</option>
                                        <option value="draft">Taslak</option>
                                    </select>
                                </div>

                                <div class="mb-4">
                                    <label class="form-label fw-semibold">Kapak Görseli</label>
                                    <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">Yayınla</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 Başlat
        $('#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 AYARLARI ---
        var input = document.querySelector('input[name=tags]');
        
        // PHP'den gelen etiket listesi (Whitelist)
        var whitelist = <?php echo $tags_json; ?>;

        var tagify = new Tagify(input, {
            whitelist: whitelist,
            maxTags: 10,
            dropdown: {
                maxItems: 20,           // En fazla kaç öneri görünsün
                classname: "tags-look", // Özel stil sınıfı
                enabled: 0,             // 0: Yazmaya başlar başlamaz öneri göster
                closeOnSelect: false    // Seçince listeyi kapatma
            }
        });
    </script>
</body>
</html>