<?php
// Admin API for managing news (JSON responses). Requires admin session.
header('Content-Type: application/json; charset=utf-8');
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) {
    http_response_code(403);
    echo json_encode(['error'=>'unauthorized']);
    exit;
}
$newsFile = __DIR__ . '/data/news.json';
$news = file_exists($newsFile) ? (@json_decode(file_get_contents($newsFile), true) ?: []) : ['enabled'=>false,'sales_item'=>[], 'items'=>[]];
$method = $_SERVER['REQUEST_METHOD'];
$action = $_REQUEST['action'] ?? '';
function saveNews($path, $data) { return file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); }
if ($method === 'GET') {
    echo json_encode($news, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    exit;
}
// POST/PUT/DELETE operations
$payload = $_POST ?: json_decode(file_get_contents('php://input'), true) ?: [];
if ($action === 'toggle_enabled') {
    $news['enabled'] = !empty($payload['enabled']) ? true : false;
    saveNews($newsFile, $news);
    echo json_encode(['ok'=>true]);
    exit;
}
if ($action === 'save_sales') {
    $news['sales_item'] = $payload['sales_item'] ?? [];
    saveNews($newsFile, $news);
    echo json_encode(['ok'=>true]);
    exit;
}
if ($action === 'add_item') {
    $item = [
        'title' => trim($payload['title'] ?? ''),
        'content' => trim($payload['content'] ?? ''),
        'image' => trim($payload['image'] ?? ''),
        'link' => trim($payload['link'] ?? ''),
        'highlight' => !empty($payload['highlight']),
        'date' => time()
    ];
    if ($item['title'] && $item['content']) {
        $news['items'][] = $item;
        saveNews($newsFile, $news);
        echo json_encode(['ok'=>true]);
    } else {
        http_response_code(400);
        echo json_encode(['error'=>'invalid']);
    }
    exit;
}
if ($action === 'edit_item') {
    $idx = isset($payload['index']) ? (int)$payload['index'] : -1;
    if (isset($news['items'][$idx])) {
        $news['items'][$idx] = array_merge($news['items'][$idx], [
            'title' => trim($payload['title'] ?? $news['items'][$idx]['title']),
            'content' => trim($payload['content'] ?? $news['items'][$idx]['content']),
            'image' => trim($payload['image'] ?? $news['items'][$idx]['image'] ?? ''),
            'link' => trim($payload['link'] ?? $news['items'][$idx]['link'] ?? ''),
            'highlight' => !empty($payload['highlight'])
        ]);
        saveNews($newsFile, $news);
        echo json_encode(['ok'=>true]);
    } else {
        http_response_code(404);
        echo json_encode(['error'=>'not_found']);
    }
    exit;
}
if ($action === 'delete_item') {
    $idx = isset($payload['index']) ? (int)$payload['index'] : -1;
    if (isset($news['items'][$idx])) {
        array_splice($news['items'], $idx, 1);
        saveNews($newsFile, $news);
        echo json_encode(['ok'=>true]);
    } else {
        http_response_code(404);
        echo json_encode(['error'=>'not_found']);
    }
    exit;
}
http_response_code(400);
echo json_encode(['error'=>'unknown_action']);
