<?php
/**
 * Template: Settings Page
 * Professional SaaS-style settings UI
 */

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

// Save settings if form submitted
$saved = false;
$settings_nonce = isset( $_POST['swpdf_settings_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['swpdf_settings_nonce'] ) ) : '';
if ( isset( $_POST['swpdf_save_settings'] ) && wp_verify_nonce( $settings_nonce, 'swpdf_save_settings' ) ) {
    $settings = array(
        // Email Settings
        'email_enabled' => isset( $_POST['email_enabled'] ) ? 1 : 0,
        'email_to_admin' => isset( $_POST['email_to_admin'] ) ? 1 : 0,
        'email_to_signer' => isset( $_POST['email_to_signer'] ) ? 1 : 0,
        'admin_email' => isset( $_POST['admin_email'] ) ? sanitize_email( wp_unslash( $_POST['admin_email'] ) ) : '',
        'email_from_name' => isset( $_POST['email_from_name'] ) ? sanitize_text_field( wp_unslash( $_POST['email_from_name'] ) ) : '',
        'email_from_address' => isset( $_POST['email_from_address'] ) ? sanitize_email( wp_unslash( $_POST['email_from_address'] ) ) : '',
        
        // Admin Email Template
        'admin_email_subject' => isset( $_POST['admin_email_subject'] ) ? sanitize_text_field( wp_unslash( $_POST['admin_email_subject'] ) ) : '',
        'admin_email_body' => isset( $_POST['admin_email_body'] ) ? wp_kses_post( wp_unslash( $_POST['admin_email_body'] ) ) : '',
        
        // Signer Email Template
        'signer_email_subject' => isset( $_POST['signer_email_subject'] ) ? sanitize_text_field( wp_unslash( $_POST['signer_email_subject'] ) ) : '',
        'signer_email_body' => isset( $_POST['signer_email_body'] ) ? wp_kses_post( wp_unslash( $_POST['signer_email_body'] ) ) : '',
        
        // Audit Trail
        'audit_trail_enabled' => isset( $_POST['audit_trail_enabled'] ) ? 1 : 0,
        'audit_trail_in_pdf' => isset( $_POST['audit_trail_in_pdf'] ) ? 1 : 0,
        
        // Branding
        'company_name' => isset( $_POST['company_name'] ) ? sanitize_text_field( wp_unslash( $_POST['company_name'] ) ) : '',
        'show_powered_by' => isset( $_POST['show_powered_by'] ) ? 1 : 0,
        
        // Success Screen Settings
        'success_title' => isset( $_POST['success_title'] ) ? sanitize_text_field( wp_unslash( $_POST['success_title'] ) ) : '',
        'success_message' => isset( $_POST['success_message'] ) ? wp_kses_post( wp_unslash( $_POST['success_message'] ) ) : '',
        'success_additional_info' => isset( $_POST['success_additional_info'] ) ? wp_kses_post( wp_unslash( $_POST['success_additional_info'] ) ) : '',
        'success_redirect_url' => isset( $_POST['success_redirect_url'] ) ? esc_url_raw( wp_unslash( $_POST['success_redirect_url'] ) ) : '',
        'success_redirect_delay' => isset( $_POST['success_redirect_delay'] ) ? intval( wp_unslash( $_POST['success_redirect_delay'] ) ) : 5,
        'allow_signer_download' => isset( $_POST['allow_signer_download'] ) ? 1 : 0,
        
        // Access Control
        'require_email_first' => isset( $_POST['require_email_first'] ) ? 1 : 0,
        
        // CSV Export Settings
        'csv_include_meta_columns' => isset( $_POST['csv_include_meta_columns'] ) ? 1 : 0,
    );
    
    update_option( 'swpdf_settings', $settings );
    $saved = true;
}

// Get current settings
$settings = get_option( 'swpdf_settings', array() );
$defaults = array(
    'email_enabled' => 1,
    'email_to_admin' => 1,
    'email_to_signer' => 1,
    'admin_email' => get_option( 'admin_email' ),
    'email_from_name' => get_bloginfo( 'name' ),
    'email_from_address' => get_option( 'admin_email' ),
    'admin_email_subject' => 'New Signed Document: {customer_name}',
    'admin_email_body' => "A new document has been signed.\n\nCustomer: {customer_name}\nEmail: {customer_email}\nPhone: {customer_phone}\nDocument Type: {agreement_type}\nSigned: {signed_date}\n\nThe signed PDF is attached.",
    'signer_email_subject' => 'Your Signed Document - {company_name}',
    'signer_email_body' => "Dear {customer_name},\n\nThank you for signing the document. Please find your signed copy attached for your records.\n\nDocument Type: {agreement_type}\nSigned: {signed_date}\n\nBest regards,\n{company_name}",
    'audit_trail_enabled' => 1,
    'audit_trail_in_pdf' => 1,
    'company_name' => get_bloginfo( 'name' ),
    'show_powered_by' => 0,
    'success_title' => 'Thank You!',
    'success_message' => 'Your document has been signed successfully. You will receive a confirmation email shortly.',
    'success_additional_info' => '',
    'success_redirect_url' => '',
    'success_redirect_delay' => 5,
    'allow_signer_download' => 1,
    'require_email_first' => 0,
    'csv_include_meta_columns' => 0, // Default OFF - exports single meta_json column
);
$settings = wp_parse_args( $settings, $defaults );
?>

<!-- Styles enqueued via wp_enqueue_style('swpdf-settings-css') in admin_enqueue_scripts -->

<div class="psf-settings-wrap">
    <h1>Settings</h1>
    
    <?php if ( $saved ) : ?>
    <div class="psf-notice psf-notice-success">
        <span class="dashicons dashicons-yes-alt"></span>
        <span>Settings saved successfully.</span>
    </div>
    <?php endif; ?>
    
    <form method="post" action="" id="psf-settings-form">
        <?php wp_nonce_field( 'swpdf_save_settings', 'swpdf_settings_nonce' ); ?>
        
        <!-- SECTION 1: Email & Notifications -->
        <div class="psf-section">
            <div class="psf-section-header">
                <h2>Email Notifications</h2>
                <p>Configure how and when email notifications are sent after documents are signed.</p>
            </div>
            
            <div class="psf-toggle-row">
                <label>
                    <input type="checkbox" name="email_enabled" value="1" <?php checked( $settings['email_enabled'], 1 ); ?> id="email_enabled">
                    <span>Enable email notifications</span>
                </label>
                <span class="psf-toggle-desc">Send emails when documents are signed</span>
            </div>
            
            <div class="psf-collapsible <?php echo esc_attr( $settings['email_enabled'] ? 'is-open' : '' ); ?>" id="email-settings-panel">
                <div class="psf-section-body">
                    <div class="psf-field-row">
                        <div class="psf-field-label">Send to</div>
                        <div class="psf-field-input">
                            <div class="psf-checkbox-group">
                                <label>
                                    <input type="checkbox" name="email_to_admin" value="1" <?php checked( $settings['email_to_admin'], 1 ); ?>>
                                    Admin (notification with PDF attached)
                                </label>
                                <label>
                                    <input type="checkbox" name="email_to_signer" value="1" <?php checked( $settings['email_to_signer'], 1 ); ?>>
                                    Signer (confirmation with PDF copy)
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="psf-field-row">
                        <div class="psf-field-label">Admin email</div>
                        <div class="psf-field-input">
                            <input type="email" name="admin_email" value="<?php echo esc_attr( $settings['admin_email'] ); ?>">
                            <p class="description">Where admin notifications are delivered</p>
                        </div>
                    </div>
                    
                    <div class="psf-field-row">
                        <div class="psf-field-label">From name</div>
                        <div class="psf-field-input">
                            <input type="text" name="email_from_name" value="<?php echo esc_attr( $settings['email_from_name'] ); ?>">
                        </div>
                    </div>
                    
                    <div class="psf-field-row">
                        <div class="psf-field-label">From email</div>
                        <div class="psf-field-input">
                            <input type="email" name="email_from_address" value="<?php echo esc_attr( $settings['email_from_address'] ); ?>">
                            <p class="description">Sender address for outgoing emails</p>
                        </div>
                    </div>
                </div>
                
                <!-- Admin Email Template (Collapsible) -->
                <button type="button" class="psf-collapsible-trigger" data-target="admin-template">
                    <span>Admin Email Template</span>
                    <span class="dashicons dashicons-arrow-down-alt2"></span>
                </button>
                <div class="psf-collapsible" id="admin-template">
                    <div class="psf-section-body">
                        <div class="psf-field-row">
                            <div class="psf-field-label">Subject</div>
                            <div class="psf-field-input">
                                <input type="text" name="admin_email_subject" value="<?php echo esc_attr( $settings['admin_email_subject'] ); ?>">
                            </div>
                        </div>
                        <div class="psf-field-row">
                            <div class="psf-field-label">Body</div>
                            <div class="psf-field-input">
                                <textarea name="admin_email_body" rows="5"><?php echo esc_textarea( $settings['admin_email_body'] ); ?></textarea>
                                <p class="description">Available variables:</p>
                                <div class="psf-variables-list">
                                    <code>{customer_name}</code>
                                    <code>{customer_email}</code>
                                    <code>{customer_phone}</code>
                                    <code>{agreement_type}</code>
                                    <code>{signed_date}</code>
                                    <code>{company_name}</code>
                                    <code>{signer_ip}</code>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Signer Email Template (Collapsible) -->
                <button type="button" class="psf-collapsible-trigger" data-target="signer-template">
                    <span>Signer Email Template</span>
                    <span class="dashicons dashicons-arrow-down-alt2"></span>
                </button>
                <div class="psf-collapsible" id="signer-template">
                    <div class="psf-section-body">
                        <div class="psf-field-row">
                            <div class="psf-field-label">Subject</div>
                            <div class="psf-field-input">
                                <input type="text" name="signer_email_subject" value="<?php echo esc_attr( $settings['signer_email_subject'] ); ?>">
                            </div>
                        </div>
                        <div class="psf-field-row">
                            <div class="psf-field-label">Body</div>
                            <div class="psf-field-input">
                                <textarea name="signer_email_body" rows="5"><?php echo esc_textarea( $settings['signer_email_body'] ); ?></textarea>
                                <p class="description">Available variables:</p>
                                <div class="psf-variables-list">
                                    <code>{customer_name}</code>
                                    <code>{customer_email}</code>
                                    <code>{agreement_type}</code>
                                    <code>{signed_date}</code>
                                    <code>{company_name}</code>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- SECTION 2: Signing & Security -->
        <div class="psf-section">
            <div class="psf-section-header">
                <h2>Signing & Security</h2>
                <p>Control access to documents and configure audit trail settings for compliance.</p>
            </div>
            
            <div class="psf-section-body">
                <div class="psf-field-row">
                    <div class="psf-field-label">Email gate</div>
                    <div class="psf-field-input">
                        <div class="psf-checkbox-group">
                            <label>
                                <input type="checkbox" name="require_email_first" value="1" <?php checked( $settings['require_email_first'], 1 ); ?>>
                                Require email before signing
                            </label>
                        </div>
                        <p class="description">Signer must enter their email address before the document loads</p>
                    </div>
                </div>
                
                <div class="psf-field-row">
                    <div class="psf-field-label">Download access</div>
                    <div class="psf-field-input">
                        <div class="psf-checkbox-group">
                            <label>
                                <input type="checkbox" name="allow_signer_download" value="1" <?php checked( $settings['allow_signer_download'], 1 ); ?>>
                                Allow signer to download signed document
                            </label>
                        </div>
                        <p class="description">Show download button on the success screen after signing</p>
                    </div>
                </div>
                
                <div class="psf-field-row">
                    <div class="psf-field-label">Audit trail</div>
                    <div class="psf-field-input">
                        <div class="psf-checkbox-group">
                            <label>
                                <input type="checkbox" name="audit_trail_enabled" value="1" <?php checked( $settings['audit_trail_enabled'], 1 ); ?>>
                                Track IP address, timestamp, and document hash
                            </label>
                        </div>
                        <p class="description">Records signer identity verification data. Document hash ensures integrity and detects tampering.</p>
                    </div>
                </div>
                
                <div class="psf-field-row">
                    <div class="psf-field-label">Audit certificate</div>
                    <div class="psf-field-input">
                        <div class="psf-checkbox-group">
                            <label>
                                <input type="checkbox" name="audit_trail_in_pdf" value="1" <?php checked( $settings['audit_trail_in_pdf'], 1 ); ?>>
                                Add audit certificate page to signed PDFs
                            </label>
                        </div>
                        <p class="description">Appends a verification page with signer details and document hash</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- SECTION: Data & Export -->
        <div class="psf-section">
            <div class="psf-section-header">
                <h2>Data & Export</h2>
                <p>Configure how agreement data is exported and displayed.</p>
            </div>
            
            <div class="psf-section-body">
                <div class="psf-field-row">
                    <div class="psf-field-label">CSV metadata columns</div>
                    <div class="psf-field-input">
                        <div class="psf-checkbox-group">
                            <label>
                                <input type="checkbox" name="csv_include_meta_columns" value="1" <?php checked( $settings['csv_include_meta_columns'], 1 ); ?>>
                                Expand metadata into separate columns
                            </label>
                        </div>
                        <p class="description">
                            <strong>OFF (default):</strong> Exports a single <code>meta_json</code> column with all custom metadata as JSON.<br>
                            <strong>ON:</strong> Creates individual <code>meta_*</code> columns for each metadata field (max 50 columns).
                        </p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- SECTION 3: Success & Redirect -->
        <div class="psf-section">
            <div class="psf-section-header">
                <h2>Success Screen</h2>
                <p>Customize what signers see after completing a document.</p>
            </div>
            
            <div class="psf-section-body">
                <div class="psf-field-row">
                    <div class="psf-field-label">Title</div>
                    <div class="psf-field-input">
                        <input type="text" name="success_title" value="<?php echo esc_attr( $settings['success_title'] ); ?>">
                    </div>
                </div>
                
                <div class="psf-field-row">
                    <div class="psf-field-label">Message</div>
                    <div class="psf-field-input">
                        <textarea name="success_message" rows="3"><?php echo esc_textarea( $settings['success_message'] ); ?></textarea>
                    </div>
                </div>
                
                <div class="psf-field-row">
                    <div class="psf-field-label">Additional Info</div>
                    <div class="psf-field-input">
                        <textarea name="success_additional_info" rows="4"><?php echo esc_textarea( $settings['success_additional_info'] ); ?></textarea>
                        <p class="description">Optional. HTML allowed. This appears in a highlighted box below the main message. Leave blank to hide.</p>
                    </div>
                </div>
                
                <div class="psf-field-row">
                    <div class="psf-field-label">Redirect URL</div>
                    <div class="psf-field-input">
                        <input type="url" name="success_redirect_url" value="<?php echo esc_attr( $settings['success_redirect_url'] ); ?>" placeholder="https://example.com/thank-you">
                        <p class="description">Leave blank to show success screen without redirect</p>
                    </div>
                </div>
                
                <div class="psf-field-row">
                    <div class="psf-field-label">Redirect delay</div>
                    <div class="psf-field-input">
                        <div class="psf-inline-fields">
                            <input type="number" name="success_redirect_delay" value="<?php echo esc_attr( $settings['success_redirect_delay'] ); ?>" min="0" max="60">
                            <span>seconds</span>
                        </div>
                        <p class="description">Time before automatic redirect. Use 0 for immediate redirect.</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- SECTION 4: Branding -->
        <div class="psf-section">
            <div class="psf-section-header">
                <h2>Branding</h2>
                <p>Personalize emails and audit certificates with your company details.</p>
            </div>
            
            <div class="psf-section-body">
                <div class="psf-field-row">
                    <div class="psf-field-label">Company name</div>
                    <div class="psf-field-input">
                        <input type="text" name="company_name" value="<?php echo esc_attr( $settings['company_name'] ); ?>">
                        <p class="description">Appears in emails and on the audit certificate page</p>
                    </div>
                </div>
                
                <?php
                // Only show this setting if user is on Free version
                $is_premium = function_exists('swpdf_is_premium_active') && swpdf_is_premium_active();
                if ( ! $is_premium ) :
                ?>
                <div class="psf-field-row">
                    <div class="psf-field-label">Powered by branding</div>
                    <div class="psf-field-input">
                        <label style="display: flex; align-items: center; gap: 8px;">
                            <input type="checkbox" name="show_powered_by" value="1" <?php checked( $settings['show_powered_by'], 1 ); ?>>
                            <span>Show "Powered by PDF Sign & Fill" on review screen (Free version only)</span>
                        </label>
                        <p class="description">A subtle branding link appears below the sign button. Premium users never see this.</p>
                    </div>
                </div>
                <?php endif; ?>

            </div>
        </div>
        
        <!-- Save Bar -->
        <div class="psf-save-bar">
            <span style="color: #646970; font-size: 13px;">Changes are saved when you click the button.</span>
            <button type="submit" name="swpdf_save_settings" class="button button-primary">Save Settings</button>
        </div>
    </form>
</div>
<!-- Scripts enqueued via wp_enqueue_script('swpdf-settings-js') in admin_enqueue_scripts -->
