<?php
// firefly-section-add-with-template.php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Optional: force login + capability check
if ( ! is_user_logged_in() || ! current_user_can( 'edit_pages' ) ) {
    wp_die( 'You must be logged in with permission to edit pages.' );
}

$errors          = [];
$success_message = '';

// Resolve templates directory + URL
$templates_dir     = trailingslashit( get_stylesheet_directory() ) . 'sections';
$template_url_base = trailingslashit( get_stylesheet_directory_uri() ) . 'sections/';

// Build template list + map from .txt files in /sections
$templates       = []; // [ 'Jeff' => 'Jeff.txt', ... ]
$template_labels = []; // just the keys, for easy looping

if ( is_dir( $templates_dir ) ) {
    $template_files = glob( $templates_dir . '/*.txt' );
    if ( ! empty( $template_files ) ) {
        foreach ( $template_files as $file_path ) {
            $name               = pathinfo( $file_path, PATHINFO_FILENAME ); // e.g. Jeff
            $filename           = basename( $file_path );                    // e.g. Jeff.txt
            $templates[ $name ] = $filename;
            $template_labels[]  = $name;
        }
    }
}

// Determine target page ID
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
    $target_page_id = isset( $_POST['ff_page_id'] ) ? intval( $_POST['ff_page_id'] ) : 0;
} else {
    // First load: get it from the query string ?post_id=123
    $target_page_id = isset( $_GET['post_id'] ) ? intval( $_GET['post_id'] ) : 0;
}

// Fetch the target page
$target_post = null;
if ( $target_page_id ) {
    $target_post = get_post( $target_page_id );
    if ( ! $target_post || $target_post->post_type !== 'page' ) {
        $errors[] = 'The specified page could not be found.';
    } elseif ( ! current_user_can( 'edit_page', $target_page_id ) ) {
        $errors[] = 'You do not have permission to edit this page.';
    }
} else {
    $errors[] = 'No target page was specified.';
}

// Current template (from POST)
$current_template = isset( $_POST['ff_template'] )
    ? sanitize_text_field( wp_unslash( $_POST['ff_template'] ) )
    : '';

// Insert position (top or bottom). Default = bottom.
$insert_position = isset( $_POST['ff_insert_position'] )
    ? sanitize_text_field( wp_unslash( $_POST['ff_insert_position'] ) )
    : 'bottom';

if ( $_SERVER['REQUEST_METHOD'] === 'POST' && empty( $errors ) ) {

    // Basic nonce check
    if ( ! isset( $_POST['ff_add_section_nonce'] ) || ! wp_verify_nonce( $_POST['ff_add_section_nonce'], 'ff_add_section_template' ) ) {
        $errors[] = 'Security check failed. Please try again.';
    } else {

        $template = isset( $_POST['ff_template'] )
            ? sanitize_text_field( wp_unslash( $_POST['ff_template'] ) )
            : '';

        // Normalise insert position
        $insert_position = ( $insert_position === 'top' ) ? 'top' : 'bottom';

        // Check that the chosen template corresponds to a discovered .txt file
        if ( ! isset( $templates[ $template ] ) ) {
            $errors[] = 'Please select a template.';
        }

        if ( empty( $templates ) ) {
            $errors[] = 'No templates found in the templates folder.';
        }

        if ( ! $target_post ) {
            $errors[] = 'The target page is invalid.';
        }

        if ( empty( $errors ) ) {

            // Build full path to the txt file
            $filename = $templates[ $template ];      // e.g. Jeff.txt
            $filepath = trailingslashit( $templates_dir ) . $filename;

            $content = '';

            if ( file_exists( $filepath ) && is_readable( $filepath ) ) {

                clearstatcache(true);
                $raw = file_get_contents( $filepath );

                if ( $raw !== false ) {
                    // You can tweak this if you want to wrap in <p> tags etc.
                    $content = $raw;
                }
            }

            if ( $content === '' ) {
                $errors[] = 'The selected template file is empty or could not be read.';
            } else {
                // Append or prepend to the existing page content
                $existing_content = (string) $target_post->post_content;

                if ( $insert_position === 'top' ) {
                    $new_content = $content . "\n\n" . $existing_content;
                } else {
                    // default: bottom
                    $new_content = $existing_content . "\n\n" . $content;
                }

                $update_args = [
                    'ID'           => $target_page_id,
                    'post_content' => $new_content,
                ];

                $result = wp_update_post( $update_args, true );

                if ( is_wp_error( $result ) ) {
                    $errors[] = 'Could not update the page: ' . $result->get_error_message();
                } else {
                    // Redirect back to the edited page
                  // Redirect back to the edited page
$url = get_permalink( $target_page_id );
if ( $url ) {
    if ( ! headers_sent() ) {
        // Normal redirect (best option)
        wp_safe_redirect( $url );
        exit;
    } else {
        // Fallback if something already started output
        echo '<script>window.location.href = ' . json_encode( $url ) . ';</script>';
        exit;
    }
} else {
    $success_message = 'Section added, but could not determine the page URL.';
}

                }
            }
        }
    }
}

// --- Output form ---
?>
<div class="wrapp" style="margin:0 auto;max-width:1660px !important;width:100%;">
    <h1>Add a section</h1>

    <?php if ( $target_post ): ?>
        <p><strong>Target page:</strong> <?php echo esc_html( get_the_title( $target_post ) ); ?></p>
    <?php endif; ?>

    <?php if ( ! empty( $errors ) ): ?>
        <div style="border:1px solid #c00;padding:10px;margin-bottom:20px;background:#fee;">
            <strong>There were problems:</strong>
            <ul>
                <?php foreach ( $errors as $e ): ?>
                    <li><?php echo esc_html( $e ); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ( $success_message ): ?>
        <div style="border:1px solid #0a0;padding:10px;margin-bottom:20px;background:#efe;">
            <?php echo esc_html( $success_message ); ?>
        </div>
    <?php endif; ?>

    <form method="post">
        <?php wp_nonce_field( 'ff_add_section_template', 'ff_add_section_nonce' ); ?>

        <!-- Hidden: target page ID -->
        <input type="hidden" name="ff_page_id"
               value="<?php echo esc_attr( $target_page_id ); ?>">

        <p><strong>Add this section:</strong></p>
        <p>
            <label>
                <input type="radio"
                       name="ff_insert_position"
                       value="top" <?php checked( $insert_position, 'top' ); ?>>
                at the top of the page
            </label><br>
            <label>
                <input type="radio"
                       name="ff_insert_position"
                       value="bottom" <?php checked( $insert_position, 'bottom' ); ?>>
                at the bottom of the page
            </label>
        </p>

        <p><strong>Template</strong></p>

        <?php
        // Hidden field to store the chosen template label (basename without .txt)
        ?>
        <input type="hidden" name="ff_template" id="ff_template_input"
               value="<?php echo esc_attr( $current_template ); ?>">

        <style>
.ff-template-grid {
    display: block !important;

    /* Masonry settings */
    column-width: 300px !important;
    column-gap: 12px;

    /* Center the whole block */
    max-width: 1500px;   /* or any width you want */
    margin-left: auto;
    margin-right: auto;
    margin-top: 10px;
    margin-bottom: 20px;
}

.ff-template-card {
    display: inline-block;            /* needed for columns */
    width: 100%;                      /* fill the column, ~300px */
    box-sizing: border-box;
    margin: 0 0 12px;
    border: 3px solid #ccc;
    border-radius: 6px;
    padding: 8px;
    text-align: center;
    cursor: pointer;
    background: #fff;
    transition: border-color 0.15s ease, box-shadow 0.15s ease;
}

.ff-template-card img {
    width: 100%;                      /* ~300px wide */
    height: auto;                     /* variable height */
    display: block;
    margin: 0 auto 6px;
}

.ff-template-card .ff-template-name {
    font-weight: 600;
    font-size: 14px;
}

.ff-template-card.is-selected {
    border-color: red;
    box-shadow: 0 0 0 2px rgba(255, 0, 0, 0.15);
}
        </style>

        <div class="ff-template-grid">
            <?php if ( ! empty( $template_labels ) ) : ?>
                <?php foreach ( $template_labels as $t ) :
                    // If an image with the same name exists, use it, otherwise use blank.png
                    $image_path = trailingslashit( $templates_dir ) . $t . '.png';
                    if ( file_exists( $image_path ) ) {
                        $img_url = $template_url_base . $t . '.png';
                    } else {
                        $img_url = $template_url_base . 'blank.png';
                    }

                    $selected_class = ( $current_template === $t ) ? ' is-selected' : '';
                ?>
                    <div class="ff-template-card<?php echo esc_attr( $selected_class ); ?>"
                         data-template="<?php echo esc_attr( $t ); ?>">
                        <img src="<?php echo esc_url( $img_url ); ?>"
                             alt="<?php echo esc_attr( $t ); ?>">
                        <div class="ff-template-name"><?php echo esc_html( $t ); ?></div>
                    </div>
                <?php endforeach; ?>
            <?php else : ?>
                <p>No templates found in the templates folder.</p>
            <?php endif; ?>
        </div>

        <script>
        document.addEventListener('DOMContentLoaded', function () {
            const cards  = document.querySelectorAll('.ff-template-card');
            const hidden = document.getElementById('ff_template_input');

            cards.forEach(function (card) {
                card.addEventListener('click', function () {
                    // Remove selection from all
                    cards.forEach(function (c) {
                        c.classList.remove('is-selected');
                    });

                    // Mark this one as selected
                    card.classList.add('is-selected');

                    // Set hidden field value
                    if (hidden) {
                        hidden.value = card.getAttribute('data-template') || '';
                    }
                });
            });
        });
        </script>

        <p align="center">
            <button type="submit"
                    style="padding:8px 16px;background:#2271b1;border:none;color:#fff;border-radius:20px;cursor:pointer;font-size:40px;">
                Save
            </button>
        </p>
    </form>
</div>

<?php
$current_user = wp_get_current_user();

if ( $current_user instanceof WP_User ) {
    if ( strtolower($current_user->user_email) === 'drjeffsimmonds@gmail.com' ) {
?>
https://generic-ecommerce-sc.websitedemos.top/<BR>
https://furniture-store-sc.websitedemos.top/<BR>
https://ceramic-product-store.websitedemos.top/<BR>
https://multipurpose-10.websitedemos.top/<BR>
https://multipurpose12.websitedemos.top/<BR>
https://multipurpose26.websitedemos.top/<BR>
https://multipurpose27.websitedemos.top/<BR>
<?php

    }}
?>