<?php

// firefly-page-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 add pages.' );
}

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

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

// Build template list + map from .txt files in /templates
$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;
        }
    }
}

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

// Process form submission
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {

    // FIXED: Use the same nonce action and field name as in the form
    check_admin_referer( 'ff_add_page_template', 'ff_add_page_nonce' );

    // Collect and sanitise form fields
    $page_name   = isset( $_POST['ff_page_name'] ) ? sanitize_text_field( wp_unslash( $_POST['ff_page_name'] ) ) : '';
    $page_slug   = isset( $_POST['ff_page_slug'] ) ? sanitize_title( wp_unslash( $_POST['ff_page_slug'] ) ) : '';
    $template    = isset( $_POST['ff_template'] ) ? sanitize_text_field( wp_unslash( $_POST['ff_template'] ) ) : '';
    $parent_page = isset( $_POST['ff_parent_page'] ) ? intval( $_POST['ff_parent_page'] ) : 0;

    if ( $page_name === '' ) {
        $errors[] = 'Please enter a page name.';
    }

    // 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 directory.';
    }

    if ( empty( $errors ) ) {

        $template_filename = $templates[ $template ];
        $filepath          = trailingslashit( $templates_dir ) . $template_filename;

        $content = '';

        if ( file_exists( $filepath ) && is_readable( $filepath ) ) {
            $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[] = 'Template file was empty or could not be read.';
        } else {

            $new_page = [
                'post_title'   => $page_name,
                'post_content' => $content,
                'post_status'  => 'publish',
                'post_type'    => 'page',
            ];

            if ( $page_slug !== '' ) {
                $new_page['post_name'] = $page_slug;
            }

            if ( $parent_page > 0 ) {
                $new_page['post_parent'] = $parent_page;
            }

            $page_id = wp_insert_post( $new_page, true );

            if ( is_wp_error( $page_id ) ) {
                $errors[] = 'Could not create page: ' . $page_id->get_error_message();
            } else {
                // Redirect to the new page (robust: HTTP redirect + JS fallback)
                $url = get_permalink( $page_id );
                if ( $url ) {
                    if ( ! headers_sent() ) {
                        wp_safe_redirect( $url );
                        exit;
                    } else {
                        echo '<script>window.location.href = ' . json_encode( $url ) . ';</script>';
                        exit;
                    }
                } else {
                    $success_message = 'Page created, but could not determine its URL.';
                }
            }
        }
    }
}

// --- Output form ---

?>
<div class="wrapp" style="margin:0 auto;max-width:1060px !important;">
    <h1>Add a new page with a template</h1>

    <?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 $error ): ?>
                    <li><?php echo esc_html( $error ); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ( ! empty( $success_message ) ): ?>
        <div style="border:1px solid #0c0;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_page_template', 'ff_add_page_nonce' ); ?>

        <p>
            <label for="ff_page_name"><strong>Page name</strong></label><br>
            <input type="text"
                   id="ff_page_name"
                   name="ff_page_name"
                   required
                   value="<?php echo isset( $_POST['ff_page_name'] ) ? esc_attr( wp_unslash( $_POST['ff_page_name'] ) ) : ''; ?>"
                   style="width:100%;max-width:400px;padding:6px;">
        </p>

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

        <input type="hidden" name="ff_template" id="ff_template_input"
               value="<?php echo esc_attr( $current_template ); ?>">

        <style>
.ff-template-grid {
    display: block !important;
    column-width: 300px !important;
    column-gap: 12px;
    max-width: 1000px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 10px;
    margin-bottom: 20px;
}

.ff-template-card {
    display: inline-block;
    width: 100%;
    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%;
    height: auto;
    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 ) :
                    $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 () {
                    cards.forEach(function (c) {
                        c.classList.remove('is-selected');
                    });

                    card.classList.add('is-selected');

                    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>