<?php

/**
 * Plugin Name: Easy File Upload & Approval
 * Plugin URI:  https://www.codedropz.com
 * Description: Drag & drop file uploads with a built‑in approval workflow. Perfect for job applications, contest entries, print shops, agencies, teachers, document submission and any site that needs users to submit files for review.
 * Version:     1.0.1
 * Author:      Glen Don Mongaya
 * Author URI:  https://profiles.wordpress.org/glenwpcoder/
 * License:     GPL-2.0-or-later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: easy-file-upload-approval
 * Domain Path: /languages
 *
 * @package EASYFUA
 *
 */
defined( 'ABSPATH' ) || exit;
if ( !function_exists( 'easyfua_fs' ) ) {
    // Create a helper function for easy SDK access.
    function easyfua_fs() {
        global $easyfua_fs;
        if ( !isset( $easyfua_fs ) ) {
            // Activate multisite network integration.
            if ( !defined( 'WP_FS__PRODUCT_22444_MULTISITE' ) ) {
                define( 'WP_FS__PRODUCT_22444_MULTISITE', true );
            }
            // Include Freemius SDK.
            require_once dirname( __FILE__ ) . '/includes/freemius/start.php';
            $easyfua_fs = fs_dynamic_init( array(
                'id'               => '22444',
                'slug'             => 'easy-file-upload-approval',
                'type'             => 'plugin',
                'public_key'       => 'pk_4095444d6f1409de0b76f78168361',
                'is_premium'       => false,
                'has_addons'       => false,
                'has_paid_plans'   => true,
                'is_org_compliant' => true,
                'menu'             => array(
                    'slug'       => 'easyfua-main-menu',
                    'first-path' => 'admin.php?page=easyfua-main-menu',
                    'contact'    => false,
                    'support'    => false,
                ),
                'is_live'          => true,
            ) );
        }
        return $easyfua_fs;
    }

    // Init Freemius.
    easyfua_fs();
    // Uninstall or cleanup hook.
    easyfua_fs()->add_action( 'after_uninstall', 'easyfua_cleanup' );
    // Hide monthly plan.
    easyfua_fs()->add_filter( 'pricing/show_annual_in_monthly', '__return_false' );
    // Signal that SDK was initiated.
    do_action( 'easyfua_fs_loaded' );
}
/**
 * Main plugin file and class for EASYFUA.
 */
final class EASYFUA {
    /**
     * Stores the single instance of EASYFUA_Plugin.
     *
     * @var EASYFUA
     */
    private static $instance;

    /**
     * Gets the singleton instance of the plugin.
     *
     * This method ensures that only one instance of the plugin class is created.
     * If an instance already exists, it returns that instance. Otherwise, it creates
     * a new one.
     *
     * @return EASYFUA The single instance of the plugin.
     */
    public static function get_instance() {
        if ( !isset( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     *
     * This private constructor prevents direct instantiation of the class
     * from outside. It initializes the plugin by defining constants,
     * loading necessary dependencies, and registering core hooks.
     */
    private function __construct() {
        // Define essential plugin constants.
        $this->define_constants();
        // Include all necessary plugin files (classes, functions, etc.).
        $this->includes();
        // Register the main initialization hook for the plugin.
        add_action( 'plugins_loaded', array($this, 'init') );
    }

    /**
     * Defines plugin constants.
     *
     * These constants provide easy access to important paths and version information
     * throughout the plugin, making the code more maintainable and robust.
     */
    private function define_constants() {
        define( 'EASYFUA_VERSION', '1.0.1' );
        define( 'EASYFUA_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
        define( 'EASYFUA_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
        define( 'EASYFUA_PLUGIN_NAME', basename( EASYFUA_PLUGIN_DIR ) );
        define( 'EASYFUA_PLUGIN_DIR_INC', EASYFUA_PLUGIN_DIR . 'includes/' );
        define( 'EASYFUA_PLUGIN_FILE', __FILE__ );
        define( 'EASYFUA_TABLE_FILES', 'easyfua_files' );
        define( 'EASYFUA_TABLE_SUBMISSIONS', 'easyfua_submissions' );
        define( 'EASYFUA_UPLOAD_FOLDER', 'easy-file-upload-approval' );
    }

    /**
     * Includes necessary plugin files.
     *
     * This method loads all the individual class files that make up the plugin's
     * functionality. This modular approach keeps the codebase organized.
     */
    private function includes() {
        // Plugin custom functions.
        require_once EASYFUA_PLUGIN_DIR_INC . 'easyfua-functions.php';
        // File manager class.
        require_once EASYFUA_PLUGIN_DIR_INC . 'file-manager/class-easyfua-file-manager.php';
        // Email manager class.
        require_once EASYFUA_PLUGIN_DIR_INC . 'email/class-easyfua-email-manager.php';
        // Admin-specific functionalities.
        require_once EASYFUA_PLUGIN_DIR . 'admin/class-easyfua-admin.php';
        // Public-facing (frontend) functionalities.
        require_once EASYFUA_PLUGIN_DIR . 'public/class-easyfua-frontend.php';
    }

    /**
     * Initializes the plugin.
     *
     * This method is called after all plugins are loaded via the 'plugins_loaded' hook.
     * It instantiates the main components of the plugin and loads the text domain
     * for internationalization.
     */
    public function init() {
        // Instantiate admin components only if in the admin area.
        if ( is_admin() ) {
            new EASYFUA_Admin();
        }
        // Instantiate frontend components.
        new EASYFUA_Frontend();
        // Email Manager.
        new EASYFUA_Email_Manager();
    }

    /**
     * Activation hook callback.
     *
     * This method is called when the plugin is activated.
     * It's used for setup tasks like creating database tables, setting default options,
     * or scheduling events.
     */
    public function activate() {
        $this->add_options();
        $this->create_database();
        $this->schedule_cron();
    }

    /**
     * Add default option/settings.
     *
     * @return void
     */
    public function add_options() {
        add_option( 'easyfua_settings', array(
            'required' => 'yes',
        ) );
    }

    /**
     * Create submission and submission files table.
     *
     * @return void
     */
    public function create_database() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        $sql = '
			CREATE TABLE `' . $wpdb->prefix . EASYFUA_TABLE_FILES . '` (
				id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				submission_id BIGINT(20) UNSIGNED DEFAULT NULL,
				file_name VARCHAR(255) NOT NULL,
				file_url TEXT NOT NULL,
				file_type VARCHAR(100) DEFAULT NULL,
				file_size BIGINT(20) DEFAULT NULL,
				file_status ENUM("temp", "pending", "approved", "rejected", "deleted") DEFAULT "temp",
				admin_note TEXT DEFAULT NULL,
				file_meta TEXT DEFAULT NULL,
				approved_by BIGINT(20) UNSIGNED DEFAULT NULL,
				submitted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
				updated_at DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
				PRIMARY KEY  (id),
				KEY file_status (file_status)
			) ' . $charset_collate . ';

			CREATE TABLE `' . $wpdb->prefix . EASYFUA_TABLE_SUBMISSIONS . '` (
				id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				user_id BIGINT(20) UNSIGNED DEFAULT NULL,
				form_data LONGTEXT DEFAULT NULL,
				total_files INT(11) DEFAULT 0,
				status ENUM("pending","approved","rejected","partial","deleted") DEFAULT "pending",
				submitted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
				is_notified TINYINT(1) DEFAULT 0,
				updated_at DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
				PRIMARY KEY (id),
				KEY user_id (user_id),
				KEY status (status)
			) ' . $charset_collate . ';
		';
        dbDelta( $sql );
    }

    /**
     * Schedule a cron
     *
     * @return void
     */
    public function schedule_cron() {
        if ( !wp_next_scheduled( 'easyfua_delete_temp_files' ) ) {
            wp_schedule_event( time(), 'twicedaily', 'easyfua_delete_temp_files' );
        }
    }

    /**
     * Deactivation hook callback.
     *
     * This method is called when the plugin is deactivated.
     * It's used for cleanup tasks like removing transients or scheduled events.
     */
    public function deactivate() {
        wp_clear_scheduled_hook( 'easyfua_delete_temp_files' );
    }

}

// Plugin instance.
$easyfua = EASYFUA::get_instance();
// Call Activate and Deactivate.
register_activation_hook( __FILE__, array($easyfua, 'activate') );
register_deactivation_hook( __FILE__, array($easyfua, 'deactivate') );
// Clean up or uninstall
function easyfua_cleanup() {
    global $wpdb;
    // Deleting tables.
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}easyfua_submissions" );
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}easyfua_files" );
    // Delete option/settings.
    $wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'easyfua_settings%'" );
}
