<?php

/**
 * Plugin Name:       Leadite
 * Plugin URI:        https://akava.site/leadite
 * Description:       Lead manager & database for Contact Form 7, Elementor, WPForms, and more. Auto-saves submissions, features advanced data exports (XLSX, CSV, JSON, XML), almost instant Telegram alerts, Google Sheets sync, follow-up tracking, and full RTL + multilingual support.
 * Version:           0.3.10
 * Requires at least: 6.2
 * Requires PHP:      7.4
 * Author:            AKAVA
 * Author URI:		  https://akava.site/
 * License:           GPL-2.0-or-later
 * Text Domain:       leadite
 * Domain Path:       /languages
 *
 * @package Leadite
 *
 */
defined( 'ABSPATH' ) || exit;
// Freemius integration.
if ( function_exists( 'leadite_fs' ) ) {
    leadite_fs()->set_basename( false, __FILE__ );
} else {
    // phpcs:disable -- Freemius boilerplate
    function leadite_fs() {
        global $leadite_fs;
        if ( !isset( $leadite_fs ) ) {
            require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
            $leadite_fs = fs_dynamic_init( array(
                'id'               => '33063',
                'slug'             => 'leadite',
                'premium_slug'     => 'leadite-pro',
                'type'             => 'plugin',
                'public_key'       => 'pk_a85179356323c04b0422cb9097104',
                'is_premium'       => false,
                'premium_suffix'   => '(Pro)',
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => true,
                'trial'            => array(
                    'days'               => 14,
                    'is_require_payment' => false,
                ),
                'menu'             => array(
                    'slug'       => 'leadite',
                    'first-path' => 'admin.php?page=leadite',
                    'account'    => true,
                    'pricing'    => true,
                    'contact'    => false,
                    'support'    => false,
                ),
                'is_live'          => true,
            ) );
        }
        return $leadite_fs;
    }

    // phpcs:enable
    leadite_fs();
    leadite_fs()->add_filter(
        'is_submenu_visible',
        function ( $is_visible, $id ) {
            if ( in_array( $id, array('pricing', 'contact', 'support'), true ) ) {
                return false;
            }
            return $is_visible;
        },
        10,
        2
    );
    do_action( 'leadite_fs_loaded' );
    // Uninstall cleanup —“ using internal leadite_ prefixed data.
    if ( !function_exists( 'leadite_fs_uninstall_cleanup' ) ) {
        function leadite_fs_uninstall_cleanup() {
            global $wpdb;
            $settings = get_option( 'leadite_settings' );
            if ( !is_array( $settings ) || empty( $settings['delete_on_uninstall'] ) ) {
                return;
            }
            $files_table = $wpdb->prefix . 'leadite_files';
            $upload_dir = wp_upload_dir();
            $root = realpath( $upload_dir['basedir'] . '/leadite' );
            if ( $root ) {
                global $wp_filesystem;
                if ( empty( $wp_filesystem ) ) {
                    require_once ABSPATH . 'wp-admin/includes/file.php';
                    WP_Filesystem();
                }
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                $file_rows = $wpdb->get_results( $wpdb->prepare( "SELECT file_path FROM %i", $files_table ) );
                if ( $file_rows ) {
                    $dirs_to_clean = array();
                    foreach ( $file_rows as $frow ) {
                        $rel = ltrim( $frow->file_path, '/' );
                        $abs = $upload_dir['basedir'] . '/' . $rel;
                        $real = realpath( $abs );
                        if ( $real && 0 === strpos( $real, $root . DIRECTORY_SEPARATOR ) ) {
                            wp_delete_file( $real );
                            $dirs_to_clean[dirname( $real )] = true;
                        }
                    }
                    foreach ( array_keys( $dirs_to_clean ) as $dir ) {
                        if ( is_dir( $dir ) ) {
                            $remaining = array_diff( scandir( $dir ), array(
                                '.',
                                '..',
                                'index.php',
                                '.htaccess'
                            ) );
                            if ( empty( $remaining ) ) {
                                $idx = $dir . '/index.php';
                                if ( file_exists( $idx ) ) {
                                    wp_delete_file( $idx );
                                }
                                $wp_filesystem->delete( $dir );
                            }
                        }
                    }
                }
                $root_htaccess = $root . '/.htaccess';
                $root_index = $root . '/index.php';
                if ( file_exists( $root_htaccess ) ) {
                    wp_delete_file( $root_htaccess );
                }
                if ( file_exists( $root_index ) ) {
                    wp_delete_file( $root_index );
                }
                $root_remaining = array_diff( scandir( $root ), array('.', '..') );
                if ( empty( $root_remaining ) ) {
                    $wp_filesystem->delete( $root );
                }
            }
            $tables = array(
                $wpdb->prefix . 'leadite_submissions',
                $wpdb->prefix . 'leadite_meta',
                $wpdb->prefix . 'leadite_notes',
                $wpdb->prefix . 'leadite_log',
                $wpdb->prefix . 'leadite_files',
                $wpdb->prefix . 'leadite_tags',
                $wpdb->prefix . 'leadite_submission_tags',
                $wpdb->prefix . 'leadite_field_map'
            );
            foreach ( $tables as $table ) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.DirectDatabaseQuery.SchemaChange,PluginCheck.Security.DirectDB -- DROP TABLE on uninstall
                $wpdb->query( $wpdb->prepare( "DROP TABLE IF EXISTS %i", $table ) );
            }
            delete_option( 'leadite_settings' );
            delete_option( 'leadite_db_version' );
            $role = get_role( 'administrator' );
            if ( $role ) {
                $role->remove_cap( 'manage_leads' );
            }
            delete_transient( 'leadite_v1_status_counts' );
            delete_transient( 'leadite_v1_kpis' );
            delete_metadata(
                'user',
                '',
                'leadite_view_mode',
                '',
                true
            );
            delete_metadata(
                'user',
                '',
                'leadite_leads_per_page',
                '',
                true
            );
        }

    }
    leadite_fs()->add_action( 'after_uninstall', 'leadite_fs_uninstall_cleanup' );
    /**
     * Custom trial invitation message (Pro trial).
     */
    leadite_fs()->add_filter( 'trial_promotion_message', function ( $message ) {
        return sprintf( 
            /* translators: %s: Plugin name (Leadite) */
            __( 'Hey! Enjoying %s? Unlock advanced features like <b>Telegram alerts, Google Sheets sync, SLA tracking, and deep data exports</b> with a 14-day free trial. No credit card required!', 'leadite' ),
            'Leadite'
         );
    } );
    define( 'leadite_VERSION', '0.3.10' );
    define( 'leadite_FILE', __FILE__ );
    define( 'leadite_PATH', plugin_dir_path( __FILE__ ) );
    define( 'leadite_URL', plugin_dir_url( __FILE__ ) );
    define( 'leadite_DB_VERSION', '6' );
    if ( !function_exists( 'leadite_get_upgrade_url' ) ) {
        /**
         * Returns the Freemius upgrade URL, or a fallback landing page URL.
         *
         * @return string
         */
        function leadite_get_upgrade_url() : string {
            if ( function_exists( 'leadite_fs' ) ) {
                return leadite_fs()->get_upgrade_url();
            }
            return 'https://akava.site/leadite-pro';
        }

    }
    /**
     * PSR-4 autoloader for the Leadite\ namespace.
     * Maps Leadite\Capture\Cf7Adapter -> src/Capture/Cf7Adapter.php
     */
    spl_autoload_register( static function ( $class ) {
        $prefix = 'Leadite\\';
        if ( 0 !== strpos( $class, $prefix ) ) {
            return;
        }
        $relative = substr( $class, strlen( $prefix ) );
        $path = leadite_PATH . 'src/' . str_replace( '\\', '/', $relative ) . '.php';
        if ( is_readable( $path ) ) {
            require $path;
        }
    } );
    if ( file_exists( leadite_PATH . 'vendor/autoload.php' ) ) {
        require_once leadite_PATH . 'vendor/autoload.php';
    }
    register_activation_hook( __FILE__, array('Leadite\\Activator', 'activate') );
    register_deactivation_hook( __FILE__, array('Leadite\\Deactivator', 'deactivate') );
    add_action( 'plugins_loaded', static function () {
        \Leadite\Plugin::instance()->boot();
    } );
    // Backward-compat redirects: soft-redirect old admin page slugs to new Leadite slugs.
    add_action( 'admin_init', static function () {
        if ( !isset( $_GET['page'] ) ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return;
        }
        $page = sanitize_key( wp_unslash( $_GET['page'] ) );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $map = array(
            'LeadHub'             => 'leadite',
            'leadhub'             => 'leadite',
            'leadhub-leads'       => 'leadite-leads',
            'leadhub-smart-views' => 'leadite-smart-views',
            'leadhub-settings'    => 'leadite-settings',
        );
        if ( isset( $map[$page] ) ) {
            $new_args = array_merge( $_GET, array(
                'page' => $map[$page],
            ) );
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            wp_safe_redirect( add_query_arg( $new_args, admin_url( 'admin.php' ) ), 301 );
            exit;
        }
    } );
    // Pro status revalidation cron.
    add_action( 'leadite_revalidate_pro', array('Leadite\\Pro', 'invalidate_cache') );
    add_action( 'admin_enqueue_scripts', static function () {
        if ( !isset( $_GET['page'] ) || 0 !== strpos( sanitize_key( $_GET['page'] ), 'leadite' ) ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return;
        }
        wp_enqueue_script(
            'leadite-easter-egg',
            leadite_URL . 'assets/js/leadite-easter-egg.js',
            array(),
            leadite_VERSION,
            true
        );
        wp_localize_script( 'leadite-easter-egg', 'leaditeEaster', array(
            'version' => leadite_VERSION,
        ) );
    } );
    add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), function ( $links ) {
        $settings_link = '<a href="' . esc_url( admin_url( 'admin.php?page=leadite-settings' ) ) . '">' . esc_html__( 'Settings', 'leadite' ) . '</a>';
        array_unshift( $links, $settings_link );
        return $links;
    } );
}