<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Edocman_Lite {

    protected $plugin_name;
    protected $version;

    public function __construct() {
        $this->plugin_name = 'edocman-lite';
        $this->version     = EDOCMAN_LITE_VERSION;

        $this->load_dependencies();
        $this->define_admin_hooks();
        $this->define_public_hooks();
        add_action( 'widgets_init', 'edocman_lite_register_categories_widget' );
    }

    private function load_dependencies() {
        require_once EDOCMAN_LITE_PLUGIN_PATH . 'includes/class-edocman-lite-database.php';
        require_once EDOCMAN_LITE_PLUGIN_PATH . 'includes/class-edocman-lite-helper.php';
        require_once EDOCMAN_LITE_PLUGIN_PATH . 'includes/class-edocman-lite-admin.php';
        require_once EDOCMAN_LITE_PLUGIN_PATH . 'includes/class-edocman-lite-public.php';
    }

    private function define_admin_hooks() {
        $plugin_admin = new Edocman_Lite_Admin( $this->get_plugin_name(), $this->get_version() );

        if ( is_admin() ) {
            require_once EDOCMAN_LITE_PLUGIN_PATH . 'admin/class-edocman-lite-admin-categories.php';
            require_once EDOCMAN_LITE_PLUGIN_PATH . 'admin/class-edocman-lite-admin-documents.php';
            require_once EDOCMAN_LITE_PLUGIN_PATH . 'admin/class-edocman-lite-admin-configuration.php';

            $categories_admin    = new Edocman_Lite_Admin_Categories();
            $documents_admin     = new Edocman_Lite_Admin_Documents();
            $configuration_admin = new Edocman_Lite_Admin_Configuration();

            $plugin_admin->set_categories_handler( $categories_admin );
            $plugin_admin->set_documents_handler( $documents_admin );
            $plugin_admin->set_configuration_handler( $configuration_admin );
        }

        add_action( 'admin_enqueue_scripts', array( $plugin_admin, 'enqueue_styles' ) );
        add_action( 'admin_enqueue_scripts', array( $plugin_admin, 'enqueue_scripts' ) );
        add_action( 'admin_enqueue_scripts', array( $plugin_admin, 'enqueue_admin_media_scripts' ) );
        add_action( 'admin_menu',            array( $plugin_admin, 'add_plugin_admin_menu' ) );
        add_action( 'wp_ajax_edocman_lite_delete_document', array( $plugin_admin, 'ajax_delete_document' ) );
        add_action( 'wp_ajax_edocman_lite_delete_category', array( $plugin_admin, 'ajax_delete_category' ) );
    }

    private function define_public_hooks() {
        $plugin_public = new Edocman_Lite_Public( $this->get_plugin_name(), $this->get_version() );

        add_action( 'wp_enqueue_scripts', array( $plugin_public, 'enqueue_styles' ) );
        add_action( 'wp_enqueue_scripts', array( $plugin_public, 'enqueue_scripts' ) );

        $plugin_public->init_shortcodes();

        add_action( 'wp', array( $plugin_public, 'handle_download' ) );
        add_action( 'wp', array( $plugin_public, 'handle_document_view' ) );

        add_action( 'wp_ajax_edocman_lite_delete_my_document', array( $plugin_public, 'ajax_delete_my_document' ) );
    }

    public function run() {
        add_action( 'plugins_loaded', array( $this, 'check_upload_directories' ) );
    }

    public function check_upload_directories() {
        $edocman_lite_dir = Edocman_Lite_Helper::get_config( 'documents_path' );

        if ( ! file_exists( $edocman_lite_dir ) ) {
            $this->create_upload_directories();
        }
    }

    private function create_upload_directories() {
        $edocman_lite_dir = Edocman_Lite_Helper::get_config( 'documents_path' );

        // ✅ Validate the path is inside the uploads directory to prevent
        // writing security files to arbitrary locations.
        $upload_dir       = wp_upload_dir();
        $uploads_basedir  = wp_normalize_path( $upload_dir['basedir'] );
        $normalized_dir   = wp_normalize_path( $edocman_lite_dir );

        if ( strpos( $normalized_dir, $uploads_basedir ) !== 0 ) {
            // Path is outside uploads — abort silently for safety.
            return;
        }

        $directories = array(
            $edocman_lite_dir,
            $edocman_lite_dir . '/categories',
            $edocman_lite_dir . '/categories/thumb',
            $edocman_lite_dir . '/documents',
            $edocman_lite_dir . '/documents/thumb',
        );

        foreach ( $directories as $dir ) {
            if ( ! file_exists( $dir ) ) {
                wp_mkdir_p( $dir );
                $this->create_security_files( $dir );
            }
        }
    }

    /**
     * Create protective index.php and .htaccess files using WP_Filesystem.
     *
     * @param string $dir Absolute path to the directory (already validated as uploads-based).
     */
    private function create_security_files( $dir ) {
        global $wp_filesystem;

        if ( ! function_exists( 'WP_Filesystem' ) ) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        WP_Filesystem();

        // .htaccess — prevent directory listing and direct access.
        $htaccess_file = $dir . '/.htaccess';
        if ( ! $wp_filesystem->exists( $htaccess_file ) ) {
            $htaccess_content = "Options -Indexes\ndeny from all\n";
            $wp_filesystem->put_contents( $htaccess_file, $htaccess_content, FS_CHMOD_FILE );
        }

        // index.php — silent fallback to block directory browsing on non-Apache servers.
        $index_file = $dir . '/index.php';
        if ( ! $wp_filesystem->exists( $index_file ) ) {
            $wp_filesystem->put_contents( $index_file, "<?php\n// Silence is golden.\n", FS_CHMOD_FILE );
        }
    }

    public function get_plugin_name() {
        return $this->plugin_name;
    }

    public function get_version() {
        return $this->version;
    }

    public static function activate() {
        require_once EDOCMAN_LITE_PLUGIN_PATH . 'includes/class-edocman-lite-database.php';
        $database = new Edocman_Lite_Database();
        $database->create_tables();

        // Create upload directories inside wp-content/uploads/edocman-lite.
        $upload_dir       = wp_upload_dir();
        $edocman_lite_dir = $upload_dir['basedir'] . '/edocman-lite';

        $directories = array(
            $edocman_lite_dir,
            $edocman_lite_dir . '/categories',
            $edocman_lite_dir . '/categories/thumb',
            $edocman_lite_dir . '/documents',
            $edocman_lite_dir . '/documents/thumb',
        );

        foreach ( $directories as $dir ) {
            if ( ! file_exists( $dir ) ) {
                wp_mkdir_p( $dir );
            }
        }

        flush_rewrite_rules();
    }

    public static function deactivate() {
        flush_rewrite_rules();
    }
}

function edocman_lite_register_categories_widget() {
    if ( class_exists( 'Edocman_Lite_Categories_Widget' ) ) {
        register_widget( 'Edocman_Lite_Categories_Widget' );
    }
}
