<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, PUT, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }
header('Content-Type: application/json');

include_once '../config/Database.php';
include_once '../middleware/auth.php';

$database = new Database();
$db = $database->connect();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $section = isset($_GET['section']) ? $_GET['section'] : die();
    $query = 'SELECT data FROM contents WHERE section = :section';
    $stmt = $db->prepare($query);
    $stmt->bindParam(':section', $section);
    $stmt->execute();
    if ($stmt->rowCount() > 0) {
        echo $stmt->fetch(PDO::FETCH_ASSOC)['data'];
    } else {
        http_response_code(404);
        echo json_encode(['message' => 'Content not found']);
    }
} elseif ($method === 'PUT') {
    $user = get_user_from_token();
    if (!$user || $user->role !== 'admin') {
        http_response_code(403);
        echo json_encode(['message' => 'Forbidden: Admin access required.']);
        exit();
    }
    
    $section = isset($_GET['section']) ? $_GET['section'] : die();
    $input_data = json_decode(file_get_contents("php://input"));
    $query = 'UPDATE contents SET data = :data WHERE section = :section';
    $stmt = $db->prepare($query);
    $stmt->bindParam(':data', json_encode($input_data->data));
    $stmt->bindParam(':section', $section);
    if($stmt->execute()) {
        echo json_encode(['message' => 'Content updated']);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Content not updated']);
    }
}
?>