<?php
/**
 * Plugin Name: PDF Smart Viewer for Elementor
 * Plugin URI: https://deknows.com/pdf-smart-viewer-elementor
 * Description: A powerful and customizable PDF viewer widget for Elementor with advanced features like zoom controls, fullscreen mode, download options, and responsive design.
 * Version: 1.0.4
 * Requires at least: 5.0
 * Tested up to: 6.8
 * Requires PHP: 7.4
 * Requires Plugins: elementor
 * Author: Deknows
 * Author URI: https://deknows.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: pdf-smart-viewer-for-elementor
 * Domain Path: /languages
 * 
 * @package PDFSmartViewerElementor
 * @version 1.0.1
 * @author Hamad - Lead Development and Operations @Deknows Inc
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('PDFSMVIF_VERSION', '1.0.4');
define('PDFSMVIF_PLUGIN_FILE', __FILE__);
define('PDFSMVIF_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('PDFSMVIF_PLUGIN_URL', plugin_dir_url(__FILE__));
define('PDFSMVIF_PLUGIN_BASENAME', plugin_basename(__FILE__));

/**
 * Main plugin class
 */
class PDFSMVIF_PDF_Smart_Viewer {

    /**
     * Plugin instance
     */
    private static $instance = null;

    /**
     * Get plugin instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct() {
        add_action('plugins_loaded', array($this, 'init'));
    }

    /**
     * Initialize plugin
     */
    public function init() {
        // Check if Elementor is installed and activated
        if (!did_action('elementor/loaded')) {
            add_action('admin_notices', array($this, 'admin_notice_missing_elementor'));
            return;
        }

        // Register widget
        add_action('elementor/widgets/register', array($this, 'register_widgets'));

        // Register scripts and styles
        add_action('elementor/frontend/after_register_scripts', array($this, 'register_scripts'));
        add_action('elementor/frontend/after_enqueue_scripts', array($this, 'enqueue_scripts'));

        // Add admin menu
        add_action('admin_menu', array($this, 'add_admin_menu'));

        // Register admin scripts and styles
        add_action('admin_enqueue_scripts', array($this, 'admin_scripts'));

        // Register activation/deactivation hooks
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));

        // Add AJAX handlers for PDF proxy
        add_action('wp_ajax_pdfsmvif_proxy_pdf', array($this, 'proxy_pdf'));
        add_action('wp_ajax_nopriv_pdfsmvif_proxy_pdf', array($this, 'proxy_pdf'));
    }

    /**
     * Admin notice for missing Elementor
     */
    public function admin_notice_missing_elementor() {
        // Only unset 'activate' if a valid nonce is present
        if (isset($_GET['activate']) && isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'activate-plugin_' . PDFSMVIF_PLUGIN_BASENAME)) {
            unset($_GET['activate']);
        }

        $message = sprintf(
            // translators: %1$s is the plugin name, %2$s is the required plugin name.
            esc_html__('"%1$s" requires "%2$s" to be installed and activated.', 'pdf-smart-viewer-for-elementor'),
            '<strong>' . esc_html__('PDF Smart Viewer for Elementor', 'pdf-smart-viewer-for-elementor') . '</strong>',
            '<strong>' . esc_html__('Elementor', 'pdf-smart-viewer-for-elementor') . '</strong>'
        );

        printf('<div class="notice notice-warning is-dismissible"><p>%1$s</p></div>', wp_kses_post($message));
    }

    /**
     * Register widgets
     */
    public function register_widgets($widgets_manager) {
        require_once(PDFSMVIF_PLUGIN_DIR . 'widgets/pdf-smart-viewer-widget.php');
        $widgets_manager->register(new \PDFSMVIF_PDF_Smart_Viewer_Widget());
    }

    /**
     * Register scripts and styles
     */
    public function register_scripts() {
        // PDF.js library - using local files instead of CDN
        wp_register_script(
            'pdfjs-lib',
            PDFSMVIF_PLUGIN_URL . 'assets/js/pdf.min.js',
            array(),
            '3.11.174',
            true
        );

        // Main plugin script
        wp_register_script(
            'pdf-smart-viewer-for-elementor',
            PDFSMVIF_PLUGIN_URL . 'assets/js/pdf-smart-viewer.js',
            array('pdfjs-lib', 'jquery'),
            PDFSMVIF_VERSION,
            true
        );

        // Localize script for AJAX
        wp_localize_script('pdf-smart-viewer-for-elementor', 'pdfsmvif_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('pdfsmvif_nonce'),
            'proxy_nonce' => wp_create_nonce('pdfsmvif_proxy_nonce'),
            'plugin_url' => PDFSMVIF_PLUGIN_URL,
        ));

        // Register styles
        wp_register_style(
            'pdf-smart-viewer-for-elementor',
            PDFSMVIF_PLUGIN_URL . 'assets/css/pdf-smart-viewer.css',
            array(),
            PDFSMVIF_VERSION
        );
    }

    /**
     * Enqueue scripts and styles
     */
    public function enqueue_scripts() {
        wp_enqueue_script('pdf-smart-viewer-for-elementor');
        wp_enqueue_style('pdf-smart-viewer-for-elementor');
    }

    /**
     * Admin scripts and styles
     */
    public function admin_scripts($hook) {
        // Only load on our plugin page
        if ($hook !== 'settings_page_elementor-pdf-smart-viewer') {
            return;
        }

        // Enqueue admin CSS
        wp_enqueue_style(
            'pdf-smart-viewer-admin',
            PDFSMVIF_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            PDFSMVIF_VERSION
        );

        // Add inline CSS for admin page
        $admin_css = '
        .pdfsmvif-admin-container {
            display: flex;
            gap: 20px;
            margin-top: 20px;
        }

        .pdfsmvif-admin-main {
            flex: 1;
            background: #fff;
            padding: 20px;
            border: 1px solid #ccd0d4;
            border-radius: 4px;
        }

        .pdfsmvif-admin-sidebar {
            width: 300px;
        }

        .pdfsmvif-admin-box {
            background: #fff;
            border: 1px solid #ccd0d4;
            border-radius: 4px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .pdfsmvif-admin-box h3 {
            margin-top: 0;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }

        .pdfsmvif-admin-box ul {
            margin: 0;
            padding-left: 20px;
        }

        .pdfsmvif-admin-box li {
            margin-bottom: 5px;
        }

        @media (max-width: 768px) {
            .pdfsmvif-admin-container {
                flex-direction: column;
            }
            
            .pdfsmvif-admin-sidebar {
                width: 100%;
            }
        }';

        wp_add_inline_style('pdf-smart-viewer-admin', $admin_css);
    }

    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_options_page(
            __('PDF Smart Viewer Settings', 'pdf-smart-viewer-for-elementor'),
            __('PDF Smart Viewer', 'pdf-smart-viewer-for-elementor'),
            'manage_options',
            'elementor-pdf-smart-viewer',
            array($this, 'admin_page')
        );
    }

    /**
     * Admin page callback
     */
    public function admin_page() {
        require_once PDFSMVIF_PLUGIN_DIR . 'admin/admin-page.php';
    }

    /**
     * Plugin activation
     */
    public function activate() {
        // Add default options
        add_option('pdfsmvif_default_zoom', '1');
        add_option('pdfsmvif_enable_download', '1');
        add_option('pdfsmvif_enable_fullscreen', '1');
        add_option('pdfsmvif_enable_print', '1');
        add_option('pdfsmvif_enable_zoom_controls', '1');
        add_option('pdfsmvif_enable_page_info', '1');
        add_option('pdfsmvif_default_height', '100%');
        add_option('pdfsmvif_enable_remote_pdfs', '1'); // Enable remote PDF support by default
        
        // Flush rewrite rules
        flush_rewrite_rules();
    }

    /**
     * Plugin deactivation
     */
    public function deactivate() {
        // Flush rewrite rules
        flush_rewrite_rules();
    }

    /**
     * Proxy PDF to bypass CORS restrictions
     */
    public function proxy_pdf() {
        // Verify nonce for security
        if (!isset($_GET['nonce'])) {
            wp_die('No nonce provided');
        }
        
        $nonce = sanitize_text_field(wp_unslash($_GET['nonce']));
        if (!wp_verify_nonce($nonce, 'pdfsmvif_proxy_nonce')) {
            wp_die('Invalid nonce');
        }

        // Get PDF URL
        $pdf_url = isset($_GET['url']) ? sanitize_url(wp_unslash($_GET['url'])) : '';
        
        if (empty($pdf_url)) {
            wp_die('No PDF URL provided');
        }

        // Validate URL
        if (!filter_var($pdf_url, FILTER_VALIDATE_URL)) {
            wp_die('Invalid URL');
        }

        // Check if remote PDFs are allowed
        if (!$this->is_remote_pdf_allowed()) {
            wp_die('Remote PDF support is disabled');
        }

        // Fetch the PDF
        $response = wp_remote_get($pdf_url, array(
            'timeout' => 30,
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'sslverify' => false,
            'stream' => false, // Don't stream to avoid encoding issues
            'headers' => array(
                'Accept' => 'application/pdf,application/octet-stream,*/*',
                'Accept-Language' => 'en-US,en;q=0.9',
                'Cache-Control' => 'no-cache'
            )
        ));

        if (is_wp_error($response)) {
            wp_die('Failed to fetch PDF: ' . $response->get_error_message());
        }

        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code !== 200) {
            // Try with a different user agent as fallback
            $fallback_response = wp_remote_get($pdf_url, array(
                'timeout' => 30,
                'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'sslverify' => false,
                'stream' => false,
                'headers' => array(
                    'Accept' => '*/*',
                    'Accept-Language' => 'en-US,en;q=0.9'
                )
            ));
            
            if (is_wp_error($fallback_response)) {
                wp_die('Failed to fetch PDF with fallback: ' . $fallback_response->get_error_message());
            }
            
            $fallback_status = wp_remote_retrieve_response_code($fallback_response);
            if ($fallback_status !== 200) {
                wp_die('HTTP Error: ' . $status_code . ' (fallback also failed: ' . $fallback_status . ')');
            }
            
            $response = $fallback_response;
        }

        // Get content type and other headers
        $content_type = wp_remote_retrieve_header($response, 'content-type');
        $content_length = wp_remote_retrieve_header($response, 'content-length');
        $last_modified = wp_remote_retrieve_header($response, 'last-modified');
        
        // Get the body content
        $body = wp_remote_retrieve_body($response);
        if ($body === false) {
            wp_die('Failed to read PDF content');
        }

        // Ensure we have a PDF content type
        if (!$content_type || strpos($content_type, 'application/pdf') === false) {
            $content_type = 'application/pdf';
        }

        // Set headers
        header('Content-Type: application/pdf');
        header('Content-Length: ' . strlen($body));
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, HEAD');
        header('Access-Control-Allow-Headers: Content-Type, Range');
        header('Accept-Ranges: bytes');
        header('Cache-Control: public, max-age=3600');
        
        if ($last_modified && !empty($last_modified)) {
            header('Last-Modified: ' . $last_modified);
        }

        // Output the PDF content
        echo $body;
        exit;
    }

    /**
     * Check if remote PDFs are allowed
     */
    private function is_remote_pdf_allowed() {
        return get_option('pdfsmvif_enable_remote_pdfs', '1') === '1';
    }
}

// Initialize the plugin
PDFSMVIF_PDF_Smart_Viewer::get_instance();
