<?php
/**
 * Plugin Name: Printable Forms
 * Description: Print-ready forms with conditional templates via shortcode [print_form].
 * Author: Dillon Caldwell
 * Version: 1.0
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: printable-forms
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

add_action('init', function() {
    add_shortcode('print_form', 'pf_render_form');
});

add_action('wp_enqueue_scripts', function() {
    wp_register_script('printable-forms-js', plugins_url('/js/printable-forms.js', __FILE__), ['jquery'], null, true);
    wp_register_style('printable-forms-css', plugins_url('/css/printable-forms.css', __FILE__));
    // wp_enqueue_style('google-fonts', 'https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;500;700&display=swap', array(), null);

    wp_localize_script('printable-forms-js', 'printableFormsVars', [
        'cssUrl' => plugins_url('/css/printable-forms.css', __FILE__)
    ]);
});

function pf_render_form() {
    wp_enqueue_script('printable-forms-js');
    wp_enqueue_style('printable-forms-css');

    ob_start(); ?>
    <form id="pf-form">
        <label for="pf-template">Choose Placard Template:</label>
        <select name="template" id="pf-template">
            <option value="">--Select--</option>
            <option value="football">Football Player</option>
            <option value="cheer">Cheerleader</option>
            <option value="coach">Coach</option>
            <option value="mom">Team Mom</option>
            <option value="admin">Admin</option>
        </select>
        <div id="pf-fields"></div>
        <button class="pf-form-btn" type="submit">Print</button>
    </form>
    <?php
    return ob_get_clean();
}

function pf_get_template_html($template, $data) {
    ob_start();
    $safe_data = array_map('esc_html', (array) $data);
    include plugin_dir_path(__FILE__) . "templates/{$template}.php";
    return ob_get_clean();
}

add_action('wp_ajax_pf_get_template', 'pf_ajax_get_template');
add_action('wp_ajax_nopriv_pf_get_template', 'pf_ajax_get_template');

function pf_ajax_get_template() {
    $template = sanitize_text_field($_POST['template']);
    $data = json_decode(stripslashes($_POST['data']), true);
    echo pf_get_template_html($template, $data);
    wp_die();
}


