<?php
$admin_title = "Tambah Artikel Baru";
require_once 'includes/header.php';

$error = '';
$success = '';

function slugify($text) {
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);
    $text = preg_replace('~[^-\w]+~', '', $text);
    $text = trim($text, '-');
    $text = preg_replace('~-+~', '-', $text);
    $text = strtolower($text);
    if (empty($text)) {
        return 'artikel-' . time();
    }
    return $text;
}

if (isset($_POST['add_article'])) {
    $title = trim($_POST['title']);
    $content = trim($_POST['content']);
    $author = trim($_POST['author']);
    
    if (empty($author)) {
        $author = 'Admin';
    }
    
    // Cover Image Handling
    $image_name = '';
    
    if (empty($title) || empty($content)) {
        $error = "Judul dan konten artikel wajib diisi.";
    } else {
        $slug = slugify($title);
        
        // Double check uniqueness of slug
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM articles WHERE slug = ?");
        $stmt->execute([$slug]);
        if ($stmt->fetchColumn() > 0) {
            $slug = $slug . '-' . time();
        }
        
        if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
            $file_tmp = $_FILES['image']['tmp_name'];
            $file_orig_name = $_FILES['image']['name'];
            $file_ext = strtolower(pathinfo($file_orig_name, PATHINFO_EXTENSION));
            
            $allowed_exts = ['jpg', 'jpeg', 'png', 'webp'];
            if (in_array($file_ext, $allowed_exts)) {
                $image_name = 'blog_' . time() . '.' . $file_ext;
                $dest_dir = __DIR__ . '/../uploads/';
                if (!is_dir($dest_dir)) {
                    mkdir($dest_dir, 0777, true);
                }
                move_uploaded_file($file_tmp, $dest_dir . $image_name);
            } else {
                $error = "Ekstensi gambar tidak valid. Hanya JPG, JPEG, PNG, dan WEBP yang diperbolehkan.";
            }
        }
        
        if (empty($error)) {
            try {
                $stmt = $pdo->prepare("INSERT INTO articles (title, slug, content, image, author) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$title, $slug, $content, $image_name, $author]);
                $success = "Artikel baru berhasil diterbitkan!";
                
                // Clear post
                $_POST = [];
            } catch (Exception $e) {
                $error = "Gagal menerbitkan artikel: " . $e->getMessage();
            }
        }
    }
}
?>

<div style="margin-bottom: 25px;">
    <a href="articles.php" style="color: var(--primary); text-decoration: none; font-weight: 600;">
        <i class="fas fa-arrow-left"></i> Kembali ke Daftar Artikel
    </a>
</div>

<?php if (!empty($error)): ?>
    <div style="background-color: rgba(239, 68, 68, 0.15); border: 1px solid var(--error); color: #f87171; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-exclamation-circle" style="margin-right: 5px;"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div style="background-color: rgba(16, 185, 129, 0.15); border: 1px solid var(--success); color: #34d399; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-check-circle" style="margin-right: 5px;"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<div class="form-card">
    <form action="" method="POST" enctype="multipart/form-data">
        <div class="form-row">
            <div class="form-group" style="flex: 2;">
                <label for="title">Judul Artikel *</label>
                <input type="text" id="title" name="title" class="form-control" placeholder="Contoh: Mengenal Varian Batu Split Konstruksi" required value="<?php echo isset($_POST['title']) ? htmlspecialchars($_POST['title']) : ''; ?>">
            </div>
            
            <div class="form-group" style="flex: 1;">
                <label for="author">Penulis (Author)</label>
                <input type="text" id="author" name="author" class="form-control" placeholder="Contoh: Admin / Tim Sales" value="<?php echo isset($_POST['author']) ? htmlspecialchars($_POST['author']) : ''; ?>">
            </div>
        </div>
        
        <div class="form-group">
            <label for="image">Gambar Sampul (Cover Image) - Rekomendasi Rasio 16:9</label>
            <input type="file" id="image" name="image" class="form-control" accept="image/*">
        </div>
        
        <div class="form-group">
            <label for="content">Konten Lengkap Artikel *</label>
            <textarea id="content" name="content" class="form-control" rows="12" placeholder="Tulis artikel lengkap di sini..." required><?php echo isset($_POST['content']) ? htmlspecialchars($_POST['content']) : ''; ?></textarea>
        </div>
        
        <button type="submit" name="add_article" class="btn-submit">Terbitkan Artikel</button>
    </form>
</div>

<style>
/* Modern styling overrides for CKEditor 4 to match admin theme */
.cke_chrome {
    border-radius: 8px !important;
    border: 1px solid var(--border-color) !important;
    box-shadow: var(--shadow-sm) !important;
}
.cke_top {
    background-color: var(--bg-light) !important;
    border-bottom: 1px solid var(--border-color) !important;
    border-radius: 8px 8px 0 0 !important;
    padding: 10px !important;
}
.cke_bottom {
    background-color: var(--bg-light) !important;
    border-top: 1px solid var(--border-color) !important;
    border-radius: 0 0 8px 8px !important;
}
.cke_toolgroup {
    border: 1px solid var(--border-color) !important;
    background: #ffffff !important;
    border-radius: 4px !important;
    box-shadow: none !important;
}
.cke_button_off:hover {
    background: var(--primary-light) !important;
}
</style>
<script src="https://cdn.ckeditor.com/4.22.1/full/ckeditor.js"></script>
<script>
    CKEDITOR.replace('content', {
        height: 380,
        versionCheck: false, // Disables the security version check warning alert
        removeButtons: 'About,Flash,Iframe,Save,NewPage,Preview,Print,Templates,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Language,BidiLtr,BidiRtl',
        // Use standard path mapping
        filebrowserUploadUrl: 'upload.php',
        filebrowserUploadMethod: 'form'
    });
</script>

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