<?php

/**
 * Admin stuff goes here
 *
 * This class Display file submission, sort files, approve files
 *
 * @package EASYFUA
 */
// Prevent direct access.
defined( 'ABSPATH' ) || exit;
/**
 * Admin Main Class
 */
class EASYFUA_Admin {
    /**
     * Default language.
     *
     * @var string
     */
    public $lang = '';

    /**
     * Plugin admin menu slug.
     *
     * @var string
     */
    const EASYFUA_SLUG = 'easyfua-main-menu';

    /**
     * Plugin settings.
     *
     * @var string
     */
    private $settings = array();

    private $submission = '';

    /**
     * Plugin parent constructor which run hooks, and file inclusions.
     */
    public function __construct() {
        $this->admin_init();
        $this->hooks();
    }

    /**
     * Initialize class or custom function.
     *
     * @return void
     */
    public function admin_init() {
        $this->lang = easyfua_lang();
    }

    /**
     * Process or run hooks.
     *
     * @return void
     */
    public function hooks() {
        add_action( 'admin_enqueue_scripts', array($this, 'admin_enqueue') );
        add_action( 'admin_menu', array($this, 'admin_menu') );
        add_action( 'admin_init', array($this, 'register_settings') );
        add_filter(
            'pre_update_option_easyfua_settings' . $this->lang,
            array($this, 'pre_update_settings'),
            10,
            2
        );
        // Generate robot.txt.
        add_action(
            'update_option_easyfua_settings' . $this->lang,
            array($this, 'manage_robot_txt'),
            10,
            2
        );
        // Add index.php file.
        add_action( 'admin_init', array($this, 'generate_index_file') );
        // Load class list table.
        add_action( 'load-toplevel_page_' . self::EASYFUA_SLUG, array($this, 'load_dependencies'), 15 );
        // Hook before sent header.
        add_action( 'load-toplevel_page_' . self::EASYFUA_SLUG, array($this, 'handle_bulk_actions'), 20 );
        // Ajax with notes reject.
        add_action( 'wp_ajax_easyfua_reject_files', array($this, 'reject_with_notes') );
        // Append robots.txt file.
        add_filter(
            'robots_txt',
            array($this, 'add_robot_disallow'),
            10,
            2
        );
        // Add plugin settings links.
        add_filter( 'plugin_action_links_' . plugin_basename( EASYFUA_PLUGIN_DIR ) . '/easy-file-upload-approval.php', array($this, 'plugin_settings') );
    }

    /**
     * Include list table dependencies.
     *
     * @return void
     */
    public function load_dependencies() {
        // Load submission class.
        require_once EASYFUA_PLUGIN_DIR_INC . 'admin/class-easyfua-submissions.php';
        require_once EASYFUA_PLUGIN_DIR_INC . 'admin/class-easyfua-submissions-files.php';
    }

    /**
     * Enqueing scripts assets like css/js
     *
     * @param mixed $hook Page slug.
     * @return void
     */
    public function admin_enqueue( $hook ) {
        // Optionally restrict to specific admin page.
        if ( 'easy-file-upload_page_easyfua-settings' !== $hook && 'toplevel_page_' . self::EASYFUA_SLUG !== $hook ) {
            return;
        }
        wp_enqueue_script( 'jquery-ui-dialog' );
        wp_enqueue_style( 'wp-jquery-ui-dialog' );
        wp_enqueue_style(
            'easyfua-admin',
            EASYFUA_PLUGIN_URL . 'admin/css/easyfua-admin.css',
            array(),
            EASYFUA_VERSION
        );
        wp_enqueue_script(
            'easyfua-admin',
            EASYFUA_PLUGIN_URL . 'admin/js/easyfua-admin.js',
            array('jquery'),
            EASYFUA_VERSION,
            true
        );
        wp_localize_script( 'easyfua-admin', 'easyfua', array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'easyfua_ajax_nonce' ),
        ) );
    }

    /**
     * Register admin menu.
     *
     * @return void
     */
    public function admin_menu() {
        // Add top-level menu page.
        add_menu_page(
            __( 'WP easyfua', 'easy-file-upload-approval' ),
            __( 'Easy File Upload', 'easy-file-upload-approval' ),
            'manage_options',
            self::EASYFUA_SLUG,
            array($this, 'render_file_submission_page'),
            'dashicons-upload',
            6
        );
        // Add submenu page for File Submission.
        add_submenu_page(
            self::EASYFUA_SLUG,
            __( 'File Submissions', 'easy-file-upload-approval' ),
            __( 'File Submissions', 'easy-file-upload-approval' ),
            'manage_options',
            self::EASYFUA_SLUG,
            array($this, 'render_file_submission_page')
        );
        // Add submenu page for plugin settings.
        add_submenu_page(
            self::EASYFUA_SLUG,
            __( 'Settings', 'easy-file-upload-approval' ),
            __( 'Settings', 'easy-file-upload-approval' ),
            'manage_options',
            'easyfua-settings',
            array($this, 'render_settings_page')
        );
    }

    /**
     * Handle process bulk actions. (before header sent).
     *
     * @return void
     */
    public function handle_bulk_actions() {
        // Verify nonce
        if ( isset( $_REQUEST['_wpnonce'] ) ) {
            check_admin_referer( 'easyfua-nonce' );
        }
        $table = new EASYFUA_Submissions();
        $view = ( isset( $_GET['sub'] ) ? sanitize_text_field( wp_unslash( $_GET['sub'] ) ) : '' );
        if ( 'view-files' === $view ) {
            $table = new EASYFUA_Submissions_Files();
        }
        $table->process_bulk_action();
    }

    /**
     * Display HTML file submission.
     *
     * @return void
     */
    public function render_file_submission_page() {
        // Verify nonce
        if ( isset( $_REQUEST['_wpnonce'] ) ) {
            check_admin_referer( 'easyfua-nonce' );
        }
        // Load table based on action.
        $list_table = new EASYFUA_Submissions();
        $view = ( isset( $_GET['sub'] ) ? sanitize_text_field( wp_unslash( $_GET['sub'] ) ) : '' );
        if ( 'view-files' === $view ) {
            $list_table = new EASYFUA_Submissions_Files();
        }
        // Preparing data items.
        $list_table->prepare_items();
        ?>

		<!-- Modal for rejection -->
		<div id="easyfua-reject-modal" title="Reject File(s)" class="hidden">
			<form id="easyfua-reject-form">
				<div id="easyfua-reject-fields"></div>
				<p class="easyfua-submit" style="margin: 0;">
					<button type="submit" class="button button-primary">Submit</button>
				</p>
			</form>
		</div>

		<div class="wrap">
			<?php 
        // Display heading.
        $list_table->heading();
        // Display admin notice.
        easyfua_admin_notices();
        ?>
			<form method="GET" id="easyfua-admin-form">
				<input type="hidden" name="page" value="<?php 
        echo esc_attr( sanitize_key( self::EASYFUA_SLUG ) );
        ?>">

				<?php 
        if ( isset( $_GET['sub'] ) && !empty( $_GET['sub'] ) ) {
            printf( '<input type="hidden" value="%s" name="sub">', esc_attr( sanitize_key( wp_unslash( $_GET['sub'] ) ) ) );
        }
        if ( isset( $_GET['submission_id'] ) && !empty( $_GET['submission_id'] ) ) {
            printf( '<input type="hidden" value="%s" name="submission_id">', intval( $_GET['submission_id'] ) );
        }
        ?>

				<?php 
        echo '<ul class="subsubsub">';
        echo wp_kses_post( implode( ' | ', $list_table->get_views() ) );
        echo '</ul>';
        ?>
				<?php 
        $list_table->search_box( __( 'Search', 'easy-file-upload-approval' ), 'easyfua' );
        $list_table->display();
        ?>
			</form>
		</div>

		<?php 
    }

    /**
     * Display plugin settings.
     *
     * @return void
     */
    public function render_settings_page() {
        // Verify nonce.
        if ( isset( $_REQUEST['_wpnonce'] ) ) {
            check_admin_referer( 'easyfua-nonce' );
        }
        $active_tab = ( isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'settings' );
        $section = ( isset( $_GET['section'] ) ? sanitize_key( $_GET['section'] ) : 'admin-notification' );
        ?>
		<div class="wrap">
			<h1><?php 
        esc_html_e( 'Easy File Upload Approval - Settings', 'easy-file-upload-approval' );
        ?></h1>
			<?php 
        settings_errors();
        ?>
			<nav class="nav-tab-wrapper">
				<a href="?page=easyfua-settings&tab=settings" class="nav-tab <?php 
        echo ( 'settings' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'Settings', 'easy-file-upload-approval' );
        ?></a>

				<?php 
        ?>

				<a href="?page=easyfua-settings&tab=extra-fields" class="nav-tab <?php 
        echo ( 'extra-fields' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'Extra Fields', 'easy-file-upload-approval' );
        ?></a>
				<a href="?page=easyfua-settings&tab=mail-settings" class="nav-tab <?php 
        echo ( 'mail-settings' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'Email Templates', 'easy-file-upload-approval' );
        ?></a>
				<a href="?page=easyfua-settings&tab=error-messages" class="nav-tab <?php 
        echo ( 'error-messages' === $active_tab ? 'nav-tab-active' : '' );
        ?>"><?php 
        esc_html_e( 'Error Messages', 'easy-file-upload-approval' );
        ?></a>
			</nav>

			<?php 
        if ( 'mail-settings' === $active_tab ) {
            ?>
				<ul class="subsubsub">
					<li><a href="<?php 
            echo esc_url( wp_nonce_url( '?page=easyfua-settings&tab=mail-settings&section=admin-notification', 'easyfua-nonce' ) );
            ?>" class="<?php 
            echo ( 'admin-notification' === $section ? 'current' : '' );
            ?>"><?php 
            esc_html_e( 'Admin Notification', 'easy-file-upload-approval' );
            ?></a> |</li>
					<li><a href="<?php 
            echo esc_url( wp_nonce_url( '?page=easyfua-settings&tab=mail-settings&section=user-notification ', 'easyfua-nonce' ) );
            ?>" class="<?php 
            echo ( 'user-notification' === $section ? 'current' : '' );
            ?>"><?php 
            esc_html_e( 'User Notification', 'easy-file-upload-approval' );
            ?></a> |</li>
					<li><a href="<?php 
            echo esc_url( wp_nonce_url( '?page=easyfua-settings&tab=mail-settings&section=submission-status', 'easyfua-nonce' ) );
            ?>" class="<?php 
            echo ( 'submission-status' === $section ? 'current' : '' );
            ?>"><?php 
            esc_html_e( 'Submission Status', 'easy-file-upload-approval' );
            ?></a></li>

				</ul>
				<br class="clear">
			<?php 
        }
        ?>

			<form method="post" action="options.php">
				<?php 
        settings_fields( 'easyfua_settings_group' . $this->lang );
        if ( 'settings' === $active_tab ) {
            $this->render_settings();
        } elseif ( 'pro' === $active_tab && easyfua_is_premium() ) {
            // Pro render only.
        } elseif ( 'extra-fields' === $active_tab ) {
            $this->render_admin_fields();
        } elseif ( 'error-messages' === $active_tab ) {
            $this->render_error_messages();
        } elseif ( 'mail-settings' === $active_tab ) {
            $this->render_mail_settings();
        }
        ?>
				<?php 
        submit_button();
        ?>
			</form>
		</div>
		<?php 
    }

    /**
     * Reject file with notes.
     *
     * @return void
     */
    public function reject_with_notes() {
        // Check ajax nonce.
        check_ajax_referer( 'easyfua_ajax_nonce' );
        // Get the notes.
        $notes = ( isset( $_POST['notes'] ) ? array_map( 'wp_kses_post', wp_unslash( $_POST['notes'] ) ) : array() );
        // Referer url.
        $referrer_url = ( isset( $_POST['_referer'] ) ? esc_url_raw( wp_unslash( $_POST['_referer'] ) ) : '' );
        // Parse url.
        $args = array();
        wp_parse_str( $referrer_url, $args );
        // File Manager class.
        if ( !isset( $args['submission_id'] ) ) {
            wp_send_json_error( __( 'Invalid Request.', 'easy-file-upload-approval' ) );
        }
        // Updating status.
        $rejected = 0;
        // File Manager.
        $submission_id = absint( $args['submission_id'] );
        $file_manager = new EASYFUA_File_Manager($submission_id);
        // Loop each note and update files table.
        foreach ( $notes as $file_id => $note ) {
            $result = $file_manager->reject_file( $file_id, $note );
            if ( false !== $result ) {
                ++$rejected;
            }
        }
        // Add query results on uri.
        if ( $rejected > 0 ) {
            $result = ( $rejected > 1 ? 'rejected-multi' : 'rejected' );
            wp_send_json_success( add_query_arg( 'result', $result, $referrer_url ) );
        }
    }

    /**
     * Pre update settings hook.
     *
     * @param mixed $new New settings value.
     * @param mixed $old Old settings value.
     */
    public function pre_update_settings( $new, $old ) {
        $old_value = (array) $old;
        $new_value = (array) $new;
        if ( !empty( $old ) ) {
            return array_merge( $old_value, $new_value );
        }
        return $new;
    }

    /**
     * Manage robot text file.
     *
     * @param mixed $old Old settings value.
     * @param mixed $new New settings value.
     * @return void
     */
    public function manage_robot_txt( $old, $new ) {
        $this->settings = $new;
    }

    /**
     * Filters the robots.txt output.
     *
     * @param mixed $ouput Robots.txt output
     * @param mixed $public Whether the site is considered "public".
     * @return void
     */
    public function add_robot_disallow( $output, $public ) {
        $sub_folder = ( isset( $this->settings['upload_folder_name'] ) ? trim( $this->settings['upload_folder_name'] ) : 'easyfua-uploads' );
        $upload_dir = wp_upload_dir();
        $upload_folder = basename( $upload_dir['basedir'] );
        $content_path = basename( WP_CONTENT_DIR );
        $upload_base = '/' . $content_path . '/' . $upload_folder . '/' . $sub_folder;
        $new_entry = "Disallow: {$upload_base}/{$sub_folder}";
        if ( strpos( $output, $new_entry ) === false ) {
            $output .= "\n{$new_entry}";
        }
        return $output;
    }

    /**
     * Generate empty index.php file.
     *
     * @return void
     */
    public function generate_index_file() {
        $dir = easyfua_dir();
        $index_file = trailingslashit( $dir['dir'] ) . 'index.php';
        // Only create if directory exists and index.php is missing.
        if ( is_dir( $dir['dir'] ) && !file_exists( $index_file ) ) {
            @file_put_contents( $index_file, "<?php\n// Silence is golden.\n" );
        }
    }

    /**
     * Callback to save admin settings.
     *
     * @return void
     */
    public function register_settings() {
        $lang = easyfua_lang();
        register_setting( 'easyfua_settings_group' . $this->lang, 'easyfua_settings' . $this->lang, array(
            'type'              => 'array',
            'sanitize_callback' => array($this, 'sanitize_settings'),
        ) );
    }

    /**
     * Sanitize all plugin settings.
     *
     * @param array $input Fields input from the settings.
     * @return array
     */
    public function sanitize_settings( $input ) {
        $sanitized = array();
        foreach ( (array) $input as $key => $value ) {
            // Handle nested arrays (like admin_notif).
            if ( is_array( $value ) ) {
                $sanitized[$key] = $this->sanitize_settings( $value );
                continue;
            }
            switch ( $key ) {
                // --- Textareas / allow limited HTML ---
                case 'email':
                case 'subject':
                case 'message':
                case 'mime_types':
                    $sanitized[$key] = wp_kses_post( $value );
                    break;
                case 'headers':
                    $sanitized[$key] = trim( htmlspecialchars( $value ) );
                    break;
                // --- Numeric fields ---
                case 'min_upload':
                case 'max_upload':
                case 'delete_temp_hours':
                    $sanitized[$key] = ( !empty( $value ) ? absint( $value ) : '' );
                    break;
                // --- Comma-separated fields ---
                case 'supported_types':
                    $sanitized[$key] = sanitize_text_field( $value );
                    break;
                // --- Folder Name ---
                case 'upload_folder_name':
                    $sanitized[$key] = sanitize_title( $value );
                    break;
                // --- Boolean or checkbox ---
                case 'required':
                case 'login_required':
                case 'hide_name_field':
                case 'name_required':
                case 'hide_email_field':
                case 'email_required':
                    $sanitized[$key] = ( 'yes' === $value ? 'yes' : 'no' );
                    break;
                // --- Default case: plain text ---
                default:
                    $sanitized[$key] = sanitize_text_field( $value );
                    break;
            }
        }
        return $sanitized;
    }

    /**
     * Render Main Settings.
     *
     * @return void
     */
    public function render_settings() {
        if ( defined( 'EASYFUA_PLUGIN_DIR' ) && file_exists( EASYFUA_PLUGIN_DIR . 'admin/settings/main-settings.php' ) ) {
            include_once EASYFUA_PLUGIN_DIR . 'admin/settings/main-settings.php';
        }
    }

    /**
     * Render Error Messages settings.
     *
     * @return void
     */
    public function render_error_messages() {
        if ( defined( 'EASYFUA_PLUGIN_DIR' ) && file_exists( EASYFUA_PLUGIN_DIR . 'admin/settings/error-messages.php' ) ) {
            include_once EASYFUA_PLUGIN_DIR . 'admin/settings/error-messages.php';
        }
    }

    /**
     * Render Fields settings.
     *
     * @return void
     */
    public function render_admin_fields() {
        if ( defined( 'EASYFUA_PLUGIN_DIR' ) && file_exists( EASYFUA_PLUGIN_DIR . 'admin/settings/fields-settings.php' ) ) {
            include_once EASYFUA_PLUGIN_DIR . 'admin/settings/fields-settings.php';
        }
    }

    /**
     * Mail Settings.
     *
     * @return void
     */
    public function render_mail_settings() {
        if ( defined( 'EASYFUA_PLUGIN_DIR' ) && file_exists( EASYFUA_PLUGIN_DIR . 'admin/settings/mail-settings.php' ) ) {
            include_once EASYFUA_PLUGIN_DIR . 'admin/settings/mail-settings.php';
        }
    }

    /**
     * Add settings links in row actions
     * @param mixed $actions
     * @return string[]
     */
    public function plugin_settings( $actions ) {
        $links = array('<a href="' . esc_url( admin_url( 'admin.php?page=easyfua-settings' ) ) . '">' . esc_html__( 'Settings', 'easy-file-upload-approval' ) . '</a>');
        $actions = array_merge( $links, $actions );
        return $actions;
    }

}
