<?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");
    }

    $input = json_decode(file_get_contents("php://input"), true);
    // 📥 Inputs
    $id = $input['id'] ?? null;
    $policyType = $input['policy_type'] ?? null;
    $description = $input['description'] ?? null;
    // ❌ Validation
    if (!$id || !$policyType || !$description) {
        sendResponse(400, "All fields are required");
    }

    if (!is_numeric($id)) {
        sendResponse(400, "Invalid policy ID");
    }

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

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

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

    // 🔍 Check policy exists
    $checkStmt = $conn->prepare("SELECT id FROM pages WHERE id = ?");
    $checkStmt->execute([$id]);

    if ($checkStmt->rowCount() === 0) {
        sendResponse(404, "Policy not found");
    }

    // 🔁 Prevent duplicate policy type (except current)
    $dupStmt = $conn->prepare(
        "SELECT id FROM pages WHERE type = ? AND id != ?"
    );
    $dupStmt->execute([$policyType, $id]);

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

    // 📝 Update policy
    $stmt = $conn->prepare(
        "UPDATE pages 
         SET type = ?, description = ? 
         WHERE id = ?"
    );
    $stmt->execute([$policyType, $description, $id]);

    sendResponse(200, "Policy updated successfully");

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