<?php ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Get the form numbers that were previously selected (toggle = 1)
$selectedQuery = "SELECT formnumber FROM master_formtypes WHERE toggle = 1";
$selectedResult = mysqli_query($GLOBALS['con'], $selectedQuery);
$selectedFormNumbers = [];
while ($row = mysqli_fetch_assoc($selectedResult)) {
    $selectedFormNumbers[] = $row['formnumber']; // Store selected form numbers in an array
}

// Fetch form types from the dd_formtypes table
$result = mysqli_query($master, "SELECT formnumber, formtype, description, shortdesc, regs FROM dd_formtypes") or die(mysqli_error($GLOBALS['$master']));

?>
<div class="row mb-4">
    <div class="col-12 col-md-6">
        <div class="note note-primary mb-3">
            <strong>Formtype Selection:</strong> This section alows you to determine which of the default <b>EnRep</b>
            built-in reports you wish to have accessible in the new report window. Your organisation may not require the
            full list
            so you
            can customise your display and options to suite your needs.<br>Only those you have set active will be
            displayed, including any custom reports you may have.
        </div>
    </div>
    <div class="col-12 col-md-6">
        <img src="<?= ROOT_URL ?>/images/formSelect.png" class="img-fluid shadow-2-strong">
    </div>
</div>

<?php

// Check if any form types were fetched
if (mysqli_num_rows($result) > 0) {
    // Form starts
    echo '<form id="form-select" action="form_select_functions.php" method="post">';
    echo '<div class="row">'; // Bootstrap row to hold cards

    // Display each form type in a card with a switch
    while ($row = mysqli_fetch_assoc($result)) {
        $formnumber = $row['formnumber'];
        $formtype = $row['formtype'];
        $description = $row['description'];
        $shortdesc = $row['shortdesc'];
        $regs = $row['regs'];

        // Check if this form number was previously selected
        $checked = in_array($formnumber, $selectedFormNumbers) ? 'checked' : '';

        // Start of card
        echo '<div class="col-md-4 mb-4">';
        echo '<div class="card h-100">';
        echo '<div class="card-body">';
        echo '<h5 class="card-title">Form Type: ' . $formtype . '</h5>';
        echo '<p class="card-text"><strong>Description:</strong> ' . $description . '</p>';
        echo '<p class="card-text"><strong>Regulation:</strong> ' . $regs . '</p>';

        // Switch (Checkbox) Input
        echo '<div class="form-check form-switch">';
        echo '<input class="form-check-input" type="checkbox" role="switch" id="switch' . $formnumber . '" name="formtypes[' . $formnumber . ']" value="1" ' . $checked . '>';
        echo '<label class="form-check-label" for="switch' . $formnumber . '">Use this form type?</label>';
        echo '</div>'; // End of switch

        echo '</div>'; // End of card-body
        echo '</div>'; // End of card
        echo '</div>'; // End of col-md-4
    }

    echo '</div>'; // End of row

    // Submit button
    echo '<div class="col-12 text-center"><button id="btn_create" class="btn btn-info hidden" type="button" onclick="submitForm()">Submit Choices</button></div>';

    // Form ends
    echo '<input type="hidden" name="tenant" value="' . TENANT_URL . '"></form>';
} else {
    echo "No form types found.";
}
?>

<script>
function submitForm() {
    const form = document.getElementById('form-select'); // Get the form element
    const formData = new FormData(form); // Create a FormData object from the form

    // Use fetch to submit the form asynchronously
    fetch(ROOT_URL + '/includes/master/form_select_functions.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.text()) // Expect text or JSON response
        .then(data => {
            console.log(data); // Log the server's response for debugging
            showResponse('success', 'Form submitted successfully!');
        })
        .catch(error => {
            console.error('Error:', error);
            showResponse('danger', 'There was an error submitting the form.');
        });
}


document.getElementById('navBox').innerHTML = '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Formtype Selection</li>';
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("footerControls").innerHTML =
        '<button class="btn btn-secondary" onclick="triggerAction(\'btn_create\')">SUBMIT CHOICES</button>';
});

</script>