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

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$article = null;

if ($id > 0) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM articles WHERE id = ?");
        $stmt->execute([$id]);
        $article = $stmt->fetch();
    } catch (Exception $e) {
        $article = null;
    }
}

if (!$article) {
    header("Location: articles.php");
    exit;
}

$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['edit_article'])) {
    $title = trim($_POST['title']);
    $content = trim($_POST['content']);
    $author = trim($_POST['author']);
    
    if (empty($author)) {
        $author = 'Admin';
    }
    
    // Cover Image Handling
    $image_name = $article['image'];
    
    if (empty($title) || empty($content)) {
        $error = "Judul dan konten artikel wajib diisi.";
    } else {
        $slug = slugify($title);
        
        // Double check uniqueness of slug (excluding current article)
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM articles WHERE slug = ? AND id != ?");
        $stmt->execute([$slug, $id]);
        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)) {
                $new_image_name = 'blog_' . time() . '.' . $file_ext;
                $dest_dir = __DIR__ . '/../uploads/';
                if (!is_dir($dest_dir)) {
                    mkdir($dest_dir, 0777, true);
                }
                
                if (move_uploaded_file($file_tmp, $dest_dir . $new_image_name)) {
                    // Delete old cover image if it existed in uploads
                    if (!empty($image_name) && file_exists($dest_dir . $image_name) && !in_array($image_name, ['blog_split.jpg', 'blog_terrazzo.jpg', 'blog_abubatu.jpg'])) {
                        @unlink($dest_dir . $image_name);
                    }
                    $image_name = $new_image_name;
                }
            } else {
                $error = "Ekstensi gambar tidak valid. Hanya JPG, JPEG, PNG, dan WEBP yang diperbolehkan.";
            }
        }
        
        if (empty($error)) {
            try {
                $stmt = $pdo->prepare("UPDATE articles SET title = ?, slug = ?, content = ?, image = ?, author = ? WHERE id = ?");
                $stmt->execute([$title, $slug, $content, $image_name, $author, $id]);
                $success = "Artikel berhasil diperbarui!";
                
                // Refresh local model cache
                $stmt = $pdo->prepare("SELECT * FROM articles WHERE id = ?");
                $stmt->execute([$id]);
                $article = $stmt->fetch();
            } catch (Exception $e) {
                $error = "Gagal memperbarui 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" required value="<?php echo htmlspecialchars($article['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" required value="<?php echo htmlspecialchars($article['author']); ?>">
            </div>
        </div>
        
        <div class="form-group">
            <label>Gambar Sampul Saat Ini</label>
            <div style="margin-bottom: 10px;">
                <?php 
                $img_src = '../assets/images/' . $article['image'];
                if (!empty($article['image']) && file_exists('../uploads/' . $article['image'])) {
                    $img_src = '../uploads/' . $article['image'];
                }
                ?>
                <img src="<?php echo $img_src; ?>" style="width: 160px; height: 90px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border-color);" onerror="this.src='../assets/images/about_img.jpg'">
            </div>
            <label for="image">Ganti 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" required><?php echo htmlspecialchars($article['content']); ?></textarea>
        </div>
        
        <button type="submit" name="edit_article" class="btn-submit">Simpan Perubahan 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'; ?>
