/* ============================
   SHORTCODE: AJAX uploadformulier
   ============================ */
add_shortcode('bestand_upload_ajax', function () {
    ob_start(); ?>

    <form id="ajaxUploadForm" enctype="multipart/form-data">
        <label>Naam:<br>
            <input type="text" name="naam" required>
        </label><br><br>

        <label>E-mail:<br>
            <input type="email" name="email" required>
        </label><br><br>

        <label>Bericht:<br>
            <textarea name="bericht" rows="4"></textarea>
        </label><br><br>

        <label>Bijlage:<br>
            <input type="file" name="bijlage" required>
        </label><br><br>

        <button type="submit">Versturen</button>
    </form>

    <div id="ajaxUploadResult" style="margin-top:15px;"></div>

    <script>
    document.getElementById('ajaxUploadForm').addEventListener('submit', function(e) {
        e.preventDefault();

        let formData = new FormData(this);
        formData.append('action', 'bestand_upload_ajax_action');

        fetch('<?php echo admin_url("admin-ajax.php"); ?>', {
            method: 'POST',
            body: formData
        })
        .then(res => res.text())
        .then(data => {
            document.getElementById('ajaxUploadResult').innerHTML = data;
        })
        .catch(() => {
            document.getElementById('ajaxUploadResult').innerHTML = "Er ging iets mis.";
        });
    });
    </script>

    <?php
    return ob_get_clean();
});


/* ============================
   AJAX HANDLER
   ============================ */
add_action('wp_ajax_bestand_upload_ajax_action', 'bestand_upload_ajax_action');
add_action('wp_ajax_nopriv_bestand_upload_ajax_action', 'bestand_upload_ajax_action');

function bestand_upload_ajax_action() {

    $naam    = sanitize_text_field($_POST['naam'] ?? '');
    $email   = sanitize_email($_POST['email'] ?? '');
    $bericht = sanitize_textarea_field($_POST['bericht'] ?? '');

    // Bijlage uploaden via WordPress
    $attachment_path = '';
    if (!empty($_FILES['bijlage']['tmp_name'])) {
        $upload = wp_handle_upload($_FILES['bijlage'], ['test_form' => false]);
        if (!empty($upload['file'])) {
            $attachment_path = $upload['file'];
        }
    }

    // E-mail opbouwen
    $to      = "bestandenopsturen@allesbedruktplaza.nl";
    $subject = "Nieuw bestand ingestuurd via AJAX formulier";
    $body    = "
        <strong>Naam:</strong> $naam<br>
        <strong>E-mail:</strong> $email<br><br>
        <strong>Bericht:</strong><br>" . nl2br($bericht);

    $headers = [
        'Content-Type: text/html; charset=UTF-8',
        'From: Uploadformulier <bestandenopsturen@allesbedruktplaza.nl>'
    ];

    // Versturen met of zonder bijlage
    if ($attachment_path) {
        wp_mail($to, $subject, $body, $headers, [$attachment_path]);
    } else {
        wp_mail($to, $subject, $body, $headers);
    }

    echo "<strong>Bedankt! Je bestand en gegevens zijn verstuurd.</strong>";
    wp_die();
}