<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/*
Plugin Name: PDF View Link for Formidable Forms
Description: Adds a basic "Download PDF" button to Formidable Forms entry view. Upgrade for more features!
Version: 1.0
Author: WDF Solutions PTY LTD
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: view-link-pdf-for-formidable-forms
Domain Path: /languages
*/

// Only allow if Formidable Forms and PDF Add-On are active
function frm_pdf_view_requirements_met() {
    return class_exists('FrmProFormsController') && (class_exists('FrmPdfsAppController') || function_exists('generate_entry_pdf'));
}

add_action('admin_notices', function() {
    if (!frm_pdf_view_requirements_met() && current_user_can('manage_options')) {
        echo '<div class="notice notice-error"><p><strong>PDF View Link for Formidable Forms:</strong> Formidable Forms Pro and the Forms to PDF Add-on must be installed and activated for this plugin to work.</p></div>';
    }
});

// Settings page (no license, no advanced options)
add_action('admin_menu', function() {
    add_submenu_page(
        'formidable',
        'PDF View Settings',
        'PDF View Settings',
        'manage_options',
        'frm-pdf-view-settings',
        'frm_pdf_view_settings_page',
        99
    );
}, 99);

// Register settings for the free version
add_action('admin_init', function() {
    register_setting('frm_pdf_view_free_settings', 'frm_pdf_view_free_template_id', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
        'default' => 12345,
    ));
});

/**
 * Upload the plugin logo to the media library during plugin activation
 */
function frm_pdf_view_upload_logo_to_media_library() {
    // Check if the logo is already uploaded by checking for the option
    $attachment_id = get_option('frm_pdf_view_logo_attachment_id', 0);
    if ($attachment_id && get_post($attachment_id)) {
        return $attachment_id; // Logo already uploaded
    }
    
    // The logo file path
    $logo_path = 'img/banner-icon-256x256.png';
    $logo_file = plugin_dir_path(__FILE__) . $logo_path;
    
    // Check if the file exists
    if (!file_exists($logo_file)) {
        return 0; // File doesn't exist
    }
    
    // WordPress includes needed for media handling
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    
    // Prepare file data for upload
    $file_array = array(
        'name'     => basename($logo_file),
        'tmp_name' => $logo_file,
        'error'    => 0,
        'size'     => filesize($logo_file),
    );
    
    // Upload the file to the media library
    $attachment_id = media_handle_sideload(
        $file_array, 
        0, 
        'WDF Solutions Logo - PDF View Link for Formidable Forms'
    );
    
    // Save the attachment ID for future use
    if (!is_wp_error($attachment_id)) {
        update_option('frm_pdf_view_logo_attachment_id', $attachment_id);
        return $attachment_id;
    }
    
    return 0; // Upload failed
}

/**
 * Register activation hook to upload the logo
 */
register_activation_hook(__FILE__, 'frm_pdf_view_upload_logo_to_media_library');

/**
 * Display the plugin logo using WordPress functions
 */
function frm_pdf_view_display_logo() {
    // Get the attachment ID from the option
    $attachment_id = get_option('frm_pdf_view_logo_attachment_id', 0);
    
    // If the attachment doesn't exist, try to upload it
    if (!$attachment_id || !get_post($attachment_id)) {
        $attachment_id = frm_pdf_view_upload_logo_to_media_library();
    }
    
    // If we have a valid attachment ID, display the image
    if ($attachment_id) {
        echo wp_get_attachment_image($attachment_id, 'full', false, array(
            'class' => 'wdf-logo',
            'alt'   => esc_attr__('WDF Solutions Logo', 'view-link-pdf-for-formidable-forms'),
        ));
    } else {
        // Fallback if no image exists or upload failed
        // Use a direct URL as last resort
        $logo_path = 'img/banner-icon-256x256.png';
        $logo_url = plugins_url($logo_path, __FILE__);
        
        if (file_exists(plugin_dir_path(__FILE__) . $logo_path)) {
            $img_html = '<img src="' . esc_url($logo_url) . '" alt="' . 
                esc_attr__('WDF Solutions Logo', 'view-link-pdf-for-formidable-forms') . 
                '" class="wdf-logo" />';
            
            echo wp_kses($img_html, array(
                'img' => array(
                    'src' => array(),
                    'alt' => array(),
                    'class' => array(),
                )
            ));
        } else {
            echo '<h2>' . esc_html__('WDF Solutions', 'view-link-pdf-for-formidable-forms') . '</h2>';
        }
    }
}

// Register and enqueue styles for the admin page
function frm_pdf_view_enqueue_admin_styles() {
    $screen = get_current_screen();
    if ($screen && $screen->id === 'formidable_page_frm-pdf-view-settings') {
        wp_register_style('frm-pdf-view-admin', false, array(), '1.0.0');
        wp_enqueue_style('frm-pdf-view-admin');
        
        $custom_css = '
        body.wp-admin, .wrap {
            background: #f7f8fa !important;
        }
        .wdf-logo-container {
            text-align: center;
            margin-bottom: 20px;
        }
        .wdf-logo-container img {
            max-width: 220px;
            height: auto;
            border-radius: 10px;
            box-shadow: 0 2px 12px rgba(80,80,120,0.08);
            background: #fff;
            padding: 8px 16px;
        }
        .wdf-card {
            background: #fff;
            border-radius: 18px;
            box-shadow: 0 2px 16px rgba(80,80,120,0.07);
            max-width: 900px;
            margin: 0 auto 32px auto;
            padding: 44px 48px 40px 48px;
            border: 1px solid #f0f1f3;
        }
        .wrap .form-table th {
            width: 220px;
            font-weight: 600;
            color: #222;
            background: none;
            border: none;
            padding-top: 18px;
            padding-bottom: 10px;
        }
        .wrap .form-table input[type="number"],
        .wrap .form-table input[type="text"],
        .wrap .form-table select {
            max-width: 320px;
            border: none;
            background: #f7f8fa;
            border-radius: 8px;
            box-shadow: none;
            padding: 10px 14px;
            font-size: 1em;
            margin-bottom: 6px;
        }
        .wrap .form-table input[type="number"]:focus,
        .wrap .form-table input[type="text"]:focus,
        .wrap .form-table select:focus {
            outline: 2px solid #7b61ff;
            background: #fff;
        }
        .wrap h1 {
            text-align: center;
            font-weight: 700;
            letter-spacing: 1px;
            margin-bottom: 10px;
        }
        .wrap .notice-info {
            border-left: 4px solid #7b61ff;
            background: linear-gradient(90deg, #7b61ff11 0%, #61aaff11 100%);
        }
        .wdf-section-heading {
            margin-top: 36px;
            font-size: 1.2em;
            font-weight: 600;
            letter-spacing: 0.5px;
            border-bottom: 1px solid #ececec;
            padding-bottom: 8px;
            margin-bottom: 18px;
        }
        .wdf-card .button-primary, .wdf-card .button {
            background: linear-gradient(90deg, #7b61ff 0%, #61aaff 100%);
            border: none;
            color: #fff;
            font-weight: 600;
            border-radius: 999px;
            padding: 12px 38px;
            margin-top: 24px;
            font-size: 1.08em;
            box-shadow: 0 2px 8px rgba(80,80,120,0.08);
            transition: background 0.2s;
        }
        .wdf-card .button-primary:hover, .wdf-card .button:hover {
            background: linear-gradient(90deg, #61aaff 0%, #7b61ff 100%);
            color: #fff;
        }
        @media (max-width: 900px) {
            .wdf-card {
                padding: 18px 8px 18px 8px;
            }
        }
        ';
        
        wp_add_inline_style('frm-pdf-view-admin', $custom_css);
    }
}
add_action('admin_enqueue_scripts', 'frm_pdf_view_enqueue_admin_styles');

// Update settings page to include PDF template ID field
function frm_pdf_view_settings_page() {
    ?>
    <div class="wrap">
        <div class="wdf-logo-container">
        <?php
        // Display the logo
        frm_pdf_view_display_logo();
        ?>
        </div>
        <h1>PDF View Link for Formidable Forms</h1>
        <div class="wdf-card">
        <div class="notice notice-info" style="margin: 20px 0 20px 0;">
            <p>
                🚀 <strong>Upgrade to Pro for more features!</strong><br>
                <ul style="margin-left: 20px;">
                    <li>Multiple PDF templates</li>
                    <li>Form-specific template selection</li>
                    <li>Custom button text</li>
                    <li>Logging and debugging</li>
                    <li>Priority support</li>
                </ul>
                <a href="https://shop.wdfsolutions.com.au/product/pdf-formatted-view-pro/" target="_blank" class="button button-primary" style="margin-top:10px;">Upgrade to Pro</a>
            </p>
        </div>
        <form action="options.php" method="post">
            <?php
            settings_fields('frm_pdf_view_free_settings');
            ?>
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="frm_pdf_view_free_template_id">PDF Template ID</label>
                    </th>
                    <td>
                        <input type="number" id="frm_pdf_view_free_template_id" name="frm_pdf_view_free_template_id" value="<?php echo esc_attr(get_option('frm_pdf_view_free_template_id', '12345')); ?>" class="regular-text">
                        <p class="description">Enter the ID of your Formidable PDF template.</p>
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
        <p style="margin-top:24px;">This free version allows a single PDF template and a fixed button label. Upgrade for more!</p>
        </div>
    </div>
    <?php
}

// Use the saved template ID in the PDF button generation
add_filter('frm_entry_actions_dropdown', function($actions, $atts) {
    if (!frm_pdf_view_requirements_met()) {
        return $actions;
    }
    if (!isset($atts['entry'])) {
        return $actions;
    }
    $entry = $atts['entry'];
    $pdf_template_id = get_option('frm_pdf_view_free_template_id', '12345');
    $entry_id = absint($entry->id);
    $shortcode = '[frm-pdf id="' . $entry_id . '" view="' . $pdf_template_id . '" mode="download"]';
    $html_link = do_shortcode($shortcode);
    $dom = new DOMDocument();
    @$dom->loadHTML($html_link);
    $links = $dom->getElementsByTagName('a');
    $pdf_url = '';
    if ($links->length > 0) {
        $pdf_url = $links->item(0)->getAttribute('href');
    }
    if (empty($pdf_url)) {
        return $actions;
    }
    $actions['frm_view_pdf'] = array(
        'url' => esc_url($pdf_url),
        'label' => __('Download View PDF', 'view-link-pdf-for-formidable-forms'),
        'icon'  => 'frm_icon_font frm_download_icon',
        'class' => 'frm_download_pdf_button',
        'data' => array(
            'frmtarget' => '_blank',
            'frmrel' => 'noopener noreferrer'
        )
    );
    return $actions;
}, 10, 2);
