<?php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

// Require admin
if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) {
    header('Location: admin_login.php'); exit;
}

// Use DatabaseHelper (keeps parity with other admin pages and supports DB-backed storage)
require_once __DIR__ . '/helpers/database_helper.php';

$dataPath = 'news.json';
$defaults = ['enabled'=>false, 'sales_item'=>[], 'items'=>[]];
$news = DatabaseHelper::loadJson($dataPath, $defaults);
if (!is_array($news)) $news = $defaults;

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'toggle_enabled') {
        $news['enabled'] = !empty($_POST['enabled']);
        DatabaseHelper::saveJson($dataPath, $news);
        $message = 'Saved.';
    }
    elseif ($action === 'save_sales') {
        $news['sales_item'] = [
            'title' => trim($_POST['sales_title'] ?? ''),
            'image' => trim($_POST['sales_image'] ?? ''),
            'link'  => trim($_POST['sales_link'] ?? ''),
            'price' => trim($_POST['sales_price'] ?? ''),
            'description' => trim($_POST['sales_description'] ?? '')
        ];
        DatabaseHelper::saveJson($dataPath, $news);
        $message = 'Sales item saved.';
    }
    elseif ($action === 'add_item' || $action === 'edit_item') {
        $title = trim($_POST['news_title'] ?? '');
        $content = trim($_POST['news_content'] ?? '');
        $image = trim($_POST['news_image'] ?? '');
        $link = trim($_POST['news_link'] ?? '');
        $highlight = !empty($_POST['news_highlight']);
        if ($title && $content) {
            $item = ['title'=>$title,'content'=>$content,'image'=>$image,'link'=>$link,'highlight'=>$highlight,'date'=>time()];
            if ($action === 'add_item') {
                $news['items'][] = $item; $message = 'News added.';
            } else {
                $idx = isset($_POST['index']) ? (int)$_POST['index'] : -1;
                if (isset($news['items'][$idx])) { $item['date']=$news['items'][$idx]['date']??$item['date']; $news['items'][$idx]=$item; $message='News updated.'; }
                else { $message='Invalid index.'; }
            }
            DatabaseHelper::saveJson($dataPath, $news);
        } else { $message='Title and content required.'; }
    }
    elseif ($action === 'delete_item') {
        $idx = isset($_POST['index']) ? (int)$_POST['index'] : -1;
        if (isset($news['items'][$idx])) { array_splice($news['items'],$idx,1); DatabaseHelper::saveJson($dataPath,$news); $message='Deleted.'; }
    }
    // reload
    $news = DatabaseHelper::loadJson($dataPath, $defaults) ?: $defaults;
}

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin - Manage News</title>
<link rel="stylesheet" href="styles.css">
<style>
.admin-box{max-width:900px;margin:20px auto;padding:16px;background:#fff;border:1px solid #eee;}
.news-item{border-bottom:1px solid #f0f0f0;padding:8px 0;}
.back-link{display:inline-block;margin-bottom:12px;}
</style>
</head>
<body>
<div class="admin-box">
    <a href="admin_dashboard.php" class="back-link">← Back to dashboard</a>
    <h1>Manage Home News</h1>
    <?php if ($message): ?><div style="padding:8px;background:#e6ffed;border:1px solid #bfe9c8;margin-bottom:12px;"><?php echo htmlspecialchars($message); ?></div><?php endif; ?>

    <form method="post">
        <input type="hidden" name="action" value="toggle_enabled">
        <label><input type="checkbox" name="enabled" value="1" <?php echo !empty($news['enabled']) ? 'checked' : ''; ?>> Enable News Section</label>
        <div style="margin-top:12px;"><button type="submit">Save</button></div>
    </form>

    <hr>
    <h2>Sales Item (left column)</h2>
    <form method="post">
        <input type="hidden" name="action" value="save_sales">
        <div><label>Title<br><input name="sales_title" style="width:100%;" value="<?php echo htmlspecialchars($news['sales_item']['title'] ?? ''); ?>"></label></div>
        <div><label>Image URL<br><input name="sales_image" style="width:100%;" value="<?php echo htmlspecialchars($news['sales_item']['image'] ?? ''); ?>"></label></div>
        <div><label>Link (product or external)<br><input name="sales_link" style="width:100%;" value="<?php echo htmlspecialchars($news['sales_item']['link'] ?? ''); ?>"></label></div>
        <div><label>Price/Text<br><input name="sales_price" style="width:100%;" value="<?php echo htmlspecialchars($news['sales_item']['price'] ?? ''); ?>"></label></div>
        <div><label>Description<br><textarea name="sales_description" style="width:100%;" rows="3"><?php echo htmlspecialchars($news['sales_item']['description'] ?? ''); ?></textarea></label></div>
        <div style="margin-top:8px;"><button type="submit">Save Sales Item</button></div>
    </form>

    <hr>
    <h2>News Items (right column)</h2>
    <?php if (!empty($news['items'])): ?>
        <?php foreach ($news['items'] as $i => $it): ?>
            <div class="news-item">
                <div style="display:flex; gap:12px; align-items:flex-start;">
                    <?php if (!empty($it['image'])): ?><div style="width:84px; flex:0 0 84px;"><img src="<?php echo htmlspecialchars($it['image']); ?>" alt="" style="width:100%; height:auto; object-fit:cover; border-radius:4px;"></div><?php endif; ?>
                    <div style="flex:1;">
                        <strong><?php echo htmlspecialchars($it['title']); ?></strong>
                        <?php if (!empty($it['highlight'])): ?><span style="background:#F07E2D;color:#fff;padding:2px 6px;border-radius:4px;font-size:12px;margin-left:8px;">Sales Highlight</span><?php endif; ?>
                        <div style="color:#666; margin:6px 0;"><?php echo nl2br(htmlspecialchars($it['content'])); ?></div>
                        <?php if (!empty($it['link'])): ?><div><a href="<?php echo htmlspecialchars($it['link']); ?>" target="_blank">Open Link</a></div><?php endif; ?>
                    </div>
                    <div style="flex:0 0 120px;text-align:right;">
                        <form method="post" style="display:inline-block;margin-bottom:6px;">
                            <input type="hidden" name="action" value="delete_item">
                            <input type="hidden" name="index" value="<?php echo $i; ?>">
                            <button type="submit">Delete</button>
                        </form>
                        <button type="button" onclick="populateEdit(<?php echo $i; ?>)">Edit</button>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <p>No news items yet.</p>
    <?php endif; ?>

    <h3 id="formHeading">Add News Item</h3>
    <form method="post" id="newsForm">
        <input type="hidden" name="action" value="add_item" id="formAction">
        <input type="hidden" name="index" value="" id="formIndex">
        <div><label>Title<br><input name="news_title" id="newsTitle" style="width:100%;"></label></div>
        <div><label>Image URL (optional)<br><input name="news_image" id="newsImage" style="width:100%;"></label></div>
        <div><label>Link (optional)<br><input name="news_link" id="newsLink" style="width:100%;"></label></div>
        <div><label><input type="checkbox" name="news_highlight" id="newsHighlight" value="1"> Mark as Sales Highlight</label></div>
        <div><label>Content<br><textarea name="news_content" id="newsContent" style="width:100%;" rows="5"></textarea></label></div>
        <div style="margin-top:8px;"><button type="submit">Save</button> <button type="button" onclick="resetForm()">Reset</button></div>
    </form>
</div>

<script>
var items = <?php echo json_encode($news['items'] ?? []); ?>;
function populateEdit(idx){
    var it = items[idx]; if(!it) return;
    document.getElementById('formAction').value = 'edit_item';
    document.getElementById('formIndex').value = idx;
    document.getElementById('newsTitle').value = it.title || '';
    document.getElementById('newsImage').value = it.image || '';
    document.getElementById('newsLink').value = it.link || '';
    document.getElementById('newsContent').value = it.content || '';
    document.getElementById('newsHighlight').checked = !!it.highlight;
    document.getElementById('formHeading').textContent = 'Edit News Item';
    window.scrollTo({top: document.getElementById('newsForm').offsetTop - 20, behavior:'smooth'});
}
function resetForm(){
    document.getElementById('formAction').value = 'add_item';
    document.getElementById('formIndex').value = '';
    document.getElementById('newsTitle').value = '';
    document.getElementById('newsImage').value = '';
    document.getElementById('newsLink').value = '';
    document.getElementById('newsContent').value = '';
    document.getElementById('newsHighlight').checked = false;
    document.getElementById('formHeading').textContent = 'Add News Item';
}
</script>
</body>
</html>
