<?php
// 1. INCLUDE THE LOGIC-ONLY FILE
require_once 'admin-logic.php';


// --- Page-Specific Logic Starts Here ---

// 2. INITIALIZE VARIABLES & DETERMINE MODE (ADD/EDIT)
$edit_mode = false;
$article = []; // Initialize empty array to prevent errors in 'add' mode
$page_error = '';

$article_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($article_id) {
    $edit_mode = true;
}

// 3. FETCH DATA FOR FORM IF EDITING
if ($edit_mode) {
    $stmt = $conn->prepare("SELECT * FROM articles WHERE id = ?");
    $stmt->bind_param("i", $article_id);
    $stmt->execute();
    $article = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if (!$article) {
        $page_error = "The requested article could not be found.";
    }
}

// 4. HANDLE FORM SUBMISSION (CREATE OR UPDATE)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect and sanitize data
    $title = trim($_POST['title']);
    $content = $_POST['content']; // TinyMCE cleans its output
    $is_published = isset($_POST['is_published']) ? 1 : 0;
    // Use current date for new posts, or keep existing date for updates unless specified otherwise
    $publish_date = !empty($_POST['publish_date']) ? $_POST['publish_date'] : date('Y-m-d H:i:s');

    // Handle file upload for the featured image
    $image_url = $_POST['current_image_url'] ?? ''; // Keep old image by default
    if (isset($_FILES['image_url']) && $_FILES['image_url']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../uploads/articles/';
        if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }
        $filename = 'article-' . uniqid() . '-' . basename($_FILES['image_url']['name']);
        $target_path = $upload_dir . $filename;
        if (move_uploaded_file($_FILES['image_url']['tmp_name'], $target_path)) {
            $image_url = 'uploads/articles/' . $filename;
        } else {
            $_SESSION['error_message'] = "Error uploading file.";
        }
    }

    if (empty($title)) {
        $_SESSION['error_message'] = "Article Title is required.";
    } else {
        if ($edit_mode) { // UPDATE
            $stmt = $conn->prepare("UPDATE articles SET title=?, content=?, is_published=?, publish_date=?, image_url=? WHERE id=?");
            $stmt->bind_param("ssissi", $title, $content, $is_published, $publish_date, $image_url, $article_id);
            if($stmt->execute()) $_SESSION['success_message'] = "Article updated successfully."; else $_SESSION['error_message'] = "Error updating article.";
            $stmt->close();
        } else { // INSERT
            $stmt = $conn->prepare("INSERT INTO articles (title, content, is_published, publish_date, image_url) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("ssiss", $title, $content, $is_published, $publish_date, $image_url);
            if($stmt->execute()) $_SESSION['success_message'] = "Article created successfully."; else $_SESSION['error_message'] = "Error creating article.";
            $stmt->close();
        }
        header("Location: manage-articles.php");
        exit();
    }
}


// 5. INCLUDE THE HTML HEADER
include 'admin-header.php';
?>

<script src="https://cdn.tiny.cloud/1/<?php echo htmlspecialchars($settings['api_tinymce'] ?? 'no-api-key'); ?>/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
  tinymce.init({
    selector: 'textarea#content',
    plugins: 'code table lists link image autoresize',
    toolbar: 'undo redo | blocks | bold italic | alignleft aligncenter alignright | bullist numlist | code | table | image link',
    skin: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'oxide-dark' : 'oxide'),
    content_css: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default'),
    height: 600
  });
</script>

<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<?php if ($page_error): ?>
    <div class="alert alert-danger mt-4"><h4 class="alert-heading">Error</h4><p><?php echo $page_error; ?></p><hr><a href="manage-articles.php" class="btn btn-outline-danger">Return to Articles List</a></div>
<?php else: ?>
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <div>
            <h1 class="h2"><?php echo $edit_mode ? 'Edit Article' : 'Write New Article'; ?></h1>
            <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="manage-articles.php">Articles</a></li><li class="breadcrumb-item active"><?php echo $edit_mode ? htmlspecialchars($article['title']) : 'New'; ?></li></ol></nav>
        </div>
    </div>
    
    <form method="POST" action="edit-article.php<?php echo $edit_mode ? '?id=' . $article_id : ''; ?>" enctype="multipart/form-data">
        <div class="row g-4">
            <div class="col-lg-9">
                <div class="card shadow-sm">
                    <div class="card-body">
                        <div class="mb-3"><label for="title" class="form-label visually-hidden">Title</label><input type="text" class="form-control form-control-lg" id="title" name="title" placeholder="Enter title here" value="<?php echo htmlspecialchars($article['title'] ?? ''); ?>" required></div>
                        <div class="mb-3"><label for="content" class="form-label visually-hidden">Content</label><textarea id="content" name="content" rows="20"><?php echo htmlspecialchars($article['content'] ?? ''); ?></textarea></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-3">
                <div class="card shadow-sm mb-4">
                    <div class="card-header"><strong>Publish</strong></div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label for="publish_date" class="form-label">Publish Date</label>
                            <input type="datetime-local" class="form-control" id="publish_date" name="publish_date" value="<?php echo date('Y-m-d\TH:i', strtotime($article['publish_date'] ?? 'now')); ?>">
                        </div>
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" role="switch" id="is_published" name="is_published" <?php if(isset($article['is_published']) && $article['is_published']) echo 'checked'; ?>>
                            <label class="form-check-label" for="is_published">Publish (Visible on site)</label>
                        </div>
                        <div class="d-flex justify-content-end gap-2">
                            <a href="manage-articles.php" class="btn btn-secondary">Cancel</a>
                            <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle-fill me-1"></i> <?php echo $edit_mode ? 'Update' : 'Save'; ?></button>
                        </div>
                    </div>
                </div>
                <div class="card shadow-sm">
                    <div class="card-header"><strong>Featured Image</strong></div>
                    <div class="card-body">
                        <input class="form-control" type="file" name="image_url" id="main-image-input">
                        <input type="hidden" name="current_image_url" value="<?php echo htmlspecialchars($article['image_url'] ?? ''); ?>">
                        <?php $image_src = !empty($article['image_url']) ? '../' . htmlspecialchars($article['image_url']) : 'https://via.placeholder.com/300x200.png?text=No+Image'; ?>
                        <img id="image-preview" src="<?php echo $image_src; ?>" class="img-fluid rounded border mt-2" alt="Image Preview">
                    </div>
                </div>
            </div>
        </div>
    </form>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const imageInput = document.getElementById('main-image-input');
    const imagePreview = document.getElementById('image-preview');
    if (imageInput) {
        imageInput.addEventListener('change', function(e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function(event) { imagePreview.src = event.target.result; }
                reader.readAsDataURL(e.target.files[0]);
            }
        });
    }
});
</script>

<?php include 'admin-footer.php'; ?>
