<?php
session_start();

// Permission Enforcement & Helpers
require_once __DIR__ . '/helpers/subadmin_page_guard.php';
require_once __DIR__ . '/helpers/get_back_button.php';

// Check permissions - allows full admins and subadmins with view access
$pageGuard = new SubAdminPageGuard('manage_news');
$pageGuard->enforceView();

// Enable error display temporarily for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// Try to load database configuration
$conn = null;
if (file_exists("db_config.php")) {
    @require_once("db_config.php");
}

$action = isset($_GET['action']) ? $_GET['action'] : '';
$news_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$error = '';
$success = '';

// Helper to check if a column exists in a table (used to remain compatible
// with databases that don't have optional columns like `has_shop_button`).
function columnExists($conn, $table, $column) {
    if (!$conn) return false;
    try {
        // First check if table exists
        $tableCheck = @$conn->query("SHOW TABLES LIKE '" . $conn->real_escape_string($table) . "'");
        if (!$tableCheck || $tableCheck->num_rows === 0) return false;
        
        $col = $conn->real_escape_string($column);
        $tbl = $conn->real_escape_string($table);
        $res = @$conn->query("SHOW COLUMNS FROM `" . $tbl . "` LIKE '" . $col . "'");
        return ($res && $res->num_rows > 0);
    } catch (Exception $e) {
        return false;
    }
}

$hasShopButtonCol = false;
$shopLinkCol = false;
$displayTypeCol = false;
if ($conn) {
    $hasShopButtonCol = columnExists($conn, 'news', 'has_shop_button');
    $shopLinkCol = columnExists($conn, 'news', 'shop_link');
    $displayTypeCol = columnExists($conn, 'news', 'display_type');
    
    // Ensure display_type column exists - create if needed
    if (!$displayTypeCol) {
        @$conn->query("ALTER TABLE news ADD COLUMN display_type VARCHAR(50) DEFAULT 'full' AFTER is_sale");
        // Verify column was created
        $displayTypeCol = columnExists($conn, 'news', 'display_type');
    }
}

// Handle delete
if ($action === 'delete' && $news_id > 0 && $conn) {
    // Check permission for delete action
    EnforceManageNews::guardAction('delete');
    
    $deleteQuery = "DELETE FROM news WHERE id = ?";
    $stmt = $conn->prepare($deleteQuery);
    if ($stmt) {
        $stmt->bind_param("i", $news_id);
        if ($stmt->execute()) {
            $success = "News item deleted successfully!";
        } else {
            $error = "Failed to delete news item.";
        }
        $stmt->close();
    }
}

// Handle add/edit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $conn) {
    $post_news_id = isset($_POST['news_id']) ? (int)$_POST['news_id'] : 0;
    
    // Check permission for create or edit action
    if ($post_news_id > 0) {
        EnforceManageNews::guardAction('edit');
    } else {
        EnforceManageNews::guardAction('create');
    }
    
    $title = isset($_POST['title']) ? trim($_POST['title']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $is_sale = isset($_POST['is_sale']) ? 1 : 0;
    $has_shop_button = isset($_POST['has_shop_button']) ? 1 : 0;
    $shop_link = isset($_POST['shop_link']) ? trim($_POST['shop_link']) : '';

    // If admin checked the shop button but didn't provide a link,
    // use the site's `shop.php` as the default if it exists.
    if ($has_shop_button && empty($shop_link)) {
        if (file_exists(__DIR__ . DIRECTORY_SEPARATOR . 'shop.php')) {
            $shop_link = 'shop.php';
        }
    }
    // Determine display_type: preserve existing on edit, otherwise default to 'card'.
    $display_type = 'full';
    if ($displayTypeCol) {
        if ($post_news_id > 0) {
            $tmpStmt = $conn->prepare("SELECT display_type FROM news WHERE id = ?");
            if ($tmpStmt) {
                $tmpStmt->bind_param('i', $post_news_id);
                $tmpStmt->execute();
                $tmpRes = $tmpStmt->get_result();
                $tmpRow = $tmpRes->fetch_assoc();
                if ($tmpRow && !empty($tmpRow['display_type'])) {
                    $display_type = $tmpRow['display_type'];
                }
                $tmpStmt->close();
            }
        }
        if (isset($_POST['display_type'])) {
            $display_type = trim($_POST['display_type']);
        }
    }
    
    if (empty($title)) {
        $error = "Title is required.";
    } else {
        $image = '';
        
        // Handle image upload
        if (!empty($_FILES['image']['name'])) {
            $target_dir = "uploads/news/";
            if (!is_dir($target_dir)) {
                mkdir($target_dir, 0755, true);
            }
            
            $file_extension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            $allowed = array('jpg', 'jpeg', 'png', 'gif');
            
            if (!in_array($file_extension, $allowed)) {
                $error = "Only JPG, PNG, and GIF files are allowed.";
            } elseif ($_FILES['image']['size'] > 5000000) {
                $error = "File size must not exceed 5MB.";
            } else {
                $image_name = time() . '_' . uniqid() . '.' . $file_extension;
                $target_file = $target_dir . $image_name;
                
                if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file)) {
                    $image = $target_file;
                } else {
                    $error = "Failed to upload image.";
                }
            }
        }
        
        if (empty($error)) {
            // Prepare dynamic queries depending on which optional columns exist.
            if ($post_news_id > 0) {
                // Edit existing news - build SET clause and parameters dynamically.
                $setParts = [];
                $params = [];
                $types = '';

                $setParts[] = 'title = ?';
                $params[] = $title; $types .= 's';

                $setParts[] = 'description = ?';
                $params[] = $description; $types .= 's';

                if (!empty($image)) {
                    $setParts[] = 'image = ?';
                    $params[] = $image; $types .= 's';
                }

                $setParts[] = 'is_sale = ?';
                $params[] = $is_sale; $types .= 'i';

                if ($displayTypeCol) {
                    $setParts[] = 'display_type = ?';
                    $params[] = $display_type; $types .= 's';
                }

                if ($hasShopButtonCol) {
                    $setParts[] = 'has_shop_button = ?';
                    $params[] = $has_shop_button; $types .= 'i';
                }

                if ($shopLinkCol) {
                    $setParts[] = 'shop_link = ?';
                    $params[] = $shop_link; $types .= 's';
                }

                $setClause = implode(', ', $setParts);
                $params[] = $post_news_id; $types .= 'i';

                $updateQuery = "UPDATE news SET " . $setClause . " WHERE id = ?";
                $stmt = $conn->prepare($updateQuery);
                if ($stmt) {
                    $refs = [];
                    $refs[] = &$types;
                    foreach ($params as $k => $v) { $refs[] = &$params[$k]; }
                    call_user_func_array(array($stmt, 'bind_param'), $refs);
                    if ($stmt->execute()) {
                        $success = "News item updated successfully!";
                    } else {
                        $error = "Database error: " . $stmt->error;
                    }
                    $stmt->close();
                } else {
                    $error = "Database prepare error: " . $conn->error;
                }
            } else {
                // Add new news - build INSERT columns/values dynamically.
                $cols = [];
                $placeholders = [];
                $params = [];
                $types = '';

                $cols[] = 'title'; $placeholders[] = '?'; $params[] = $title; $types .= 's';
                $cols[] = 'description'; $placeholders[] = '?'; $params[] = $description; $types .= 's';

                if (!empty($image)) {
                    $cols[] = 'image'; $placeholders[] = '?'; $params[] = $image; $types .= 's';
                }

                $cols[] = 'is_sale'; $placeholders[] = '?'; $params[] = $is_sale; $types .= 'i';

                if ($displayTypeCol) {
                    $cols[] = 'display_type'; $placeholders[] = '?'; $params[] = $display_type; $types .= 's';
                }

                if ($hasShopButtonCol) {
                    $cols[] = 'has_shop_button'; $placeholders[] = '?'; $params[] = $has_shop_button; $types .= 'i';
                }

                if ($shopLinkCol) {
                    $cols[] = 'shop_link'; $placeholders[] = '?'; $params[] = $shop_link; $types .= 's';
                }

                $insertQuery = "INSERT INTO news (" . implode(', ', $cols) . ", created_at) VALUES (" . implode(', ', $placeholders) . ", NOW())";
                $stmt = $conn->prepare($insertQuery);
                if ($stmt) {
                    $refs = [];
                    $refs[] = &$types;
                    foreach ($params as $k => $v) { $refs[] = &$params[$k]; }
                    if (!empty($params)) {
                        call_user_func_array(array($stmt, 'bind_param'), $refs);
                    }
                    if ($stmt->execute()) {
                        $success = "News item added successfully!";
                    } else {
                        $error = "Database error: " . $stmt->error;
                    }
                    $stmt->close();
                } else {
                    $error = "Database prepare error: " . $conn->error;
                }
            }
        }
    }
}

// Fetch news item for editing
$editNews = null;
if ($action === 'edit' && $news_id > 0 && $conn) {
    $editQuery = "SELECT * FROM news WHERE id = ?";
    $stmt = $conn->prepare($editQuery);
    if ($stmt) {
        $stmt->bind_param("i", $news_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $editNews = $result->fetch_assoc();
        $stmt->close();
    }
}

// Handle section title
$section_title = '';
$section_description = '';
if ($conn) {
    try {
        // Try to fetch section settings - wrapped in try-catch for safety
        $settingsRes = @$conn->query("SELECT section_title, section_description FROM news_settings LIMIT 1");
        if ($settingsRes && $row = $settingsRes->fetch_assoc()) {
            $section_title = $row['section_title'] ?? '';
            $section_description = $row['section_description'] ?? '';
        }
    } catch (Exception $e) {
        // Table doesn't exist yet, that's fine
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_section_title']) && $conn) {
    $new_title = isset($_POST['section_title']) ? trim($_POST['section_title']) : '';
    $new_desc = isset($_POST['section_description']) ? trim($_POST['section_description']) : '';
    
    // Create settings table if it doesn't exist
    $createSettingsTable = "CREATE TABLE IF NOT EXISTS `news_settings` (
        `id` INT PRIMARY KEY DEFAULT 1,
        `section_title` VARCHAR(255) DEFAULT '',
        `section_description` TEXT DEFAULT '',
        `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )";
    @$conn->query($createSettingsTable);
    
    // Update or insert settings
    $upsertQuery = "INSERT INTO news_settings (id, section_title, section_description) VALUES (1, ?, ?) 
                    ON DUPLICATE KEY UPDATE section_title = VALUES(section_title), section_description = VALUES(section_description)";
    $stmt = $conn->prepare($upsertQuery);
    if ($stmt) {
        $stmt->bind_param("ss", $new_title, $new_desc);
        if ($stmt->execute()) {
            $section_title = $new_title;
            $section_description = $new_desc;
            $success = "Section title updated successfully!";
        }
        $stmt->close();
    }
}

// Fetch all news items
$allNewsResult = null;
$newsCount = 0;
if ($conn) {
    $allNewsQuery = "SELECT id, title, image, created_at FROM news ORDER BY created_at DESC";
    $allNewsResult = $conn->query($allNewsQuery);
    if ($allNewsResult) {
        $newsCount = $allNewsResult->num_rows;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage News & Banners</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .container {
            max-width: 1400px;
            width: 100%;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .header h1 {
            color: white;
            font-size: 2.5em;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
            flex: 1;
            text-align: center;
            min-width: 300px;
        }

        .back-btn {
            display: inline-block;
            padding: 12px 24px;
            background: #ff6b6b;
            color: white;
            text-decoration: none;
            border-radius: 25px;
            font-weight: bold;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            align-self: center;
        }

        .back-btn:hover {
            background: #ff5252;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
        }

        /* Section Settings Card */
        .section-settings {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        .section-settings h2 {
            color: #333;
            margin-bottom: 20px;
            border-bottom: 3px solid #667eea;
            padding-bottom: 12px;
            font-size: 1.6em;
        }

        .content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 30px;
        }

        @media (max-width: 768px) {
            .content {
                grid-template-columns: 1fr;
            }
            
            .header {
                justify-content: center;
            }
            
            .header h1 {
                width: 100%;
                font-size: 2em;
            }
        }

        .card {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        }

        .card h2 {
            color: #333;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 3px solid #667eea;
            font-size: 1.8em;
        }

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

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 600;
            font-size: 0.95em;
        }

        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-family: inherit;
            font-size: 1em;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

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

        .checkbox-group {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 15px;
        }

        .checkbox-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }

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

        .checkbox-item label {
            margin: 0;
            cursor: pointer;
            font-weight: 500;
        }

        .btn-group {
            display: flex;
            gap: 15px;
            margin-top: 30px;
            flex-wrap: wrap;
        }

        .btn {
            flex: 1;
            min-width: 150px;
            padding: 14px 28px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            text-align: center;
        }

        .btn-submit {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
        }

        .btn-reset {
            background: #f0f0f0;
            color: #666;
            border: 2px solid #ddd;
        }

        .btn-reset:hover {
            background: #e8e8e8;
        }

        .alert {
            padding: 16px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .news-list {
            max-height: 600px;
            overflow-y: auto;
        }

        .news-item {
            display: flex;
            gap: 15px;
            padding: 15px;
            border: 2px solid #f0f0f0;
            border-radius: 8px;
            margin-bottom: 15px;
            background: #f9f9f9;
            transition: all 0.3s ease;
        }

        .news-item:hover {
            border-color: #667eea;
            background: #f5f7ff;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
        }

        .news-item-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 6px;
            background: #e0e0e0;
        }

        .news-item-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .news-item-title {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
            word-break: break-word;
        }

        .news-item-type {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 4px 10px;
            border-radius: 4px;
            font-size: 0.8em;
            margin-bottom: 8px;
            width: fit-content;
        }

        .news-item-type.banner {
            background: #ff9800;
        }

        .news-item-type.card {
            background: #4caf50;
        }

        .news-item-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .btn-small {
            padding: 8px 12px;
            font-size: 0.85em;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            text-align: center;
        }

        .btn-edit {
            background: #4caf50;
            color: white;
        }

        .btn-edit:hover {
            background: #45a049;
            transform: translateY(-1px);
        }

        .btn-delete {
            background: #f44336;
            color: white;
        }

        .btn-delete:hover {
            background: #da190b;
            transform: translateY(-1px);
        }

        .display-type-info {
            background: #e3f2fd;
            padding: 10px;
            border-left: 4px solid #2196f3;
            margin-bottom: 15px;
            border-radius: 4px;
            color: #1565c0;
            font-size: 0.9em;
        }

        .image-preview {
            max-width: 200px;
            max-height: 150px;
            margin-top: 10px;
            border-radius: 6px;
            border: 2px solid #f0f0f0;
        }

        .no-news-message {
            text-align: center;
            padding: 40px 20px;
            color: #999;
            font-style: italic;
        }

        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb {
            background: #667eea;
            border-radius: 10px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #764ba2;
        }

        @media print {
            body {
                background: white;
            }
            .btn, .back-btn {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📰 News & Banner Manager</h1>
            <a href="<?php echo getBackUrl(); ?>" class="back-btn">← Back</a>
        </div>

        <!-- Section Settings -->
        <div class="section-settings">
            <h2>⚙️ Section Title & Settings</h2>
            
            <?php if (isset($_POST['update_section_title']) && $success): ?>
                <div class="alert alert-success">✅ <?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>

            <form method="POST">
                <input type="hidden" name="update_section_title" value="1">
                
                <div class="form-group">
                    <label for="section_title">Section Title</label>
                    <input type="text" name="section_title" id="section_title" value="<?php echo htmlspecialchars($section_title); ?>" placeholder="e.g., Latest Offers, Featured Promotions" maxlength="255">
                    <small style="color: #666;">This title will be displayed at the top center of the news/banner section on the homepage</small>
                </div>

                <div class="form-group">
                    <label for="section_description">Section Description (Optional)</label>
                    <textarea name="section_description" id="section_description" placeholder="Add an optional description" style="min-height: 60px;"><?php echo htmlspecialchars($section_description); ?></textarea>
                </div>

                <div class="btn-group" style="margin-top: 15px;">
                    <button type="submit" class="btn btn-submit">💾 Save Section Settings</button>
                </div>
            </form>
        </div>

        <div class="content">
            <!-- Add/Edit News Form -->
            <div class="card">
                <h2><?php echo $editNews ? '✏️ Edit News Item' : '➕ Add New News Item'; ?></h2>

                <?php if (!$pageGuard->can(($editNews ? 'edit' : 'create'))): ?>
                    <div class="alert alert-error">
                        ❌ You don't have permission to <?php echo $editNews ? 'edit' : 'add'; ?> news items.
                        <?php echo $pageGuard->getLevel() === 'viewer' ? '(Your access level: Viewer)' : ''; ?>
                    </div>
                    <?php // Don't show the form to users without permission ?>
                <?php else: ?>

                <?php if (!$conn): ?>
                    <div class="alert alert-error">⚠️ Database connection unavailable. The form is displayed but database features are disabled. Please check your database configuration.</div>
                <?php endif; ?>

                <?php if ($error): ?>
                    <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>

                <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
                <?php endif; ?>

                <form method="POST" enctype="multipart/form-data" <?php echo !$conn ? 'style="opacity: 0.6; pointer-events: none;"' : ''; ?>>
                    <?php if ($editNews): ?>
                        <input type="hidden" name="news_id" value="<?php echo $editNews['id']; ?>">
                    <?php endif; ?>

                    <div class="form-group">
                        <label for="title">Title *</label>
                        <input type="text" name="title" id="title" value="<?php echo ($editNews && isset($editNews['title'])) ? htmlspecialchars($editNews['title']) : ''; ?>" required placeholder="Enter news title">
                    </div>

                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea name="description" id="description" placeholder="Enter detailed description"><?php echo ($editNews && isset($editNews['description'])) ? htmlspecialchars($editNews['description']) : ''; ?></textarea>
                    </div>

                    <div class="form-group">
                        <label for="display_type">Display Type *</label>
                        <select name="display_type" id="display_type" required>
                            <option value="">-- Select Display Type --</option>
                            <option value="full" <?php echo ($editNews && isset($editNews['display_type']) && $editNews['display_type'] === 'full') ? 'selected' : ''; ?>>Both Title & Image (Half/Half)</option>
                            <option value="image_only" <?php echo ($editNews && isset($editNews['display_type']) && $editNews['display_type'] === 'image_only') ? 'selected' : ''; ?>>Image Only (Full Width)</option>
                            <option value="description_only" <?php echo ($editNews && isset($editNews['display_type']) && $editNews['display_type'] === 'description_only') ? 'selected' : ''; ?>>Title & Description Only (Full Width)</option>
                            <option value="title_only" <?php echo ($editNews && isset($editNews['display_type']) && $editNews['display_type'] === 'title_only') ? 'selected' : ''; ?>>Title Only</option>
                            <option value="banner_only" <?php echo ($editNews && isset($editNews['display_type']) && $editNews['display_type'] === 'banner_only') ? 'selected' : ''; ?>>Banner Mode (Image with Overlay Title)</option>
                        </select>
                        <small style="color: #666; display: block; margin-top: 6px;">
                            • <strong>Both:</strong> Image and content side by side<br>
                            • <strong>Image Only:</strong> Just the image, full card width<br>
                            • <strong>Title & Description:</strong> Text content, full width<br>
                            • <strong>Title Only:</strong> Minimal card with just title<br>
                            • <strong>Banner Mode:</strong> Full image with title overlay at bottom
                        </small>
                    </div>

                    <div class="form-group">
                        <label for="image">Image</label>
                        <input type="file" name="image" id="image" accept="image/*">
                        <small style="color: #666;">Accepted formats: JPG, PNG, GIF. Max size: 5MB</small>
                        <?php if ($editNews && isset($editNews['image']) && $editNews['image']): ?>
                            <div style="margin-top: 10px;">
                                <p style="color: #666; font-weight: 600;">Current Image:</p>
                                <img src="<?php echo htmlspecialchars($editNews['image']); ?>" alt="Current" class="image-preview">
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="form-group">
                        <div class="checkbox-group">
                            <div class="checkbox-item">
                                <input type="checkbox" name="is_sale" id="is_sale" <?php echo ($editNews && isset($editNews['is_sale']) && $editNews['is_sale']) ? 'checked' : ''; ?>>
                                <label for="is_sale">Mark as Sale/Highlight</label>
                           -->  </div>
                            <div class="checkbox-item">
                                <input type="checkbox" name="has_shop_button" id="has_shop_button" <?php echo ($editNews && isset($editNews['has_shop_button']) && $editNews['has_shop_button']) ? 'checked' : ''; ?>>
                                <!-- <label for="has_shop_button">Add Shop Button</label>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <!-- <label for="shop_link">Shop Link (if shop button enabled)</label>
                        <input type="url" name="shop_link" id="shop_link" value="<?php echo ($editNews && isset($editNews['shop_link'])) ? htmlspecialchars($editNews['shop_link']) : ''; ?>" placeholder="https://example.com/product">
                    </div> -->

                    <div class="btn-group">
                        <button type="submit" class="btn btn-submit">
                            <?php echo $editNews ? '💾 Update News Item' : '✅ Add News Item'; ?>
                        </button>
                        <button type="reset" class="btn btn-reset">🔄 Reset Form</button>
                        <?php if ($editNews): ?>
                            <a href="admin_add_news.php" class="btn btn-reset">↩️ Cancel</a>
                        <?php endif; ?>
                    </div>
                </form>
                <?php endif; ?>
            </div>

            <!-- News List -->
            <div class="card">
                <h2>📋 All News Items (<?php echo $newsCount; ?>)</h2>

                <div class="news-list">
                    <?php if (!$conn): ?>
                        <div class="no-news-message">
                            📭 Database not connected. Cannot display news items.
                        </div>
                    <?php elseif ($allNewsResult && $newsCount > 0): ?>
                        <?php while ($news = $allNewsResult->fetch_assoc()): ?>
                            <div class="news-item">
                                <?php if ($news['image']): ?>
                                    <img src="<?php echo htmlspecialchars($news['image']); ?>" alt="<?php echo htmlspecialchars($news['title']); ?>" class="news-item-image">
                                <?php else: ?>
                                    <div class="news-item-image" style="display: flex; align-items: center; justify-content: center; background: #f0f0f0;">
                                        <span style="color: #999; font-size: 12px;">No Image</span>
                                    </div>
                                <?php endif; ?>
                                <div class="news-item-info">
                                    <div>
                                        <div class="news-item-title"><?php echo htmlspecialchars($news['title']); ?></div>
                                    </div>
                                    <small style="color: #999;"><?php echo date('M d, Y', strtotime($news['created_at'])); ?></small>
                                </div>
                                <div class="news-item-actions">
                                    <?php if ($pageGuard->can('edit')): ?>
                                        <a href="?action=edit&id=<?php echo $news['id']; ?>" class="btn-small btn-edit">✏️ Edit</a>
                                    <?php else: ?>
                                        <span class="btn-small btn-edit" style="color: #ccc; cursor: not-allowed;">✏️ Edit</span>
                                    <?php endif; ?>
                                    
                                    <?php if ($pageGuard->can('delete')): ?>
                                        <a href="?action=delete&id=<?php echo $news['id']; ?>" class="btn-small btn-delete" onclick="return confirm('Are you sure you want to delete this item?');">🗑️ Delete</a>
                                    <?php else: ?>
                                        <span class="btn-small btn-delete" style="color: #ccc; cursor: not-allowed;">🗑️ Delete</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="no-news-message">
                            📭 No news items yet. Create your first one!
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
