<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);

header("Content-Type: application/json");

try {
    require_once __DIR__ . "/../includes/config.php";
    $pdo = getDB();

    if (!isset($_SESSION["user_id"])) {
        echo json_encode(["success" => false, "error" => "Nao autenticado"]);
        exit;
    }

    $userId = $_SESSION["user_id"];
    $action = $_GET["action"] ?? $_POST["action"] ?? "";
    $storeId = $_GET["store_id"] ?? $_POST["store_id"] ?? null;

    if (!$storeId) {
        echo json_encode(["success" => false, "error" => "ID da loja nao informado"]);
        exit;
    }

    $stmt = $pdo->prepare("SELECT id FROM stores WHERE id = ? AND owner_user_id = ?");
    $stmt->execute([$storeId, $userId]);
    if (!$stmt->fetch()) {
        echo json_encode(["success" => false, "error" => "Acesso negado"]);
        exit;
    }

    switch ($action) {
        case "list":
            $stmt = $pdo->prepare("SELECT id, title, slug, meta_description, is_active, show_in_menu, menu_order, created_at FROM store_pages WHERE store_id = ? ORDER BY menu_order ASC, title ASC");
            $stmt->execute([$storeId]);
            echo json_encode(["success" => true, "pages" => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
            break;

        case "get":
            $pageId = $_GET["id"] ?? null;
            if (!$pageId) { echo json_encode(["success" => false, "error" => "ID da pagina nao informado"]); exit; }
            $stmt = $pdo->prepare("SELECT * FROM store_pages WHERE id = ? AND store_id = ?");
            $stmt->execute([$pageId, $storeId]);
            $page = $stmt->fetch(PDO::FETCH_ASSOC);
            echo json_encode($page ? ["success" => true, "page" => $page] : ["success" => false, "error" => "Pagina nao encontrada"]);
            break;

        case "create":
            $title = trim($_POST["title"] ?? "");
            $slug = trim($_POST["slug"] ?? "");
            $content = $_POST["content"] ?? "";
            $metaDesc = trim($_POST["meta_description"] ?? "");
            $isActive = isset($_POST["is_active"]) ? (int)$_POST["is_active"] : 1;
            $showMenu = isset($_POST["show_in_menu"]) ? (int)$_POST["show_in_menu"] : 0;

            if (empty($title) or empty($slug)) { echo json_encode(["success" => false, "error" => "Titulo e slug obrigatorios"]); exit; }

            $stmt = $pdo->prepare("SELECT id FROM store_pages WHERE store_id = ? AND slug = ?");
            $stmt->execute([$storeId, $slug]);
            if ($stmt->fetch()) { echo json_encode(["success" => false, "error" => "Slug ja existe"]); exit; }

            $stmt = $pdo->prepare("SELECT COALESCE(MAX(menu_order), 0) + 1 FROM store_pages WHERE store_id = ?");
            $stmt->execute([$storeId]);
            $order = $stmt->fetchColumn();

            $stmt = $pdo->prepare("INSERT INTO store_pages (store_id, title, slug, content, meta_description, is_active, show_in_menu, menu_order, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
            $stmt->execute([$storeId, $title, $slug, $content, $metaDesc, $isActive, $showMenu, $order]);
            echo json_encode(["success" => true, "id" => $pdo->lastInsertId()]);
            break;

        case "update":
            $pageId = $_POST["id"] ?? null;
            $title = trim($_POST["title"] ?? "");
            $slug = trim($_POST["slug"] ?? "");
            $content = $_POST["content"] ?? "";
            $metaDesc = trim($_POST["meta_description"] ?? "");
            $isActive = isset($_POST["is_active"]) ? (int)$_POST["is_active"] : 1;
            $showMenu = isset($_POST["show_in_menu"]) ? (int)$_POST["show_in_menu"] : 0;

            if (empty($pageId) or empty($title) or empty($slug)) { echo json_encode(["success" => false, "error" => "ID, titulo e slug obrigatorios"]); exit; }

            $stmt = $pdo->prepare("SELECT id FROM store_pages WHERE store_id = ? AND slug = ? AND id != ?");
            $stmt->execute([$storeId, $slug, $pageId]);
            if ($stmt->fetch()) { echo json_encode(["success" => false, "error" => "Slug ja existe em outra pagina"]); exit; }

            $stmt = $pdo->prepare("UPDATE store_pages SET title = ?, slug = ?, content = ?, meta_description = ?, is_active = ?, show_in_menu = ?, updated_at = NOW() WHERE id = ? AND store_id = ?");
            $stmt->execute([$title, $slug, $content, $metaDesc, $isActive, $showMenu, $pageId, $storeId]);
            echo json_encode(["success" => true]);
            break;

        case "delete":
            $pageId = $_POST["id"] ?? null;
            if (!$pageId) { echo json_encode(["success" => false, "error" => "ID nao informado"]); exit; }
            $stmt = $pdo->prepare("DELETE FROM store_pages WHERE id = ? AND store_id = ?");
            $stmt->execute([$pageId, $storeId]);
            echo json_encode(["success" => true]);
            break;

        default:
            echo json_encode(["success" => false, "error" => "Acao invalida"]);
    }
} catch (Exception $e) {
    echo json_encode(["success" => false, "error" => "Erro interno: " . $e->getMessage()]);
} catch (Error $e) {
    echo json_encode(["success" => false, "error" => "Erro fatal: " . $e->getMessage()]);
}
