<?php
try {

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

    include_once dirname(__DIR__, 2) . "/config/dbcon.php";
    include_once dirname(__DIR__, 2) . "/helpers/api_helper.php";

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(405, "Method Not Allowed");
    }

    // 📥 Inputs
    $input = json_decode(file_get_contents("php://input"), true);
    $policyType = $input['policy_type'] ?? null;
    $description = $input['description'] ?? null;

    // ❌ Validation
    if (!$policyType || !$description) {
        sendResponse(400, "All fields are required");
    }

    if (strlen(trim($description)) < 20) {
        sendResponse(400, "Description must be at least 20 characters");
    }

    // ✅ Allowed policy types (security check)
    $allowedPolicies = [
        'privacy_policy',
        'terms_conditions',
        'cookie_policy',
        'refund_policy',
        'disclaimer',
        'equal_opportunity',
        'security_policy'
    ];

    if (!in_array($policyType, $allowedPolicies)) {
        sendResponse(400, "Invalid policy type");
    }

    // 🔍 Prevent duplicate policy type
    $checkStmt = $conn->prepare("SELECT id FROM pages WHERE type = ?");
    $checkStmt->execute([$policyType]);

    if ($checkStmt->rowCount() > 0) {
        sendResponse(400, "This policy already exists");
    }

    // 🧾 Insert policy
    $stmt = $conn->prepare(
        "INSERT INTO pages (type, description) VALUES (?, ?)"
    );
    $stmt->execute([$policyType, $description]);

    sendResponse(200, "Policy added successfully");

} catch (PDOException $e) {
    sendResponse(500, "Server Error");
}
