<?php
if ( ! defined( 'ABSPATH' ) ) exit;

function aipd_templates_page() {

    /* ===== Save selected templates ===== */
    if ( isset( $_POST['aipd_nonce'] ) && wp_verify_nonce( $_POST['aipd_nonce'], 'aipd_save_templates' ) ) {
        foreach ( ['invoice','delivery','package'] as $type ) {
            if ( isset( $_POST['aipd_template_'.$type] ) ) {
                update_option(
                    'aipd_template_'.$type,
                    sanitize_text_field( $_POST['aipd_template_'.$type] )
                );
            }
        }
        echo '<div class="notice notice-success is-dismissible"><p>'.esc_html__( 'Templates saved successfully.', 'awesome-invoice-delivery-notes-packing-slips' ).'</p></div>';
    }

    $get = fn($k,$d='') => get_option( 'aipd_'.$k, $d );

    // Template definitions
    $templates = [
        'invoice' => [
            'default' => ['name'=>'Default Invoice','preview'=>plugins_url('../assets/previews/invoice-default.png',__FILE__)],
            'modern'  => ['name'=>'Modern Invoice','preview'=>plugins_url('../assets/previews/invoice-modern.png',__FILE__)],
        ],
        'delivery' => [
            'default' => ['name'=>'Default Delivery','preview'=>plugins_url('../assets/previews/delivery-default.png',__FILE__)],
            'compact' => ['name'=>'Compact Delivery','preview'=>plugins_url('../assets/previews/delivery-compact.png',__FILE__)],
        ],
        'package' => [
            'default' => ['name'=>'Default Package','preview'=>plugins_url('../assets/previews/package-default.png',__FILE__)],
            'minimal' => ['name'=>'Minimal Package','preview'=>plugins_url('../assets/previews/package-minimal.png',__FILE__)],
        ],
    ];
    ?>
    <div class="wrap aipd-templates-wrap">
        <h1 class="aipd-heading">
            <span class="dashicons dashicons-format-gallery"></span>
            <?php esc_html_e( 'Awesome Templates', 'awesome-invoice-delivery-notes-packing-slips' ); ?>
        </h1>

        <form method="post">
            <?php wp_nonce_field( 'aipd_save_templates', 'aipd_nonce' ); ?>

            <?php foreach ( $templates as $type => $tpls ) :
                $selected = $get( 'template_'.$type );
                $first    = key( $tpls );
            ?>
            <div class="aipd-section">
                <h2><span class="dashicons dashicons-admin-appearance"></span>
                    <?php echo esc_html( ucfirst( $type ) . ' ' . __( 'Templates', 'awesome-invoice-delivery-notes-packing-slips' ) ); ?>
                </h2>
                <div class="aipd-template-grid">
                    <?php foreach ( $tpls as $id => $tpl ) : ?>
                        <label class="aipd-template-card <?php checked( $selected ?: $first, $id, true ); ?>">
                            <input type="radio"
                                   name="aipd_template_<?php echo esc_attr( $type ); ?>"
                                   value="<?php echo esc_attr( $id ); ?>"
                                   <?php checked( $selected ?: $first, $id ); ?> />
                            <div class="aipd-card-image">
                                <img src="<?php echo esc_url( $tpl['preview'] ); ?>" alt="">
                                <div class="aipd-card-overlay">
                                    <button type="button"
                                            class="button button-secondary aipd-preview-btn"
                                            data-type="<?php echo esc_attr( $type ); ?>"
                                            data-template="<?php echo esc_attr( $id ); ?>">
                                        <?php esc_html_e( 'Preview', 'awesome-invoice-delivery-notes-packing-slips' ); ?>
                                    </button>
                                </div>
                            </div>
                            <div class="aipd-card-title"><?php echo esc_html( $tpl['name'] ); ?></div>
                        </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endforeach; ?>

            <?php submit_button( __( 'Save Templates', 'awesome-invoice-delivery-notes-packing-slips' ) ); ?>
        </form>

        <!-- Modal -->
        <div id="aipd-template-modal" class="aipd-modal">
            <div class="aipd-modal-content">
                <span class="aipd-close dashicons dashicons-no-alt"></span>
                <div id="aipd-modal-body"></div>
            </div>
        </div>
    </div>

    <style>
    .aipd-heading { display:flex; align-items:center; gap:6px; }
    .aipd-section { background:#fff; padding:20px; margin-bottom:25px; border-radius:8px;
                    box-shadow:0 2px 6px rgba(0,0,0,0.05); }
    .aipd-template-grid {
        display:grid;
        grid-template-columns:repeat(auto-fill,minmax(220px,1fr));
        gap:20px;
        margin-top:15px;
    }
    .aipd-template-card {
        background:#fafafa;
        border:2px solid transparent;
        border-radius:6px;
        overflow:hidden;
        cursor:pointer;
        transition:all .25s ease;
        display:block;
        text-align:center;
        position:relative;
    }
    .aipd-template-card input { display:none; }
    .aipd-template-card:hover { box-shadow:0 2px 10px rgba(0,0,0,0.1); }
    .aipd-template-card img { width:100%; height:auto; display:block; }
    .aipd-card-image { position:relative; }
    .aipd-card-overlay {
        position:absolute; top:0; left:0; right:0; bottom:0;
        background:rgba(0,0,0,0.4);
        opacity:0; display:flex; justify-content:center; align-items:center;
        transition:opacity .3s;
    }
    .aipd-template-card:hover .aipd-card-overlay { opacity:1; }
    .aipd-card-title { padding:10px; font-weight:600; background:#fff; }
    .aipd-template-card input:checked + .aipd-card-image,
    .aipd-template-card input:checked ~ .aipd-card-title,
    .aipd-template-card.checked {
        border-color:#0073aa;
        box-shadow:0 0 0 2px #0073aa inset;
    }

    /* Modal */
    .aipd-modal { display:none; position:fixed; z-index:9999; left:0; top:0; width:100%; height:100%;
                  background:rgba(0,0,0,0.6); }
    .aipd-modal-content {
        background:#fff; margin:40px auto; padding:20px; border-radius:8px;
        width:90%; max-width:1000px; position:relative;
    }
    .aipd-close { position:absolute; right:15px; top:15px; cursor:pointer; font-size:24px; }
    </style>

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        const modal = document.getElementById('aipd-template-modal'),
              body  = document.getElementById('aipd-modal-body'),
              close = modal.querySelector('.aipd-close');

        document.querySelectorAll('.aipd-preview-btn').forEach(btn=>{
            btn.addEventListener('click', ()=>{
                body.innerHTML = '<p><?php echo esc_js__( 'Loading preview…', 'awesome-invoice-delivery-notes-packing-slips' ); ?></p>';
                fetch('<?php echo admin_url('admin-ajax.php'); ?>?action=aipd_preview_template&type='
                      + btn.dataset.type + '&template=' + btn.dataset.template)
                  .then(res=>res.text())
                  .then(html => body.innerHTML = html);
                modal.style.display = 'block';
            });
        });
        close.addEventListener('click', ()=> modal.style.display='none');
        window.addEventListener('click', e => { if (e.target === modal) modal.style.display='none'; });
    });
    </script>
    <?php
}

/* AJAX preview handler */
add_action('wp_ajax_aipd_preview_template', function(){
    $type = sanitize_text_field($_GET['type'] ?? '');
    $tpl  = sanitize_text_field($_GET['template'] ?? '');
    $file = plugin_dir_path(__FILE__) . "../templates/{$type}/{$tpl}.php";
    if ( file_exists( $file ) ) {
        include $file;
    } else {
        echo '<p>' . esc_html__( 'Template preview not found.', 'awesome-invoice-delivery-notes-packing-slips' ) . '</p>';
    }
    wp_die();
});
