<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

header('Content-Type: application/json');
hw_require_auth(['admin']);

$method = $_SERVER['REQUEST_METHOD'];
$pdo = hw_db();

try {
    if ($method === 'GET') {
        // Get all pages
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        
        $stmt = $pdo->prepare('
            SELECT id, title, slug, status, updated_at
            FROM content_articles
            WHERE status != "archived"
            ORDER BY updated_at DESC
            LIMIT ? OFFSET ?
        ');
        $stmt->execute([$limit, $offset]);
        $pages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get total count
        $countStmt = $pdo->prepare('SELECT COUNT(*) as total FROM content_articles WHERE status != "archived"');
        $countStmt->execute();
        $total = $countStmt->fetch()['total'];
        
        echo json_encode([
            'success' => true,
            'pages' => $pages,
            'pagination' => [
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'pages' => ceil($total / $limit)
            ]
        ]);
    } 
    else if ($method === 'POST') {
        // Create/Update page
        $input = json_decode(file_get_contents('php://input'), true);
        $authUser = hw_get_auth_user();
        
        $id = $input['id'] ?? null;
        $title = $input['title'] ?? '';
        $slug = $input['slug'] ?? '';
        $content = $input['content'] ?? '';
        $status = $input['status'] ?? 'draft';
        
        if (!$title || !$slug) {
            echo json_encode(['success' => false, 'error' => 'Title and slug are required']);
            exit;
        }
        
        if ($id) {
            // Update
            $stmt = $pdo->prepare('
                UPDATE content_articles
                SET title = ?, slug = ?, content = ?, status = ?, updated_at = NOW()
                WHERE id = ?
            ');
            $stmt->execute([$title, $slug, $content, $status, $id]);
            echo json_encode(['success' => true, 'message' => 'Page updated', 'id' => $id]);
        } else {
            // Create
            $stmt = $pdo->prepare('
                INSERT INTO content_articles (title, slug, content, author_id, status, published_at, created_at, updated_at)
                VALUES (?, ?, ?, ?, ?, NOW(), NOW(), NOW())
            ');
            $stmt->execute([$title, $slug, $content, $authUser['id'], $status]);
            echo json_encode(['success' => true, 'message' => 'Page created', 'id' => $pdo->lastInsertId()]);
        }
    } 
    else if ($method === 'DELETE') {
        // Delete page
        $input = json_decode(file_get_contents('php://input'), true);
        $id = $input['id'] ?? 0;
        
        $stmt = $pdo->prepare('DELETE FROM content_articles WHERE id = ?');
        $stmt->execute([$id]);
        
        echo json_encode(['success' => true, 'message' => 'Page deleted']);
    }
    else {
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
