<?php
// Load existing history
$history = [];
if (file_exists('policies.json')) {
    $history = json_decode(file_get_contents('policies.json'), true);
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <title>HelpLine Policy Editor</title>
    <style>
        body {
            font-family: sans-serif;
            margin: 30px;
            background-color: #f5f5f5;
        }

        h2 {
            margin-bottom: 10px;
        }

        #editor {
            border: 1px solid #ccc;
            padding: 15px;
            min-height: 300px;
            background-color: white;
        }

        .toolbar button {
            margin: 5px;
        }

        button {
            padding: 8px 12px;
            font-size: 14px;
        }

        .history {
            margin-top: 40px;
        }

        .history-item {
            background: #fff;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
        }

        .timestamp {
            font-size: 12px;
            color: #777;
        }
    </style>
</head>
<body>

<h2>📄 HelpLine Policy Editor</h2>

<!-- Toolbar -->
<div class="toolbar">
    <button onclick="execCmd('bold')">Bold</button>
    <button onclick="execCmd('italic')">Italic</button>
    <button onclick="execCmd('underline')">Underline</button>
    <button onclick="execCmd('insertUnorderedList')">List</button>
    <button onclick="execCmd('formatBlock','h1')">H1</button>
    <button onclick="execCmd('formatBlock','h2')">H2</button>
</div>

<!-- Editor -->
<div id="editor" contenteditable="true">
    এখানে পলিসি লিখুন...
</div>

<br>
<button onclick="submitPolicy()">✅ Save Policy</button>

<!-- History Section -->
<div class="history">
    <h3>📚 Policy History</h3>
    <?php foreach (array_reverse($history) as $index => $item): ?>
        <div class="history-item">
            <div class="timestamp">🕒 <?= $item['timestamp'] ?></div>
            <div class="content"><?= $item['policy_text'] ?></div>
            <button onclick='editPolicy(`<?= htmlspecialchars($item["policy_text"], ENT_QUOTES) ?>`)'>✏️ Edit</button>
        </div>
    <?php endforeach; ?>
</div>

<script>
    function execCmd(cmd, val = null) {
        document.execCommand(cmd, false, val);
    }

    function submitPolicy() {
        const policyText = document.getElementById('editor').innerHTML;

        fetch('save_policy.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ policy_text: policyText })
        })
        .then(res => res.json())
        .then(data => {
            alert("✅ Policy saved successfully!");
            location.reload();
        });
    }

    function editPolicy(content) {
        document.getElementById('editor').innerHTML = content;
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }
</script>

</body>
</html>
