<?php
include "../../root.class.php";
$html = new html();
$db = new db_safeguard();
$html->add_styles_page();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $docName = preg_replace('/[^a-zA-Z0-9_]/', '_', $_POST['doc_name']);
    $formContent = $_POST['form_html'];

    if (!is_dir("forms")) {
        mkdir("forms");
    }

    // Add your PHP header before the saved form
    $phpdata = "<?php
    include \"../../root.class.php\";
    \$html = new html();
    \$db = new db_safeguard();
    \$html->add_styles_page();
    \n?>\n
    <div class='form_down'>
    \n $formContent
    \n</div>";

    file_put_contents("forms/{$docName}.php", $phpdata);
    // echo "<p>✅ Form saved as <strong>forms/{$docName}.php</strong></p>";
}

$submit_btn = new button();
$submit_btn->class("submit_btn");
$submit_btn->value("SAVE FORM");
$submit_btn->onclick("saveForm()");
?>

<script>
    let tableCount = 0;

    // Add heading
    function addHeading() {
        const text = prompt("Enter heading text:");
        if (text) {
            document.getElementById("form_content").innerHTML += `<h1 contenteditable='true'>${text}</h1>`;
        }
    }

    // Add table
    function addTable() {
        tableCount++;
        const rows = parseInt(prompt("Number of rows?"));
        const cols = parseInt(prompt("Number of columns?"));

        if (rows > 0 && cols > 0) {
            let tableHTML = `<table id="table_${tableCount}" style='width:90%'><tr>`;
            for (let c = 0; c < cols; c++) tableHTML += `<th contenteditable='true'>ADD HEADER</th>`;
            tableHTML += "</tr>";

            for (let r = 0; r < rows; r++) {
                tableHTML += "<tr>";
                for (let c = 0; c < cols; c++) {
                    tableHTML += `<td onclick="editCell(this)">ADD DATA TYPE</td>`;
                }
                tableHTML += "</tr>";
            }
            tableHTML += "</table>";
            document.getElementById("form_content").innerHTML += tableHTML;
        }
    }

    // Edit table cell
    function editCell(cell) {
        let existingElement = cell.querySelector("input, select");

        if (existingElement) {
            // EDIT EXISTING ELEMENT
            if (existingElement.tagName.toLowerCase() === "input") {
                const newType = prompt("Enter new input type (text, date, number, email, time, password):", existingElement.type);
                const newName = prompt("Enter input name:", existingElement.name);
                const newPlaceholder = prompt("Enter placeholder:", existingElement.placeholder);
                existingElement.type = newType;
                existingElement.name = newName;
                existingElement.placeholder = newPlaceholder;
            }
            else if (existingElement.tagName.toLowerCase() === "select") {
                const newName = prompt("Enter select name:", existingElement.name);
                const newOptions = prompt("Enter options separated by commas:",
                    Array.from(existingElement.options).map(opt => opt.text).join(","));
                existingElement.name = newName;
                existingElement.innerHTML = newOptions.split(",").map(o => `<option value='${o.trim()}'>${o.trim()}</option>`).join("");
            }
        } else {
            // ADD NEW ELEMENT IF EMPTY
            const type = prompt("Choose type (text, select, file, signature, label):").toLowerCase();
            let cellHTML = "";

            if (type === "text") {
                const name = prompt("Enter input name:");
                const placeholder = prompt("Enter placeholder:", name);
                const inputType = prompt("Enter input type (text, date, number, email, time, password):", "text");
                cellHTML = `<input type='${inputType}' class='inputs' style='width:90%' name='${name}' placeholder='${placeholder}'>`;
            }
            else if (type === "select") {
                const name = prompt("Enter select name:");
                const opts = prompt("Enter options separated by commas:").split(",");
                cellHTML = `<select name='${name}' class='inputs' style='width:90%'>` +
                    opts.map(o => `<option value='${o.trim()}'>${o.trim()}</option>`).join("") + `</select>`;
            }
            else if (type === "file") {
                const name = prompt("Enter file input name:");
                cellHTML = `<input type='file' class='inputs' style='width:90%' name='${name}'>`;
            }
            else if (type === "signature") {
                const label = prompt("Signature for who? (e.g. Driver, QA Manager)");
                const sigName = label.toLowerCase().replace(/ /g, "_") + "_signature";
                cellHTML = `<label>${label}:</label><br><input type='text' class='inputs' style='width:90%' name='${sigName}' placeholder='Sign here'>`;
            }
            else if (type === "label") {
                cellHTML = prompt("Enter static text for cell:");
            }
            cell.innerHTML = cellHTML;
        }
    }

    // Add single text row
    function addTextRow() {
        const text = prompt("Enter text for row:");
        if (text) {
            document.getElementById("form_content").innerHTML += `
        <div class='text-row' contenteditable='true'>
        <p>${text}</p>
        </div>`;
        }
    }

    function addInput() {
        const type = prompt("Enter input type (text, date, number, datetime-local):", "text").toLowerCase();
        const name = prompt("Enter input name:");
        const placeholder = prompt("Enter placeholder text (optional):", name);

        if (name) {
            document.getElementById("form_content").innerHTML +=
                `<input type='${type}' class='inputs' name='${name}' id='${name}' placeholder='${placeholder}' style='width:90%'>`;
        }
    }

    function addLabel() {
        const text = prompt("Enter label text:");
        if (text) {
            document.getElementById("form_content").innerHTML += `<label>${text}</label>`;
        }
    }

    function addSelect() {
        const name = prompt("Enter select name:");
        const opts = prompt("Enter options separated by commas:").split(",");
        let html = `<select name='${name}' id='${name}' class='inputs'>`;
        opts.forEach(o => html += `<option value='${o.trim()}'>${o.trim()}</option>`);
        html += "</select>";
        document.getElementById("form_content").innerHTML += html;
    }

    function addFileUpload() {
        const name = prompt("Enter file input name:");
        document.getElementById("form_content").innerHTML += `<input type='file' class='inputs' name='${name}' id='${name}' style='width:50%'>`;
    }

    function addSignature() {
        const label = prompt("Signature for who? (e.g. Driver, QA Manager)");
        const sigName = label.toLowerCase().replace(/ /g, "_") + "_signature";
        document.getElementById("form_content").innerHTML += `<div><label>${label} Signature:</label><br><input type='text' class='inputs' name='${sigName}' placeholder='Sign here'></div>`;
    }

    function saveForm() {
        const docName = document.getElementById("doc_name").value.trim();
        const formHTML = document.getElementById("form_content").innerHTML;
        document.getElementById("form_html").value = `<form method='post' enctype='multipart/form-data'>${formHTML}</form>`;
        return docName !== "";
    }
</script>

<div class="form_down">
    <h1>FORM BUILDER</h1>
    <form method="post" onsubmit="return saveForm();">
        <style>
            table,
            th,
            td {
                border: 2px solid black;
                border-collapse: collapse;
                padding: 5px;
            }
        </style>
        <label>Document Name: </label>
        <input type="text" id="doc_name" name="doc_name" class="inputs" required>
        <br><br>

        <button type="button" class="submit_btn" onclick="addHeading()">Add Heading</button>
        <button type="button" class="submit_btn" onclick="addTextRow()">Add Text Row</button>

        <button type="button" class="submit_btn" onclick="addTable()">Add Table</button>

        <button type="button" class="submit_btn" onclick="addLabel()">Add Label</button>
        <button type="button" class="submit_btn" onclick="addInput()">Add Input</button>
        <button type="button" class="submit_btn" onclick="addSelect()">Add Select</button>

        <button type="button" class="submit_btn" onclick="addFileUpload()">Add File Upload</button>
        <button type="button" class="submit_btn" onclick="addSignature()">Add Signature</button>

        <br>

        <div id="form_content" class="preview"
            style="width:100%; display:flex; flex-direction:column; align-items: center;"></div>

        <input type="hidden" id="form_html" name="form_html">
        <br>
        <?php
        $submit_btn->add();
        ?>

    </form>
</div>
