<?php

/**
 * Plugin Name: Unlock Addons for Elementor
 * Description: Unlock Addons for Elementor plugin offer 10+ Free widgets includes widgets and addons like Blog Post Grid, Megamenu, Post Carousel, Countdown, Testimonials.
 * Version: 2.2.4
 * Requires at least: 6.5
 * Requires PHP: 7.4
 * Requires Plugins: elementor
 * Author: WPRealizer
 * Author URI: https://wprealizer.com
 * Plugin URI: https://unlockaddons.com/unlock-addons-for-elementor/
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: unlock-addons-for-elementor
 *
 * Elementor tested up to: 3.35.7
 * Elementor Pro tested up to: 3.35.7
 *
 *
 * Unlock Addons for Elementor Addons is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * any later version.
 *
 * Unlock Addons for Elementor Addons is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Quantum Addons. If not, see https://www.gnu.org/licenses/gpl-3.0.html.
 */


if (! defined('ABSPATH')) exit; // Exit if accessed directly.

// Suppress Elementor pro-free-trial-popup warnings
add_action('plugins_loaded', function () {
    // Suppress undefined array key warnings from Elementor's pro-free-trial-popup module
    if (class_exists('\Elementor\Plugin')) {
        // This is a known Elementor issue that doesn't affect functionality
        // The warnings occur when Elementor tries to access module settings that may not exist
    }
}, 1);

// Clean up removed widgets from options
add_action('plugins_loaded', function () {
    // Only run this in admin to avoid performance impact on frontend
    if (is_admin()) {
        // Get current widget options
        $widgets = get_option('_unlockafe_addons_opstions', []);

        // Array of widgets to remove
        $widgets_to_remove = [
            'unlockafe-mega-menu',
            'unlockafe-parallax-background'
        ];

        // Filter out removed widgets
        $updated_widgets = [];
        foreach ($widgets as $widget) {
            if (!in_array($widget['id'], $widgets_to_remove)) {
                $updated_widgets[] = $widget;
            }
        }

        // Only update if there's a difference
        if (count($widgets) !== count($updated_widgets)) {
            update_option('_unlockafe_addons_opstions', $updated_widgets);
        }
    }
});

/**
 * Define constance
 */

define('UNLOCKAFE_VERSION', '1.0.0');
define('UNLOCKAFE_SLUG', 'unlock-addons-for-elementor');
define('UNLOCKAFE_ADDONS_BASE', plugin_basename(__FILE__));
define('UNLOCKAFE_ADDONS_URL', plugins_url('/', __FILE__));
define('UNLOCKAFE_ADDONS_DIR', dirname(__FILE__));
define('UNLOCKAFE_ADDONS_PATH', plugin_dir_path(__FILE__));
define('UNLOCKAFE_ASSETS', UNLOCKAFE_ADDONS_URL . 'assets/');
define('UNLOCKAFE_INCLUDE_PATH', UNLOCKAFE_ADDONS_DIR . '/includes/');
define('UNLOCKAFE_TEMPLATE_PATH', UNLOCKAFE_ADDONS_DIR . '/includes/Widgets/templates/');
define('UNLOCKAFE_WP_ASSETS_PATH', wp_upload_dir()['basedir'] . '/' . UNLOCKAFE_SLUG . '/');
define('UNLOCKAFE_WP_ASSETS_URI', wp_upload_dir()['baseurl'] . '/' . UNLOCKAFE_SLUG . '/');

/**
 * AutoLoad fiels
 */
require UNLOCKAFE_ADDONS_PATH . '/autoload.php';
require UNLOCKAFE_ADDONS_PATH . '/includes/Classes/Popup_Click_Tracker.php';

/**
 * Main UNLOCKAFE Class
 *
 * The init class that runs the Unlock Addons plugin.
 * Intended To make sure that the plugin's minimum requirements are met.
 *
 * @since 1.0.0
 */
final class UNLOCKAFE_Final
{

    /**
     *
     * $instance property for instance
     */
    private static $instance = null;

    /**
     * Plugin prefix
     *
     * @since 1.0.0
     * @var string The plugin version.
     */
    const PREFIX = 'unlockafe';



    /**
     * Minimum Elementor Version
     *
     * @since 1.0.0
     * @var string Minimum Elementor version required to run the plugin.
     */
    const MINIMUM_ELEMENTOR_VERSION = '3.5.0';

    /**
     * Constructor
     *
     * @since 1.0.0
     * @access public
     */
    public function __construct()
    {

        // Init Plugin
        add_action('plugins_loaded', array($this, 'plugins_loaded'));
    }

    /**
     *
     * @return self
     * @since  1.0.0
     */
    public static function getInstance()
    {
        if (! isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function plugins_loaded()
    {

        if (! did_action('elementor/loaded')) {
            add_action('admin_notices', [$this, 'unlockafe_elementor_load_notice']);
            return;
        }

        // load textdomain
        load_plugin_textdomain('unlock-addons-for-elementor', false, basename(dirname(__FILE__)) . '/languages');

        // run
        \Unlockafe_addons\Classes\Unlockafe_addons::getInstance();
    }

    /**
     * Check if elementor active and notice
     * 
     * @return void
     */
    public function unlockafe_elementor_load_notice()
    {
        $plugin = 'elementor/elementor.php';
        if ($this->is_elementor_activated()) {
            if (! current_user_can('activate_plugins')) {
                return;
            }
            $activation_url = wp_nonce_url('plugins.php?action = activate&amp;plugin = ' . $plugin . '&amp;plugin_status = all&amp;paged = 1&amp;s', 'activate-plugin_' . $plugin);
            $admin_notice   = '<p>' . esc_html__('Elementor is missing. You need to activate your installed Elementor to use Unlock Addons for Elementor.', 'unlock-addons-for-elementor') . '</p>';
            $admin_notice .= '<p>' . sprintf('<a href         = "%s" class          = "button-primary">%s</a>', $activation_url, esc_html__('Activate Elementor Now', 'unlock-addons-for-elementor')) . '</p>';
        } else {
            if (! current_user_can('install_plugins')) {
                return;
            }
            $install_url  = wp_nonce_url(self_admin_url('update.php?action=install-plugin&plugin=elementor'), 'install-plugin_elementor');
            $admin_notice = '<p>' . esc_html__('Elementor Required. You need to install & activate Elementor to use Unlock Addons for Elementor.', 'unlock-addons-for-elementor') . '</p>';
            $admin_notice .= '<p>' . sprintf('<a href="%s" class="button-primary">%s</a>', $install_url, esc_html__('Install Elementor Now', 'unlock-addons-for-elementor')) . '</p>';
        }
        echo '<div class="notice notice-error is-dismissible">' . wp_kses($admin_notice, true) . '</div>';
    }

    /**
     * Elementor activated or not
     */
    public function is_elementor_activated()
    {
        $file_path         = 'elementor/elementor.php';
        $installed_plugins = get_plugins();

        return isset($installed_plugins[$file_path]);
    }
}

// DEVELOPMENT MODE: Super Simple Form Processing for Email Capture
// This version skips nonce verification completely for development purposes
function unlockafe_process_email_form_ajax_handler()
{
    // Log the incoming data for debugging
    error_log('Email form submission received: ' . print_r($_REQUEST, true));

    // Get basic form data (checking both POST and GET for maximum compatibility)
    $name = isset($_REQUEST['name']) ? sanitize_text_field($_REQUEST['name']) : '';
    $email = isset($_REQUEST['email']) ? sanitize_email($_REQUEST['email']) : '';
    $form_id = isset($_REQUEST['form_id']) ? sanitize_text_field($_REQUEST['form_id']) : '';
    $page_url = isset($_REQUEST['page_url']) ? esc_url_raw($_REQUEST['page_url']) : '';
    $category_id = isset($_REQUEST['category_id']) ? intval($_REQUEST['category_id']) : null;

    // Basic validation
    if (empty($email)) {
        wp_send_json_error(array('message' => 'Email is required'));
        exit;
    }

    // Get DB info
    global $wpdb;
    $table_name = $wpdb->prefix . 'unlockafe_email_capture';

    // Ensure table structure exists (dbDelta also handles column upgrades)
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE `$table_name` (
        `id` bigint(20) NOT NULL AUTO_INCREMENT,
        `name` varchar(100) NOT NULL,
        `email` varchar(100) NOT NULL,
        `page_url` text NOT NULL,
        `submitted_at` datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        `status` varchar(20) DEFAULT 'subscribed',
        `ip_address` varchar(45) DEFAULT '',
        `user_agent` text,
        `form_id` varchar(50) DEFAULT '',
        `meta` longtext,
        `category_id` bigint(20) DEFAULT NULL,
        PRIMARY KEY (`id`)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);

    // Backfill column on legacy tables where dbDelta could not add it
    $has_category_column = $wpdb->get_var("SHOW COLUMNS FROM {$table_name} LIKE 'category_id'");
    if (!$has_category_column) {
        $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN `category_id` bigint(20) DEFAULT NULL");
    }

    // Get IP address
    $ip_address = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip_address = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip_address = $_SERVER['REMOTE_ADDR'];
    }

    // Get user agent
    $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';

    // Duplicate check: same email, page_url, and category_id
    $duplicate = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $table_name WHERE email = %s AND page_url = %s AND category_id = %d",
        $email,
        $page_url,
        $category_id
    ));
    if ($duplicate > 0) {
        wp_send_json_error(array('message' => 'This email is already added for this page and category.'));
        exit;
    }

    // Insert data into the database
    $result = $wpdb->insert(
        $table_name,
        array(
            'name' => $name,
            'email' => $email,
            'page_url' => $page_url,
            'form_id' => $form_id,
            'ip_address' => $ip_address,
            'user_agent' => $user_agent,
            'submitted_at' => current_time('mysql'),
            'status' => 'subscribed',
            'category_id' => $category_id
        ),
        array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d')
    );

    // Log the database insert result
    error_log('Database insert result: ' . ($result ? 'Success' : 'Failed') . ', Last error: ' . $wpdb->last_error);

    if ($result) {
        // Success response
        wp_send_json_success(array(
            'message' => 'Thank you for subscribing!',
            'data_saved' => true,
            'id' => $wpdb->insert_id
        ));
    } else {
        // Error response with useful debugging info
        wp_send_json_error(array(
            'message' => 'Failed to save your information. Please try again.',
            'db_error' => $wpdb->last_error
        ));
    }

    exit;
}

// Register AJAX handlers for email form submission
add_action('wp_ajax_unlockafe_process_email_form', 'unlockafe_process_email_form_ajax_handler');
add_action('wp_ajax_nopriv_unlockafe_process_email_form', 'unlockafe_process_email_form_ajax_handler');

// AJAX handler for retrieving email capture records for the admin panel
function unlockafe_get_email_records_handler()
{
    // Check if user has permissions to access admin data
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'You don\'t have permission to access this data'));
        exit;
    }

    // Verify nonce
    if (!isset($_REQUEST['nonce']) || !wp_verify_nonce($_REQUEST['nonce'], 'unlockafe_email_records_nonce')) {
        wp_send_json_error(array('message' => 'Security check failed'));
        exit;
    }

    global $wpdb;
    $table_name = $wpdb->prefix . 'unlockafe_email_capture';
    $cat_table = $wpdb->prefix . 'unlockafe_email_categories';

    // Check if table exists
    if ($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") != $table_name) {
        wp_send_json_success(array(
            'records' => array(),
            'message' => 'No records found - database table does not exist'
        ));
        exit;
    }

    // Get all records, ordered by most recent first
    $records = $wpdb->get_results(
        "SELECT ec.id, ec.name, ec.email, ec.page_url, ec.form_id, ec.submitted_at as created_at, ec.status, ec.ip_address, ec.category_id, cat.name as category_name
         FROM {$table_name} ec
         LEFT JOIN {$cat_table} cat ON ec.category_id = cat.id
         ORDER BY ec.submitted_at DESC",
        ARRAY_A
    );

    // Return the records
    wp_send_json_success(array(
        'records' => $records,
        'count' => count($records)
    ));

    exit;
}

// Register AJAX handlers
add_action('wp_ajax_unlockafe_process_email_form', 'unlockafe_process_email_form_ajax_handler');
add_action('wp_ajax_nopriv_unlockafe_process_email_form', 'unlockafe_process_email_form_ajax_handler');

// Register AJAX handler for email records (admin only)
add_action('wp_ajax_unlockafe_get_email_records', 'unlockafe_get_email_records_handler');

// Initialize the Email Records admin page
add_action('plugins_loaded', function () {
    if (is_admin()) {
        require_once __DIR__ . '/includes/Admin/EmailRecords.php';
        Unlockafe_addons\Admin\EmailRecords::get_instance();
        require_once __DIR__ . '/includes/Admin/Table_Reservation_List.php';
        Unlockafe_addons\Admin\Table_Reservation_List::get_instance();
    }
});

// --- CATEGORY AJAX HANDLERS ---
add_action('wp_ajax_unlockafe_get_categories', function () {
    check_ajax_referer('unlockafe_email_records_nonce', 'nonce');
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_categories';
    $categories = $wpdb->get_results("SELECT * FROM $table ORDER BY name ASC");
    wp_send_json_success(['categories' => $categories]);
});
add_action('wp_ajax_unlockafe_add_category', function () {
    check_ajax_referer('unlockafe_email_records_nonce', 'nonce');
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_categories';
    $name = sanitize_text_field($_POST['name']);
    $wpdb->insert($table, ['name' => $name]);
    wp_send_json_success(['id' => $wpdb->insert_id, 'name' => $name]);
});
add_action('wp_ajax_unlockafe_edit_category', function () {
    check_ajax_referer('unlockafe_email_records_nonce', 'nonce');
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_categories';
    $id = intval($_POST['id']);
    $name = sanitize_text_field($_POST['name']);
    $wpdb->update($table, ['name' => $name], ['id' => $id]);
    wp_send_json_success();
});
add_action('wp_ajax_unlockafe_delete_category', function () {
    check_ajax_referer('unlockafe_email_records_nonce', 'nonce');
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_categories';
    $id = intval($_POST['id']);
    $wpdb->delete($table, ['id' => $id]);
    wp_send_json_success();
});
add_action('wp_ajax_unlockafe_bulk_assign_category', function () {
    check_ajax_referer('unlockafe_email_records_nonce', 'nonce');
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_capture';
    $ids = array_map('intval', explode(',', $_POST['ids'] ?? ''));
    $category_id = intval($_POST['category_id']);
    if ($ids && $category_id) {
        $wpdb->query("UPDATE $table SET category_id = $category_id WHERE id IN (" . implode(',', $ids) . ")");
        wp_send_json_success();
    }
    wp_send_json_error(['message' => 'Invalid input']);
});

add_action('wp_ajax_unlockafe_delete_email_record', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
        exit;
    }
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'unlockafe_email_records_nonce')) {
        wp_send_json_error(['message' => 'Security check failed']);
        exit;
    }
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_capture';
    $id = intval($_POST['id'] ?? 0);
    if ($id) {
        $deleted = $wpdb->delete($table, ['id' => $id]);
        if ($deleted) {
            wp_send_json_success();
        } else {
            wp_send_json_error(['message' => 'Delete failed']);
        }
    } else {
        wp_send_json_error(['message' => 'Invalid ID']);
    }
    exit;
});

add_action('wp_ajax_unlockafe_edit_email_record', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
        exit;
    }
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'unlockafe_email_records_nonce')) {
        wp_send_json_error(['message' => 'Security check failed']);
        exit;
    }
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_capture';
    $id = intval($_POST['id'] ?? 0);
    $fields = [];
    if (isset($_POST['name'])) $fields['name'] = sanitize_text_field($_POST['name']);
    if (isset($_POST['email'])) $fields['email'] = sanitize_email($_POST['email']);
    if (isset($_POST['category_id'])) $fields['category_id'] = intval($_POST['category_id']);
    if (isset($_POST['status'])) $fields['status'] = sanitize_text_field($_POST['status']);
    if ($id && !empty($fields)) {
        $updated = $wpdb->update($table, $fields, ['id' => $id]);
        if ($updated !== false) {
            wp_send_json_success();
        } else {
            wp_send_json_error(['message' => 'Update failed']);
        }
    } else {
        wp_send_json_error(['message' => 'Invalid input']);
    }
    exit;
});

add_action('wp_ajax_unlockafe_bulk_delete_email_records', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
        exit;
    }
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'unlockafe_email_records_nonce')) {
        wp_send_json_error(['message' => 'Security check failed']);
        exit;
    }
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_capture';
    $ids = array_filter(array_map('intval', explode(',', $_POST['ids'] ?? '')));
    if ($ids) {
        $in = implode(',', $ids);
        $deleted = $wpdb->query("DELETE FROM $table WHERE id IN ($in)");
        if ($deleted !== false) {
            wp_send_json_success();
        } else {
            wp_send_json_error(['message' => 'Bulk delete failed']);
        }
    } else {
        wp_send_json_error(['message' => 'Invalid IDs']);
    }
    exit;
});

add_action('wp_ajax_unlockafe_get_datewise_counts', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
        exit;
    }
    global $wpdb;
    $table = $wpdb->prefix . 'unlockafe_email_capture';
    $results = $wpdb->get_results("SELECT DATE(submitted_at) as date, COUNT(*) as count FROM $table GROUP BY DATE(submitted_at) ORDER BY date ASC", ARRAY_A);
    wp_send_json_success(['data' => $results]);
    exit;
});

if (! function_exists('UNLOCKAFE_Init')) {
    function UNLOCKAFE_Init()
    {
        return UNLOCKAFE_Final::getInstance();
    }
    UNLOCKAFE_Init();
}

// Initialize Popup Click Tracker
add_action('init', function () {
    if (class_exists('Unlockafe_addons\Classes\Popup_Click_Tracker')) {
        \Unlockafe_addons\Classes\Popup_Click_Tracker::getInstance();
    }
});

// AJAX handler for popup stats (fallback)
add_action('wp_ajax_unlockafe_get_popup_stats', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
        exit;
    }

    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], '_unlockafe_nonce')) {
        wp_send_json_error(['message' => 'Security check failed']);
        exit;
    }

    if (class_exists('Unlockafe_addons\Classes\Popup_Click_Tracker')) {
        $tracker = \Unlockafe_addons\Classes\Popup_Click_Tracker::getInstance();

        // Check if table exists and has data
        global $wpdb;
        $table_name = $wpdb->prefix . 'unlockafe_popup_clicks';
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") === $table_name;

        if (!$table_exists) {
            // Create table if it doesn't exist
            $reflection = new ReflectionClass($tracker);
            $method = $reflection->getMethod('maybe_create_table');
            $method->setAccessible(true);
            $method->invoke($tracker);
        }

        $stats = $tracker->get_stats();

        // If no data exists, optionally create some sample data for testing
        if (empty($stats) && isset($_POST['create_sample']) && $_POST['create_sample'] === 'true') {
            // Create sample data
            $sample_data = [
                ['popup_id' => 'unlockafe-popup-anywhere-promo', 'cta_url' => home_url('/promo'), 'page_url' => home_url('/homepage')],
                ['popup_id' => 'unlockafe-popup-anywhere-promo', 'cta_url' => home_url('/promo'), 'page_url' => home_url('/homepage')],
                ['popup_id' => 'unlockafe-popup-anywhere-promo', 'cta_url' => home_url('/promo'), 'page_url' => home_url('/homepage')],
                ['popup_id' => 'unlockafe-popup-anywhere-exit', 'cta_url' => home_url('/discount'), 'page_url' => home_url('/product')],
            ];

            foreach ($sample_data as $data) {
                $wpdb->insert($table_name, array_merge($data, [
                    'ip_address' => '127.0.0.1',
                    'user_agent' => 'Sample Browser',
                    'created_at' => current_time('mysql')
                ]));
            }

            // Get updated stats
            $stats = $tracker->get_stats();
        }

        wp_send_json_success($stats);
    } else {
        wp_send_json_error(['message' => 'Popup tracker class not available']);
    }
    exit;
});

register_activation_hook(__FILE__, function () {
    if (class_exists('Unlockafe_addons\Classes\Popup_Click_Tracker')) {
        $tracker = \Unlockafe_addons\Classes\Popup_Click_Tracker::getInstance();
        $reflection = new ReflectionClass($tracker);
        $method = $reflection->getMethod('maybe_create_table');
        $method->setAccessible(true);
        $method->invoke($tracker);
    }
});
