<?php

/**
 * Admin - Viewing Files
 *
 * This class render list table of all the files belong to submission id.
 *
 * @package EASYFUA
 */
// Prevent direct access.
defined( 'ABSPATH' ) || exit;
if ( !class_exists( 'EASYFUA_Submissions_Files' ) ) {
    /**
     * File Submission Files list table.
     */
    class EASYFUA_Submissions_Files extends WP_List_Table {
        /**
         * Admin base url of the plugin.
         *
         * @var string $base_url
         */
        private $base_url;

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

        /**
         * File list table constructor.
         */
        public function __construct() {
            // Check for nonce.
            check_admin_referer( 'easyfua-nonce' );
            parent::__construct( array(
                'singular' => 'submission-file',
                'plural'   => 'submission-files',
                'ajax'     => false,
            ) );
            // Build base url.
            $this->base_url = add_query_arg( array(
                'page'          => self::EASYFUA_SLUG,
                'sub'           => ( isset( $_GET['sub'] ) ? sanitize_text_field( wp_unslash( $_GET['sub'] ) ) : '' ),
                'submission_id' => ( isset( $_GET['submission_id'] ) ? absint( $_GET['submission_id'] ) : '' ),
            ), admin_url( 'admin.php' ) );
            // 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 files page view.
         *
         * @return void
         */
        public function heading() {
            // Check for nonce.
            check_admin_referer( 'easyfua-nonce' );
            $id = ( isset( $_GET['submission_id'] ) ? absint( wp_unslash( $_GET['submission_id'] ) ) : null );
            $heading = sprintf( 
                // translators: %d will be replaced with submission ID.
                esc_html__( 'File Submission #%d - Files', 'easy-file-upload-approval' ),
                absint( $id )
             );
            printf( '<h1>%s</h1>', wp_kses_post( $heading ) );
            ?>
			<div class="easyfua-submission-meta">
				<?php 
            $file_manager = new EASYFUA_File_Manager();
            $submission = $file_manager->get_submission( $id );
            // Get submission name.
            if ( $submission->user_id ) {
                $user = get_userdata( $submission->user_id );
                $name = $user->first_name . ' ' . $user->last_name;
            } elseif ( !empty( $submission->form_data ) ) {
                $user = json_decode( $submission->form_data, true );
                $name = ( isset( $user['name'] ) ? $user['name'] : 'Guest' );
            }
            echo '<div class="easyfua-submision-data">';
            // Submitted by.
            if ( $name ) {
                printf( '<p><strong>%s:</strong> %s</p>', esc_html__( 'Submitted By', 'easy-file-upload-approval' ), esc_html( ucwords( $name ) ) );
            }
            // Submitted At.
            if ( !empty( $submission->submitted_at ) ) {
                printf( '<p><strong>%s:</strong> %s</p>', esc_html__( 'Submission Date', 'easy-file-upload-approval' ), esc_html( easyfua_date( $submission->submitted_at ) ) );
            }
            // Updated At.
            if ( !empty( $submission->updated_at ) ) {
                printf( '<p><strong>%s:</strong> %s</p>', esc_html__( 'Updated At', 'easy-file-upload-approval' ), esc_html( easyfua_date( $submission->updated_at ) ) );
            }
            echo '</div>';
            // Show only if user already notified after the reviewed.
            if ( 1 === (int) $submission->is_notified ) {
                printf(
                    '
							<div class="easyfua-notify-user">
								<span>%s</span>
								<a href="%s" class="button-primary">%s</a>
							</div>',
                    esc_html__( 'Changes made — notify uploader?', 'easy-file-upload-approval' ),
                    esc_url( wp_nonce_url( add_query_arg( array(
                        'action'        => 'notify_user',
                        'submission_id' => $id,
                    ), $this->base_url ), 'easyfua-nonce' ) ),
                    esc_html__( 'Send Email', 'easy-file-upload-approval' )
                );
            }
            ?>
			</div>
			<?php 
        }

        /**
         * 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;
            // Files Table.
            $files_table = 'easyfua_files';
            // Get files data through function.
            $files_data = easyfua_admin_query( $files_table, array(
                'per_page'      => $per_page,
                'current_page'  => $this->get_pagenum(),
                's'             => ( isset( $_GET['s'] ) && !empty( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '' ),
                'has_filename'  => true,
                'submission_id' => ( isset( $_GET['submission_id'] ) ? absint( $_GET['submission_id'] ) : null ),
                '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( $files_data['items'] ) ) {
                $this->items = $files_data['items'];
            }
            // Getting total items.
            $total_items = ( isset( $files_data['total_items'] ) ? (int) $files_data['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() {
            return array(
                'cb'           => '<input type="checkbox" />',
                'id'           => esc_html__( 'File ID', 'easy-file-upload-approval' ),
                'file_name'    => esc_html__( 'File Name', 'easy-file-upload-approval' ),
                'type'         => esc_html__( 'Type', 'easy-file-upload-approval' ),
                'status'       => esc_html__( 'Status', 'easy-file-upload-approval' ),
                'approved_by'  => esc_html__( 'Reviewed By', 'easy-file-upload-approval' ),
                'note'         => esc_html__( 'Note', 'easy-file-upload-approval' ),
                'submitted_at' => esc_html__( 'Date Uploaded', 'easy-file-upload-approval' ),
                'actions'      => esc_html__( 'Actions', 'easy-file-upload-approval' ),
            );
        }

        /**
         * Table Values for column.
         *
         * @param mixed $item File item data.
         * @param mixed $column_name Specific key/name of the table column.
         * @return int|string
         */
        public function column_default( $item, $column_name ) {
            switch ( $column_name ) {
                case 'id':
                    $status = ( isset( $item['file_status'] ) ? $item['file_status'] : null );
                    $file_id = ( isset( $item['id'] ) ? absint( $item['id'] ) : null );
                    $action_links = array();
                    // Show approve if the file is still pending, rejected.
                    if ( 'approved' !== $status ) {
                        $approve_url = add_query_arg( array(
                            'action' => 'approve',
                            'id'     => $file_id,
                        ), $this->base_url );
                        $can_approve = apply_filters( 'easyfua_can_approve', true );
                        $approve_label = __( 'Approve', 'easy-file-upload-approval' );
                        if ( $can_approve ) {
                            $action_links[] = sprintf( '<a href="%s">%s</a>', esc_url( wp_nonce_url( $approve_url, 'easyfua-nonce' ) ), esc_html( $approve_label ) );
                        } else {
                            $action_links[] = sprintf(
                                '<a href="%s" class="%s">%s</a>',
                                'javascript:void(0)',
                                'easyfua-text-disabled',
                                esc_html( $approve_label )
                            );
                        }
                    }
                    // Show reject if file is pending or rejected.
                    if ( 'rejected' !== $status ) {
                        $reject_url = add_query_arg( array(
                            'action' => 'reject',
                            'id'     => $file_id,
                        ), $this->base_url );
                        $action_links[] = sprintf(
                            '<a class="easyfua-reject-btn" data-id="%s" data-name="%s" href="%s">%s</a>',
                            esc_attr( $file_id ),
                            esc_attr( $item['file_name'] ),
                            esc_url( wp_nonce_url( $reject_url, 'easyfua-nonce' ) ),
                            esc_html__( 'Reject', 'easy-file-upload-approval' )
                        );
                    }
                    // Always show Delete action.
                    $delete_url = add_query_arg( array(
                        'action' => 'delete',
                        'id'     => $file_id,
                    ), $this->base_url );
                    $action_links[] = sprintf( '<a href="%s" class="delete easyfua-action-delete" data-title="file" 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: %2$s will be replaced with file ID.
                        esc_html__( 'File #%1$d %2$s', 'easy-file-upload-approval' ),
                        $file_id,
                        $actions
                     );
                case 'file_name':
                    if ( isset( $item['file_name'] ) ) {
                        // File Size.
                        $size = sprintf( '<small class="easyfua-file-size">%s</small>', esc_html( easyfua_format_file_size( $item['file_size'] ) ) );
                        // Return filename + extension + file size.
                        return sprintf( '<span>%s</span> %s', $item['file_name'], $size );
                    }
                    break;
                case 'type':
                    if ( isset( $item['file_type'] ) ) {
                        return esc_html( $item['file_type'] );
                    }
                    break;
                case 'size':
                    if ( isset( $item['file_size'] ) ) {
                        return esc_html( easyfua_format_file_size( $item['file_size'] ) );
                    }
                    break;
                case 'actions':
                    $view_url = ( isset( $item['file_url'] ) ? $item['file_url'] : null );
                    return sprintf( '<a href="%s" target="_blank" class="button button-small">%s</a>', esc_url( $view_url ), esc_html__( 'Review File', 'easy-file-upload-approval' ) );
                case 'note':
                    return sprintf( '<small>%s</small>', wp_kses_post( $item['admin_note'] ) );
                case 'submitted_at':
                    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(
                'submitted_at' => array('submitted_at', true),
                'id'           => array('id', true),
            );
        }

        /**
         * Specific column for status
         *
         * @param mixed $item File item data.
         * @return string
         */
        public function column_status( $item ) {
            $status = ( isset( $item['file_status'] ) ? $item['file_status'] : null );
            return sprintf( '<span class="easyfua-status easyfua-status-%s">%s</span>', esc_attr( $status ), ucfirst( $status ) );
        }

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

        /**
         * Specific column for date
         *
         * @param mixed $item File Item Data.
         * @return string
         */
        public function column_date( $item ) {
            return esc_html( get_the_date( '', $item ) );
        }

        /**
         * Specific column for approved by.
         *
         * @param mixed $item File item Data.
         * @return void|string
         */
        public function column_approved_by( $item ) {
            $approve_by = ( isset( $item['approved_by'] ) ? (int) $item['approved_by'] : null );
            if ( $approve_by ) {
                $user = get_userdata( $approve_by );
                return sprintf( '<a href="%s">%s</a>', esc_url( admin_url( 'user-edit.php?user_id=' . absint( $approve_by ) ) ), esc_html( ucwords( $user->user_firstname . ' ' . $user->user_lastname ) ) );
            }
        }

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

        /**
         * Handle or process all bulk actions.
         *
         * @return void
         */
        public function process_bulk_action() {
            // Get current action.
            $action = $this->current_action();
            if ( !$action ) {
                return;
            }
            // Verify nonce.
            check_admin_referer( 'easyfua-nonce' );
            // File ids.
            $ids = array();
            if ( !empty( $_REQUEST['id'] ) ) {
                $ids = array_map( 'absint', (array) wp_unslash( $_REQUEST['id'] ) );
            }
            // Variables.
            $submission_id = ( isset( $_GET['submission_id'] ) ? absint( $_GET['submission_id'] ) : '' );
            $file_manager = new EASYFUA_File_Manager($submission_id);
            $result = '';
            // Remove query string from uri.
            $_SERVER['REQUEST_URI'] = remove_query_arg( array('action', 'id') );
            // Bail early except for notify user since, no file `id` pass to query string only `submission_id`.
            if ( empty( $ids ) && 'notify_user' !== $action ) {
                return;
            }
            // Get method from action. ie: $action_map['approve'].
            switch ( $action ) {
                case 'notify_user':
                    $email = new EASYFUA_Email_Manager();
                    $email->notified_user( $submission_id );
                    $result = 'notified-user';
                    break;
                case 'download':
                    $file_manager->download_files( $ids );
                    break;
                case 'approve':
                    foreach ( $ids as $id ) {
                        $file_manager->approve_file( $id );
                    }
                    $result = ( count( $ids ) === 1 ? 'approved' : 'approved-multi' );
                    break;
                case 'reject':
                    foreach ( $ids as $id ) {
                        $file_manager->reject_file( $id, '' );
                        // 2nd param is admin_note.
                    }
                    $result = ( count( $ids ) === 1 ? 'rejected' : 'rejected-multi' );
                    break;
                case 'delete':
                    foreach ( $ids as $id ) {
                        $file_manager->delete_file( $id );
                    }
                    $result = ( count( $ids ) === 1 ? 'deleted' : 'deleted-multi' );
                    break;
            }
            if ( isset( $result ) ) {
                wp_safe_redirect( esc_url_raw( add_query_arg( 'result', $result ) ) );
                exit;
            }
        }

    }

}