<?php
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    getLandingContent();
} elseif ($method === 'PUT') {
    updateLandingContent();
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}

function getLandingContent() {
    $db = getDB();
    
    $stmt = $db->query("SELECT section, title, subtitle, content FROM landing_content WHERE is_active = true ORDER BY id");
    $content = $stmt->fetchAll();
    
    $result = [];
    foreach ($content as $item) {
        $result[$item['section']] = [
            'title' => $item['title'],
            'subtitle' => $item['subtitle'],
            'content' => json_decode($item['content'], true)
        ];
    }
    
    echo json_encode([
        'success' => true,
        'data' => $result
    ]);
}

function updateLandingContent() {
    $input = json_decode(file_get_contents('php://input'), true);
    $section = $input['section'] ?? '';
    $title = $input['title'] ?? '';
    $subtitle = $input['subtitle'] ?? null;
    $content = $input['content'] ?? [];
    
    if (empty($section)) {
        http_response_code(400);
        echo json_encode(['error' => 'Section required']);
        return;
    }
    
    $db = getDB();
    
    $stmt = $db->prepare("
        UPDATE landing_content 
        SET title = ?, subtitle = ?, content = ?::jsonb, updated_at = CURRENT_TIMESTAMP
        WHERE section = ?
    ");
    
    $stmt->execute([
        $title,
        $subtitle,
        json_encode($content),
        $section
    ]);
    
    echo json_encode([
        'success' => true,
        'message' => 'Content updated'
    ]);
}
