<?php
/**
 * Template: PDF Templates Management Page
 */

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

$templates = get_option( 'swpdf_templates', array() );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Tab navigation only, no data processing
$active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'list';
?>

<div class="wrap psf-templates-wrap">
    <h1>PDF Templates Manager</h1>
    
    <nav class="nav-tab-wrapper">
        <a href="?page=swpdf-templates&tab=list" class="nav-tab <?php echo esc_attr( $active_tab === 'list' ? 'nav-tab-active' : '' ); ?>">Templates</a>
        <a href="?page=swpdf-templates&tab=upload" class="nav-tab <?php echo esc_attr( $active_tab === 'upload' ? 'nav-tab-active' : '' ); ?>">Upload New</a>
    </nav>
    
    <div class="tab-content">
        <?php if ( $active_tab === 'list' ) : ?>
            <!-- List Templates -->
            <div class="templates-list">
                <h2>Your PDF Templates</h2>
                
                <?php if ( empty( $templates ) ) : ?>
                    <div class="notice notice-info">
                        <p>No templates uploaded yet. <a href="?page=swpdf-templates&tab=upload">Upload your first template</a></p>
                    </div>
                <?php else : ?>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th>Template Name</th>
                                <th>Agreement Type</th>
                                <th>Shortcode</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $templates as $type => $template ) : 
                                // Skip invalid templates without filename
                                if ( empty( $template['filename'] ) ) continue;
                                $template_name = isset( $template['name'] ) ? $template['name'] : ucwords( str_replace( '-', ' ', $type ) );
                                $template_created = isset( $template['created'] ) ? $template['created'] : '';
                                $template_filename = $template['filename'];
                            ?>
                                <tr>
                                    <td><strong><?php echo esc_html( $template_name ); ?></strong></td>
                                    <td><code><?php echo esc_html( $type ); ?></code></td>
                                    <td><code style="background: #f0f0f1; padding: 4px 8px; border-radius: 3px; cursor: pointer;" onclick="if(navigator.clipboard){navigator.clipboard.writeText(this.innerText);alert('Shortcode copied!');}else{prompt('Copy this shortcode:',this.innerText);}" title="Click to copy">[swpdf_signature_form type="<?php echo esc_attr( $type ); ?>"]</code></td>
                                    <td><?php echo $template_created ? esc_html( wp_date( 'M j, Y', strtotime( $template_created ) ) ) : '—'; ?></td>
                                    <td>
                                        <?php $upload_dir = wp_upload_dir(); ?>
                                        <a href="<?php echo esc_url( $upload_dir['baseurl'] . '/psf-templates/' . $template_filename ); ?>" class="button button-small" target="_blank">View PDF</a>
                                        <button class="button button-small button-primary edit-template-labels" data-type="<?php echo esc_attr( $type ); ?>" data-filename="<?php echo esc_attr( $template_filename ); ?>">Edit Labels</button>
                                        <button class="button button-small duplicate-template" data-type="<?php echo esc_attr( $type ); ?>" style="background: #2271b1; color: #fff; border-color: #2271b1;">📋 Duplicate</button>
                                        <button class="button button-small delete-template" data-type="<?php echo esc_attr( $type ); ?>" data-filename="<?php echo esc_attr( $template_filename ); ?>" style="color: #a00;">Delete</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
            
        <?php else : ?>
            <!-- Upload Template -->
            <div class="upload-template">
                <h2>Upload PDF Template</h2>
                <p>Upload your PDF agreement document. Fields will be automatically detected.</p>
                
                <form id="upload-template-form" method="post" enctype="multipart/form-data">
                    <table class="form-table">
                        <tr>
                            <th><label for="template_name">Template Name</label></th>
                            <td>
                                <input type="text" id="template_name" name="template_name" class="regular-text" required placeholder="e.g., Purchase Agreement">
                                <p class="description">A friendly name for this template</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="agreement_type">Agreement Type</label></th>
                            <td>
                                <input type="text" id="agreement_type" name="agreement_type" class="regular-text" required placeholder="e.g., purchase-to-order">
                                <p class="description">A unique identifier (lowercase, hyphens only). Use this in your shortcode: [swpdf_signature_form type="purchase-to-order"]</p>
                            </td>
                        </tr>
                        <tr>
                            <th><label for="pdf_file">PDF File</label></th>
                            <td>
                                <input type="file" id="pdf_file" name="pdf_file" accept=".pdf" required>
                                <p class="description">Upload your PDF agreement document</p>
                            </td>
                        </tr>
                    </table>
                    
                    <p class="submit">
                        <button type="submit" class="button button-primary button-large">Upload & Detect Fields</button>
                    </p>
                    
                    <div id="upload-progress" style="display: none; margin: 20px 0;">
                        <p>Uploading and detecting fields...</p>
                        <div style="background: #f0f0f0; height: 30px; border-radius: 4px; overflow: hidden;">
                            <div id="progress-bar" style="background: #0073aa; height: 100%; width: 0%; transition: width 0.3s;"></div>
                        </div>
                    </div>
                    
                    <div id="upload-message" style="display: none;"></div>
                </form>
                
                <!-- Preview Section -->
                <div id="template-preview" style="display: none; margin-top: 40px; border-top: 2px solid #ddd; padding-top: 30px;">
                    <h2>✅ Upload Successful!</h2>
                    
                    <!-- Signature & Fields Position Settings with Visual Editor -->
                    <div style="background: #f0f6fc; border: 1px solid #c3d9ed; padding: 15px; margin-bottom: 20px; border-radius: 5px;">
                        <h3 style="margin-top: 0; color: #1d4ed8;">✍️ Position Signature & Fields - Drag boxes to position</h3>
                        
                        <!-- Zoom Controls -->
                        <div style="margin-bottom: 15px; padding: 10px; background: #e8f4fc; border-radius: 4px; display: flex; align-items: center; gap: 15px;">
                            <span style="font-weight: 600;">🔍 Zoom:</span>
                            <button type="button" id="zoom-out-btn" class="button button-small">➖</button>
                            <span id="zoom-level-display" style="min-width: 50px; text-align: center; font-weight: bold;">100%</span>
                            <button type="button" id="zoom-in-btn" class="button button-small">➕</button>
                            <button type="button" id="zoom-fit-btn" class="button button-small">Fit</button>
                            <button type="button" id="zoom-150-btn" class="button button-small">150%</button>
                            <button type="button" id="zoom-200-btn" class="button button-small">200%</button>
                            <span style="margin-left: 20px; color: #666; font-size: 12px;">💡 Zoom in for precise positioning</span>
                        </div>
                        
                        <div style="display: flex; gap: 20px; align-items: flex-start;">
                            <!-- PDF Preview with draggable signature box - NOW SCROLLABLE -->
                            <div style="flex: 1; position: relative;">
                                <div id="upload-sig-pdf-container" style="position: relative; border: 2px solid #ccc; background: #525659; overflow: auto; max-height: 700px; min-height: 500px;">
                                    <div id="upload-sig-pdf-wrapper" style="position: relative; display: inline-block;">
                                        <canvas id="upload-sig-pdf-canvas" style="display: block;"></canvas>
                                        <div id="upload-sig-drag-box" style="position: absolute; border: 2px dashed #e74c3c; background: rgba(231, 76, 60, 0.3); cursor: move; display: flex; align-items: center; justify-content: center; font-size: 10px; color: #c0392b; font-weight: bold; z-index: 10;">✍️ SIG</div>
                                        <div id="upload-date-drag-box" style="position: absolute; border: 2px dashed #27ae60; background: rgba(39, 174, 96, 0.3); cursor: move; display: flex; align-items: center; justify-content: center; font-size: 10px; color: #1e8449; font-weight: bold; z-index: 10;">📅 DATE</div>
                                    </div>
                                </div>
                                <p style="font-size: 11px; color: #666; margin-top: 5px;">👆 Drag <span style="color: #e74c3c; font-weight: bold;">red box</span> = signature. Drag <span style="color: #27ae60; font-weight: bold;">green box</span> = date. Drag <span style="color: #0073aa; font-weight: bold;">blue boxes</span> = manual fields.</p>
                                <div style="margin-top: 10px; text-align: center;">
                                    <button type="button" id="prev-preview" class="button">← Previous</button>
                                    <span id="preview-page-info" style="margin: 0 10px;">Page 1 of 1</span>
                                    <button type="button" id="next-preview" class="button">Next →</button>
                                </div>
                            </div>
                            <!-- Position values for Signature -->
                            <div style="width: 150px; position: sticky; top: 20px;">
                                <div style="background: #fdf2f2; padding: 10px; border-radius: 4px; border: 1px solid #e74c3c; margin-bottom: 10px;">
                                    <strong style="color: #c0392b; font-size: 12px;">✍️ Signature Position</strong>
                                    <p style="font-size: 9px; color: #856404; margin: 5px 0 8px 0; background: #fff8e5; padding: 4px; border-radius: 3px;">⚠️ Delete any "Signature" fields below - use this box instead!</p>
                                    <div><label style="display: block; font-size: 10px; color: #666;">X Position</label><input type="number" id="upload-sig-pos-x" value="72" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                    <div style="margin-top: 5px;"><label style="display: block; font-size: 10px; color: #666;">Y (from bottom)</label><input type="number" id="upload-sig-pos-y" value="68" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                    <div style="margin-top: 5px;"><label style="display: block; font-size: 10px; color: #666;">Width</label><input type="number" id="upload-sig-width" value="120" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                    <div style="margin-top: 5px;"><label style="display: block; font-size: 10px; color: #666;">Height</label><input type="number" id="upload-sig-height" value="35" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                </div>
                                <div style="background: #f2fdf4; padding: 10px; border-radius: 4px; border: 1px solid #27ae60; margin-bottom: 10px;">
                                    <label style="display: flex; align-items: center; gap: 5px; cursor: pointer; margin-bottom: 8px;">
                                        <input type="checkbox" id="upload-date-enabled" style="margin: 0;">
                                        <strong style="color: #1e8449; font-size: 12px;">📅 Draw Date Here</strong>
                                    </label>
                                    <p style="font-size: 9px; color: #856404; margin: 0 0 8px 0; background: #fff8e5; padding: 4px; border-radius: 3px;">⚠️ Only enable if PDF has no date field, or delete it below first!</p>
                                    <div id="date-position-inputs" style="opacity: 0.5; pointer-events: none;">
                                        <div><label style="display: block; font-size: 10px; color: #666;">X Position</label><input type="number" id="upload-date-pos-x" value="350" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                        <div style="margin-top: 5px;"><label style="display: block; font-size: 10px; color: #666;">Y (from bottom)</label><input type="number" id="upload-date-pos-y" value="68" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                        <div style="margin-top: 5px;"><label style="display: block; font-size: 10px; color: #666;">Font Size</label><input type="number" id="upload-date-size" value="10" min="6" max="24" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                    </div>
                                </div>
                                <div id="selected-field-position" style="display: none; background: #f0f7fc; padding: 10px; border-radius: 4px; border: 1px solid #0073aa;">
                                    <strong style="color: #0073aa; font-size: 12px;">📝 <span id="selected-field-name">Field</span></strong>
                                    <div style="margin-top: 8px;"><label style="display: block; font-size: 10px; color: #666;">X Position</label><input type="number" id="field-pos-x" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                    <div style="margin-top: 5px;"><label style="display: block; font-size: 10px; color: #666;">Y (from bottom)</label><input type="number" id="field-pos-y" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                    <div style="margin-top: 5px;"><label style="display: block; font-size: 10px; color: #666;">Width</label><input type="number" id="field-pos-width" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                    <div style="margin-top: 5px;"><label style="display: block; font-size: 10px; color: #666;">Height</label><input type="number" id="field-pos-height" style="width: 100%; padding: 4px; font-size: 12px;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Field Mapping Help Section -->
                    <div style="background: #fff8e5; border: 1px solid #ffcc00; padding: 15px; margin-bottom: 20px; border-radius: 5px;">
                        <h4 style="margin-top: 0; color: #856404;">📋 Field Mapping - How data appears in Signed Agreements</h4>
                        <p style="font-size: 12px; color: #666; margin-bottom: 10px;">Use the <strong>"Maps To"</strong> dropdown to specify which database column each field should save to:</p>
                        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; font-size: 12px;">
                            <div style="background: #fff; padding: 10px; border-radius: 4px;"><strong>📛 Customer Name:</strong> Shows in Name column</div>
                            <div style="background: #fff; padding: 10px; border-radius: 4px;"><strong>📧 Email:</strong> Shows in Email column</div>
                            <div style="background: #fff; padding: 10px; border-radius: 4px;"><strong>📱 Phone:</strong> Shows in Phone column</div>
                            <div style="background: #fff; padding: 10px; border-radius: 4px;"><strong>🚗 Stock Number:</strong> Shows in Stock # column</div>
                        </div>
                    </div>
                    
                    <!-- Detected Fields -->
                    <div>
                        <h3>Detected Fields (<span id="field-count">0</span>)</h3>
                        <div id="detected-fields-list" style="max-height: 600px; overflow-y: auto; border: 1px solid #ddd; padding: 15px; background: white;">
                            <!-- Fields will be listed here -->
                        </div>
                        <div style="margin-top: 20px; background: #f0f0f0; padding: 15px; border-radius: 4px;">
                            <p><strong>✏️ Shortcode to use on your page:</strong></p>
                            <input type="text" id="shortcode-display" readonly style="width: 100%; padding: 10px; background: white; font-family: monospace; font-size: 14px;" value="" onclick="this.select();">
                            <p class="description" style="margin-top: 10px;">Copy this shortcode and paste it into any page or post where you want the signature form to appear.</p>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Edit Labels Modal -->
<div id="edit-labels-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 100000; overflow-y: auto;">
    <div style="max-width: 1300px; margin: 30px auto; background: white; border-radius: 8px; padding: 30px; position: relative;">
        <button id="close-edit-modal" style="position: absolute; top: 15px; right: 15px; background: none; border: none; font-size: 24px; cursor: pointer; color: #666;">&times;</button>
        <h2 style="margin-top: 0;">Edit Field Labels</h2>
        <p>Customize how field names appear to users filling the form:</p>
        <div id="edit-labels-content" style="margin: 20px 0;">
            <!-- Content loaded via AJAX -->
        </div>
        <div style="text-align: right; margin-top: 20px; padding-top: 20px; border-top: 1px solid #ddd;">
            <button id="cancel-edit-labels" class="button">Cancel</button>
            <button id="save-edited-labels" class="button button-primary">Save Changes</button>
        </div>
    </div>
</div>



