<?php

/**
 * Admin - File submission table
 *
 * This class render list table and columns for file submissions
 *
 * @package EASYFUA
 */
// Prevent direct access.
defined( 'ABSPATH' ) || exit;
if ( !class_exists( 'EASYFUA_Submissions' ) ) {
    /**
     * File Submission list table class.
     */
    class EASYFUA_Submissions extends WP_List_Table {
        /**
         * Admin base url of the plugin.
         *
         * @var string $base_url
         */
        private $base_url;

        /**
         * Default date format.
         *
         * @var string $date_format.
         */
        private $date_format;

        /**
         * Constant slug of the plugin.
         *
         * @var string EASYFUA_SLUG
         */
        const EASYFUA_SLUG = 'easyfua-main-menu';

        /**
         * Submission list table constructor.
         */
        public function __construct() {
            parent::__construct( array(
                'singular' => 'submission',
                'plural'   => 'submissions',
                'ajax'     => false,
            ) );
            // Build base url.
            $this->base_url = add_query_arg( array(
                'page' => self::EASYFUA_SLUG,
            ), admin_url( 'admin.php' ) );
            // Date format from WordPress.
            $this->date_format = get_option( 'date_format' );
            // Stripped `result` query args from url.
            $_SERVER['REQUEST_URI'] = remove_query_arg( 'result' );
        }

        /**
         * Display table nav.
         *
         * @return void
         */
        protected function display_tablenav( $which ) {
            if ( 'top' === $which ) {
                wp_nonce_field( 'easyfua-nonce' );
            }
            ?>
			<div class="tablenav <?php 
            echo esc_attr( $which );
            ?>">
				<?php 
            if ( $this->has_items() ) {
                ?>
					<div class="alignleft actions bulkactions">
						<?php 
                $this->bulk_actions( $which );
                ?>
					</div>
				<?php 
            }
            ?>
				<?php 
            $this->extra_tablenav( $which );
            $this->pagination( $which );
            ?>
				<br class="clear" />
			</div>
			<?php 
        }

        /**
         * Display admin heading for submission.
         *
         * @return void
         */
        public function heading() {
            $heading = esc_html__( 'Easy File Upload Approval - File Submissions', 'easy-file-upload-approval' );
            printf( '<h1>%s</h1>', wp_kses_post( $heading ) );
        }

        /**
         * Preparation for items data.
         *
         * @return void
         */
        public function prepare_items() {
            global $wpdb;
            // Verify nonce.
            if ( isset( $_REQUEST['_wpnonce'] ) ) {
                check_admin_referer( 'easyfua-nonce' );
            }
            $columns = $this->get_columns();
            $hidden = array();
            $sortable = $this->get_sortable_columns();
            $per_page = 20;
            // Column headers.
            $this->_column_headers = array($columns, $hidden, $sortable);
            // Submission Table.
            $submission_table = 'easyfua_submissions';
            // Get submission data through function.
            $submission = easyfua_admin_query( $submission_table, array(
                'per_page'     => $per_page,
                'current_page' => $this->get_pagenum(),
                'status'       => ( isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '' ),
                's'            => ( isset( $_GET['s'] ) && !empty( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '' ),
                'has_filename' => false,
                'orderby'      => ( isset( $_GET['orderby'] ) ? sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) : 'id' ),
                'order'        => ( isset( $_GET['order'] ) ? sanitize_text_field( wp_unslash( $_GET['order'] ) ) : 'DESC' ),
            ) );
            // Assigning items to $items variable.
            if ( isset( $submission['items'] ) ) {
                $this->items = $submission['items'];
            }
            // Getting total items.
            $total_items = ( isset( $submission['total_items'] ) ? (int) $submission['total_items'] : 0 );
            // Set pagination args.
            $this->set_pagination_args( array(
                'total_items' => $total_items,
                'per_page'    => $per_page,
                'total_pages' => ceil( $total_items / $per_page ),
            ) );
        }

        /**
         * Default table columns.
         *
         * @return array
         */
        public function get_columns() {
            $columns = array(
                'cb'           => '<input type="checkbox" />',
                'id'           => esc_html__( 'Submission ID', 'easy-file-upload-approval' ),
                'submitted_by' => esc_html__( 'Submitted By', 'easy-file-upload-approval' ),
                'files'        => esc_html__( 'Files', 'easy-file-upload-approval' ),
                'total_files'  => esc_html__( 'Total Files', 'easy-file-upload-approval' ),
                'status'       => esc_html__( 'Status', 'easy-file-upload-approval' ),
                'date'         => esc_html__( 'Submitted At', 'easy-file-upload-approval' ),
            );
            return $columns;
        }

        /**
         * Default sub nav links/items.
         *
         * @return array
         */
        public function get_views() {
            // verify nonce
            if ( isset( $_REQUEST['_wpnonce'] ) ) {
                check_admin_referer( 'easyfua-nonce' );
            }
            $status = ( isset( $_REQUEST['status'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['status'] ) ) : 'all' );
            $file_manager = new EASYFUA_File_Manager();
            $counts = array(
                'all'      => $file_manager->get_submission_status(),
                'pending'  => $file_manager->get_submission_status( 'pending' ),
                'approved' => $file_manager->get_submission_status( 'approved' ),
                'rejected' => $file_manager->get_submission_status( 'rejected' ),
                'partial'  => $file_manager->get_submission_status( 'partial' ),
            );
            $views = array();
            // Loop count items.
            foreach ( $counts as $key => $count ) {
                $class = ( $status === $key ? 'class="current"' : '' );
                $url = add_query_arg( 'status', $key, $this->base_url );
                $views[$key] = sprintf(
                    '<li><a href="%1$s" %2$s>%3$s <span class="count">(%4$d)</span></a></li>',
                    esc_url( $url ),
                    esc_attr( $class ),
                    ucfirst( $key ),
                    $count
                );
            }
            return $views;
        }

        /**
         * Table Values for column.
         *
         * @param mixed $item        File item data.
         * @param mixed $column_name Table column name.
         * @return int|string|void
         */
        public function column_default( $item, $column_name ) {
            $submission_id = ( isset( $item['id'] ) ? absint( $item['id'] ) : null );
            switch ( $column_name ) {
                case 'id':
                    $status = ( isset( $item['status'] ) ? $item['status'] : null );
                    $action_links = array();
                    // File Submission link.
                    $file_link = add_query_arg( array(
                        'sub'           => 'view-files',
                        'submission_id' => $submission_id,
                        '_wpnonce'      => wp_create_nonce( 'easyfua-nonce' ),
                    ), $this->base_url );
                    // Show approve if the file is still pending, rejected.
                    if ( 'approved' !== $status ) {
                        $action_links[] = sprintf( '<a href="%s">%s</a>', esc_url( $file_link ), esc_html( _n(
                            'Review File',
                            'Review Files',
                            $item['total_files'],
                            'easy-file-upload-approval'
                        ) ) );
                    } else {
                        $action_links[] = sprintf( '<a href="%s">%s</a>', esc_url( $file_link ), esc_html( _n(
                            'View File',
                            'View Files',
                            $item['total_files'],
                            'easy-file-upload-approval'
                        ) ) );
                    }
                    // Always show Delete action.
                    $delete_url = add_query_arg( array(
                        'action'        => 'delete',
                        'submission_id' => $submission_id,
                    ), $this->base_url );
                    $action_links[] = sprintf( '<a href="%s" class="delete easyfua-action-delete" data-title="submission" style="color:#d63638;">%s</a>', esc_url( wp_nonce_url( $delete_url, 'easyfua-nonce' ) ), esc_html__( 'Delete', 'easy-file-upload-approval' ) );
                    // Concat actions.
                    $actions = sprintf( '<div class="row-actions">%s</div>', implode( ' | ', $action_links ) );
                    return sprintf(
                        // translators: 1: Submission URL, 2: Submission ID, 3: Additional message or status text.
                        __( '<a href="%1$s">Submission #%2$d</a> %3$s', 'easy-file-upload-approval' ),
                        esc_url( $file_link ),
                        $submission_id,
                        $actions
                    );
                case 'submitted_by':
                    $user_id = (int) $item['user_id'];
                    $user = ( $user_id > 0 ? get_userdata( $user_id ) : json_decode( $item['form_data'], true ) );
                    if ( !is_array( $user ) ) {
                        return sprintf(
                            '<a href="%s">%s</a><small>%s</small>',
                            esc_url( admin_url( 'user-edit.php?user_id=' . absint( $user->ID ) ) ),
                            esc_html( ucwords( $user->first_name . ' ' . $user->last_name ) ),
                            esc_html( $user->user_email )
                        );
                    } else {
                        $name = ( isset( $user['name'] ) ? ucwords( $user['name'] ) : 'Guest' );
                        $email = ( isset( $user['email'] ) ? $user['email'] : '' );
                        return sprintf( '%s <small>%s</small>', esc_html( $name ), esc_html( $email ) );
                    }
                case 'total_files':
                    return intval( $item['total_files'] );
                case 'actions':
                    // Premium only.
                    if ( !easyfua_is_premium() ) {
                        return;
                    }
                    $download_url = add_query_arg( array(
                        'action'        => 'download',
                        'submission_id' => $submission_id,
                    ), $this->base_url );
                    return sprintf( '<a href="%s" class="button button-small">%s</a>', esc_url( wp_nonce_url( $download_url, 'easyfua-nonce' ) ), esc_html( _n(
                        'Download File',
                        'Download Files',
                        $item['total_files'],
                        'easy-file-upload-approval'
                    ) ) );
                case 'date':
                    return esc_html( easyfua_date( $item['submitted_at'] ) );
                default:
                    return '';
            }
        }

        /**
         * Add date and id for sortable columns.
         *
         * @return array
         */
        protected function get_sortable_columns() {
            return array(
                'date' => array('submitted_at', true),
                'id'   => array('id', true),
            );
        }

        /**
         * Add checkbox column for submission ID.
         *
         * @param mixed $item File item data.
         * @return void
         */
        public function column_cb( $item ) {
            printf( '<input type="checkbox" name="submission_id[]" value="%d" />', absint( $item['id'] ) );
        }

        /**
         * Specific column for files.
         *
         * @param mixed $item File item data.
         * @return void
         */
        public function column_files( $item ) {
            // File Manager.
            $file_manager = new EASYFUA_File_Manager();
            $files = $file_manager->get_submission_files( $item['id'] );
            if ( !empty( $files ) ) {
                $total_files = count( $files );
                $no_to_show = 2;
                // no of files to show (initial).
                $more_link = add_query_arg( array(
                    'sub'           => 'view-files',
                    'submission_id' => absint( $item['id'] ),
                    '_wpnonce'      => wp_create_nonce( 'easyfua-nonce' ),
                ), $this->base_url );
                // Initial files to display.
                $display_files = array_slice( $files, 0, $no_to_show );
                foreach ( $display_files as $i => $file ) {
                    $name = ( isset( $file['file_name'] ) ? pathinfo( $file['file_name'] ) : '' );
                    if ( $name ) {
                        $last_char = 3;
                        // show last 3 character of filename.
                        $char_limit = (( 0 === $i || 2 === count( $files ) ? 28 : 18 )) - $last_char;
                        // @note pro: 30 and 15 (if 'actions' column is added ).
                        $filename = $name['filename'];
                        // Trim filename.
                        if ( strlen( $filename ) > $char_limit ) {
                            $filename = substr( $filename, 0, $char_limit ) . '...' . substr( $filename, -$last_char );
                        }
                        // Show (+2 more).
                        $total_text_files = '';
                        if ( $total_files > $no_to_show ) {
                            $total_text_files = sprintf(
                                '<a href="%s">[+%s %s]</a>',
                                esc_url( $more_link ),
                                absint( $total_files - $no_to_show ),
                                __( 'more', 'easy-file-upload-approval' )
                            );
                        }
                        // Display filename and extension.
                        printf(
                            '<span class="%s">%s %s</span>',
                            esc_attr( 'easyfua-file-name-' . absint( $i ) ),
                            esc_html( $filename . '.' . $name['extension'] ),
                            ( 0 !== $i ? wp_kses_post( $total_text_files ) : '' )
                        );
                    }
                }
            }
        }

        /**
         * Specific column for status.
         *
         * @param mixed $item File item data.
         * @return string
         */
        public function column_status( $item ) {
            $status = $item['status'];
            switch ( $status ) {
                case 'approved':
                    $label = esc_html__( 'Approved', 'easy-file-upload-approval' );
                    break;
                case 'partial':
                    $label = esc_html__( 'Partial', 'easy-file-upload-approval' );
                    break;
                case 'rejected':
                    $label = esc_html__( 'Rejected', 'easy-file-upload-approval' );
                    break;
                case 'deleted':
                    $label = esc_html__( 'Deleted', 'easy-file-upload-approval' );
                    break;
                default:
                    $label = esc_html__( 'Pending', 'easy-file-upload-approval' );
            }
            return sprintf( '<span class="%s">%s</span>', 'easyfua-status easyfua-status-' . esc_attr( $status ), esc_html( $label ) );
        }

        /**
         * Get All bulk actions.
         *
         * @return array{delete: string}
         */
        protected function get_bulk_actions() {
            return array(
                'delete' => esc_html__( 'Delete', 'easy-file-upload-approval' ),
            );
        }

        /**
         * Handle or process all bulk actions.
         *
         * @return void
         */
        public function process_bulk_action() {
            // No action bail early.
            $action = $this->current_action();
            if ( !$action ) {
                return;
            }
            // Verify nonce.
            check_admin_referer( 'easyfua-nonce' );
            // Submision ID Variable.
            $ids = array();
            if ( !empty( $_REQUEST['submission_id'] ) ) {
                $ids = array_map( 'absint', (array) wp_unslash( $_REQUEST['submission_id'] ) );
            }
            $file = new EASYFUA_File_Manager();
            $result = '';
            // Remove from query string.
            $_SERVER['REQUEST_URI'] = remove_query_arg( array('action', 'id') );
            // Bail early.
            if ( empty( $ids ) ) {
                return;
            }
            switch ( $action ) {
                case 'delete':
                    foreach ( $ids as $submission_id ) {
                        $submission_id = absint( $submission_id );
                        if ( $submission_id > 0 ) {
                            $file->delete_submission( $submission_id );
                        }
                    }
                    $result = 'delete-multi';
                    break;
                case 'download':
                    if ( easyfua_is_premium() ) {
                        $files = $file->get_submission_files( current( $ids ) );
                        if ( $files && is_array( $files ) ) {
                            $file_ids = wp_list_pluck( $files, 'id' );
                            $file->download_files( $file_ids );
                        }
                    }
                    break;
            }
            // Redirect and add result query to display confirmation message.
            if ( isset( $result ) ) {
                wp_safe_redirect( esc_url_raw( add_query_arg( 'result', $result ) ) );
            }
        }

    }

}