<?php
/**
 * إضافة منشور جديد
 */

session_start();
require_once '../../config/database.php';

$database = new Database();
$conn = $database->getConnection();

// معالجة الإرسال
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = $_POST['title'];
    $slug = $_POST['slug'] ?: strtolower(str_replace(' ', '-', $title));
    $excerpt = $_POST['excerpt'];
    $content = $_POST['content'];
    $category = $_POST['category'];
    $tags = $_POST['tags'];
    $status = $_POST['status'];
    $is_featured = isset($_POST['is_featured']) ? 1 : 0;
    $published_at = $status == 'published' ? date('Y-m-d H:i:s') : null;
    
    // رفع الصورة
    $featured_image = '';
    if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] == 0) {
        $upload_dir = '../../uploads/posts/';
        $file_name = time() . '_' . $_FILES['featured_image']['name'];
        $target_file = $upload_dir . $file_name;
        
        if (move_uploaded_file($_FILES['featured_image']['tmp_name'], $target_file)) {
            $featured_image = 'uploads/posts/' . $file_name;
        }
    }
    
    try {
        $stmt = $conn->prepare("INSERT INTO posts (title, slug, excerpt, content, featured_image, author_id, category, tags, status, is_featured, published_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $title,
            $slug,
            $excerpt,
            $content,
            $featured_image,
            $_SESSION['admin_id'],
            $category,
            $tags,
            $status,
            $is_featured,
            $published_at
        ]);
        
        header('Location: index.php?msg=created');
        exit;
    } catch (PDOException $e) {
        $error = "خطأ: " . $e->getMessage();
    }
}

// جلب الفئات
$categories = $conn->query("SELECT * FROM post_categories WHERE is_active = 1 ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

$page_title = 'منشور جديد';
include '../includes/header.php';
?>

<style>
.post-create-container {
    max-width: 1400px;
    margin: 0 auto;
}

.post-grid {
    display: grid;
    grid-template-columns: 1fr 380px;
    gap: 24px;
    margin-top: 24px;
}

.post-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    margin-bottom: 20px;
}

.post-card h3 {
    font-size: 16px;
    font-weight: 600;
    color: #1f2937;
    margin: 0 0 16px 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group:last-child {
    margin-bottom: 0;
}

.form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #374151;
    font-size: 14px;
}

.form-input,
.form-textarea,
.form-select {
    width: 100%;
    padding: 12px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    font-size: 14px;
    font-family: 'Tajawal', sans-serif;
    transition: all 0.2s;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-input.large {
    font-size: 18px;
    font-weight: 500;
    padding: 14px;
}

.form-textarea {
    resize: vertical;
    min-height: 120px;
}

.form-textarea.large {
    min-height: 400px;
    font-size: 15px;
    line-height: 1.7;
}

.form-hint {
    display: block;
    margin-top: 6px;
    font-size: 13px;
    color: #6b7280;
}

.toolbar {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    padding: 12px;
    background: #f9fafb;
    border-radius: 8px;
}

.toolbar-btn {
    padding: 8px 12px;
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 6px;
}

.toolbar-btn:hover {
    background: #f3f4f6;
    border-color: #d1d5db;
}

.btn-publish {
    width: 100%;
    padding: 12px;
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.btn-publish:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.btn-back {
    padding: 10px 20px;
    background: white;
    color: #6b7280;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    transition: all 0.2s;
}

.btn-back:hover {
    background: #f9fafb;
    color: #374151;
}

.checkbox-label {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    padding: 12px;
    background: #f9fafb;
    border-radius: 8px;
    transition: all 0.2s;
}

.checkbox-label:hover {
    background: #f3f4f6;
}

.checkbox-label input[type="checkbox"] {
    width: 18px;
    height: 18px;
    cursor: pointer;
}

.image-upload {
    position: relative;
    border: 2px dashed #e5e7eb;
    border-radius: 8px;
    padding: 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
}

.image-upload:hover {
    border-color: #3b82f6;
    background: #f9fafb;
}

.image-upload input[type="file"] {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    opacity: 0;
    cursor: pointer;
}

.image-preview {
    margin-top: 16px;
    border-radius: 8px;
    overflow: hidden;
}

.image-preview img {
    width: 100%;
    display: block;
}

.alert {
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.alert-danger {
    background: #fef2f2;
    color: #991b1b;
    border: 1px solid #fecaca;
}

@media (max-width: 1024px) {
    .post-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<div class="post-create-container">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h1 style="font-size: 28px; font-weight: 700; color: #1f2937; margin: 0;">
            ✍️ منشور جديد
        </h1>
        <a href="index.php" class="btn-back">
            <i class="fas fa-arrow-right"></i>
            رجوع
        </a>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle"></i>
            <?php echo $error; ?>
        </div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <div class="post-grid">
            <!-- العمود الرئيسي -->
            <div>
                <!-- العنوان -->
                <div class="post-card">
                    <div class="form-group">
                        <label class="form-label">عنوان المنشور *</label>
                        <input type="text" name="title" required 
                               class="form-input large"
                               placeholder="اكتب عنوان جذاب للمنشور...">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">الرابط (Slug)</label>
                        <input type="text" name="slug" 
                               class="form-input"
                               placeholder="يتم إنشاؤه تلقائياً من العنوان">
                        <small class="form-hint">مثال: my-first-post</small>
                    </div>
                </div>

                <!-- المحتوى -->
                <div class="post-card">
                    <div class="form-group">
                        <label class="form-label">ملخص المنشور</label>
                        <textarea name="excerpt" 
                                  class="form-textarea"
                                  placeholder="ملخص قصير يظهر في قائمة المنشورات..."></textarea>
                        <small class="form-hint">يظهر في البطاقات وفي محركات البحث</small>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">المحتوى *</label>
                        
                        <!-- أزرار التنسيق -->
                        <div class="toolbar">
                            <button type="button" onclick="insertTag('h2', 'عنوان رئيسي')" class="toolbar-btn">
                                <i class="fas fa-heading"></i> عنوان
                            </button>
                            <button type="button" onclick="insertTag('strong', 'نص عريض')" class="toolbar-btn">
                                <i class="fas fa-bold"></i> عريض
                            </button>
                            <button type="button" onclick="insertTag('em', 'نص مائل')" class="toolbar-btn">
                                <i class="fas fa-italic"></i> مائل
                            </button>
                            <button type="button" onclick="insertList('ul')" class="toolbar-btn">
                                <i class="fas fa-list-ul"></i> قائمة
                            </button>
                            <button type="button" onclick="insertList('ol')" class="toolbar-btn">
                                <i class="fas fa-list-ol"></i> مرقمة
                            </button>
                            <button type="button" onclick="insertTag('a', 'رابط', 'href=\"#/"')" class="toolbar-btn">
                                <i class="fas fa-link"></i> رابط
                            </button>
                        </div>
                        
                        <textarea name="content" id="content" required
                                  class="form-textarea large"
                                  placeholder="اكتب محتوى المنشور هنا..."></textarea>
                        <small class="form-hint">يمكنك استخدام HTML للتنسيق المتقدم</small>
                    </div>
                </div>
            </div>

            <!-- الشريط الجانبي -->
            <div>
                <!-- النشر -->
                <div class="post-card">
                    <h3>📤 النشر</h3>
                    
                    <div class="form-group">
                        <label class="form-label">الحالة</label>
                        <select name="status" class="form-select">
                            <option value="draft">📝 مسودة</option>
                            <option value="published">✅ نشر الآن</option>
                            <option value="scheduled">⏰ جدولة</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="is_featured">
                            <span>⭐ منشور مميز</span>
                        </label>
                    </div>
                    
                    <button type="submit" class="btn-publish">
                        <i class="fas fa-check"></i>
                        حفظ المنشور
                    </button>
                </div>

                <!-- الفئة -->
                <div class="post-card">
                    <h3>📁 الفئة</h3>
                    <select name="category" required class="form-select">
                        <option value="">اختر الفئة</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['name']; ?>">
                                <?php echo $cat['icon'] . ' ' . $cat['name']; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- الوسوم -->
                <div class="post-card">
                    <h3>🏷️ الوسوم</h3>
                    <input type="text" name="tags" 
                           class="form-input"
                           placeholder="مثال: جمال, عناية, بشرة">
                    <small class="form-hint">افصل بين الوسوم بفاصلة</small>
                </div>

                <!-- الصورة المميزة -->
                <div class="post-card">
                    <h3>🖼️ الصورة المميزة</h3>
                    <div class="image-upload">
                        <input type="file" name="featured_image" accept="image/*" 
                               onchange="previewImage(this)">
                        <i class="fas fa-cloud-upload-alt" style="font-size: 32px; color: #9ca3af; margin-bottom: 8px;"></i>
                        <p style="margin: 0; color: #6b7280; font-size: 14px;">اضغط لاختيار صورة</p>
                    </div>
                    <div id="imagePreview" class="image-preview" style="display: none;">
                        <img id="preview">
                    </div>
                    <small class="form-hint">الحجم الموصى به: 1200×630 بكسل</small>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
// معاينة الصورة
function previewImage(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('imagePreview').style.display = 'block';
            document.getElementById('preview').src = e.target.result;
        }
        reader.readAsDataURL(input.files[0]);
    }
}

// إدراج تاج HTML
function insertTag(tag, placeholder, attrs = '') {
    const textarea = document.getElementById('content');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selectedText = textarea.value.substring(start, end) || placeholder;
    const attrStr = attrs ? ' ' + attrs : '';
    const newText = `<${tag}${attrStr}>${selectedText}</${tag}>`;
    
    textarea.value = textarea.value.substring(0, start) + newText + textarea.value.substring(end);
    textarea.focus();
    textarea.setSelectionRange(start + tag.length + 2 + attrs.length, start + tag.length + 2 + attrs.length + selectedText.length);
}

// إدراج قائمة
function insertList(type) {
    const textarea = document.getElementById('content');
    const start = textarea.selectionStart;
    const list = `<${type}>\n  <li>عنصر 1</li>\n  <li>عنصر 2</li>\n  <li>عنصر 3</li>\n</${type}>`;
    
    textarea.value = textarea.value.substring(0, start) + list + textarea.value.substring(start);
    textarea.focus();
}

// Auto-generate slug from title
document.querySelector('input[name="title"]')?.addEventListener('input', function(e) {
    const slugInput = document.querySelector('input[name="slug"]');
    if (!slugInput.value || slugInput.dataset.auto !== 'false') {
        const slug = e.target.value
            .toLowerCase()
            .replace(/[أإآ]/g, 'ا')
            .replace(/[ى]/g, 'ي')
            .replace(/[ة]/g, 'ه')
            .replace(/\s+/g, '-')
            .replace(/[^\w\u0600-\u06FF-]/g, '');
        slugInput.value = slug;
    }
});

document.querySelector('input[name="slug"]')?.addEventListener('input', function() {
    this.dataset.auto = 'false';
});
</script>

<?php include '../includes/footer.php'; ?>
