<?php

/**
 * Submissions List Table Class
 *
 * @package Giraforms
 */
// Exit if accessed directly.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Load WP_List_Table if not loaded
if ( !class_exists( 'WP_List_Table' ) ) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}
/**
 * Class GiraForms_Submissions_List
 */
class GiraForms_Submissions_List extends WP_List_Table {
    /**
     * Constructor.
     */
    public function __construct() {
        parent::__construct( array(
            'singular' => 'submission',
            'plural'   => 'submissions',
            'ajax'     => false,
        ) );
    }

    /**
     * Get columns.
     *
     * @return array
     */
    public function get_columns() {
        $columns = array(
            'cb'         => '<input type="checkbox" />',
            'id'         => __( 'ID', 'giraforms' ),
            'email'      => __( 'Email', 'giraforms' ),
            'form_name'  => __( 'Form Name', 'giraforms' ),
            'post'       => __( 'Post', 'giraforms' ),
            'status'     => __( 'Status', 'giraforms' ),
            'created_at' => __( 'Date', 'giraforms' ),
        );
        return $columns;
    }

    /**
     * Get sortable columns.
     *
     * @return array
     */
    protected function get_sortable_columns() {
        return array(
            'id'         => array('id', true),
            'form_name'  => array('form_name', false),
            'status'     => array('status', false),
            'created_at' => array('created_at', true),
        );
    }

    /**
     * Get bulk actions.
     *
     * @return array
     */
    protected function get_bulk_actions() {
        $actions = array(
            'delete' => __( 'Delete', 'giraforms' ),
            'read'   => __( 'Mark as Read', 'giraforms' ),
            'unread' => __( 'Mark as Unread', 'giraforms' ),
        );
        return $actions;
    }

    /**
     * Prepare items for display.
     */
    public function prepare_items() {
        $per_page = 20;
        $current_page = $this->get_pagenum();
        // Get query parameters
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- These are pagination/sorting parameters handled by WP_List_Table.
        $form_id = ( isset( $_GET['form_id'] ) ? sanitize_text_field( wp_unslash( $_GET['form_id'] ) ) : '' );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- These are pagination/sorting parameters handled by WP_List_Table.
        $status = ( isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '' );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- These are pagination/sorting parameters handled by WP_List_Table.
        $orderby = ( isset( $_GET['orderby'] ) ? sanitize_text_field( wp_unslash( $_GET['orderby'] ) ) : 'form_name,id' );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- These are pagination/sorting parameters handled by WP_List_Table.
        $order = ( isset( $_GET['order'] ) ? sanitize_text_field( wp_unslash( $_GET['order'] ) ) : 'ASC' );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Filter parameter for display only.
        $email_search = ( giraforms__fs()->can_use_premium_code__premium_only() && isset( $_GET['email_search'] ) ? sanitize_email( wp_unslash( $_GET['email_search'] ) ) : '' );
        // Build query args
        $args = array(
            'limit'        => $per_page,
            'offset'       => ($current_page - 1) * $per_page,
            'orderby'      => $orderby,
            'order'        => $order,
            'email_search' => $email_search,
        );
        if ( !empty( $form_id ) ) {
            $args['form_id'] = $form_id;
        }
        if ( !empty( $status ) ) {
            $args['status'] = $status;
        }
        // Get submissions
        $this->items = GiraForms_Submissions::get_submissions( $args );
        // Get total count
        $db = GiraForms_Database::instance();
        $total = $db->count_submissions( $args );
        // Set pagination
        $this->set_pagination_args( array(
            'total_items' => $total,
            'per_page'    => $per_page,
            'total_pages' => ceil( $total / $per_page ),
        ) );
        // Set columns
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable);
    }

    /**
     * Column default.
     *
     * @param array  $item Item data.
     * @param string $column_name Column name.
     * @return string
     */
    protected function column_default( $item, $column_name ) {
        switch ( $column_name ) {
            case 'id':
            case 'form_id':
            case 'form_name':
            case 'status':
            case 'created_at':
                return esc_html( $item[$column_name] );
            case 'post':
                return $this->format_post_column( $item['post_id'] );
            case 'email':
                return $this->format_email_column( $item['data'], $item['id'] );
            default:
                return '';
        }
    }

    /**
     * Column checkbox.
     *
     * @param array $item Item data.
     * @return string
     */
    protected function column_cb( $item ) {
        return sprintf( '<input type="checkbox" name="submission[]" value="%d" />', $item['id'] );
    }

    /**
     * Column ID.
     *
     * @param array $item Item data.
     * @return string
     */
    protected function column_id( $item ) {
        $view_url = admin_url( 'admin.php?page=giraforms-submissions&submission_id=' . $item['id'] );
        $delete_url = wp_nonce_url( admin_url( 'admin.php?page=giraforms-submissions&action=delete&submission_id=' . $item['id'] ), 'delete_submission_' . $item['id'] );
        $actions = array(
            'view'   => sprintf( '<a href="%s">%s</a>', esc_url( $view_url ), __( 'View', 'giraforms' ) ),
            'delete' => sprintf(
                '<a href="%s" onclick="return confirm(\'%s\')">%s</a>',
                esc_url( $delete_url ),
                esc_js( __( 'Are you sure?', 'giraforms' ) ),
                __( 'Delete', 'giraforms' )
            ),
        );
        return sprintf(
            '<strong><a href="%s">#%d</a></strong> %s',
            esc_url( $view_url ),
            $item['id'],
            $this->row_actions( $actions )
        );
    }

    /**
     * Column status.
     *
     * @param array $item Item data.
     * @return string
     */
    protected function column_status( $item ) {
        $status_labels = array(
            'unread'   => __( 'Unread', 'giraforms' ),
            'read'     => __( 'Read', 'giraforms' ),
            'archived' => __( 'Archived', 'giraforms' ),
            'spam'     => __( 'Spam', 'giraforms' ),
        );
        $status = ( isset( $status_labels[$item['status']] ) ? $status_labels[$item['status']] : $item['status'] );
        $class = 'status-' . $item['status'];
        return sprintf( '<span class="giraforms-status-badge %s">%s</span>', esc_attr( $class ), esc_html( $status ) );
    }

    /**
     * Column payment.
     *
     * @param array $item Item data.
     * @return string
     */
    protected function column_payment( $item ) {
        if ( empty( $item['data'] ) || !isset( $item['data']['_payment_status'] ) ) {
            return '';
        }
        $payment_status = $item['data']['_payment_status'];
        $status_colors = array(
            'paid'     => '#00a32a',
            'failed'   => '#d63638',
            'refunded' => '#dba617',
            'disputed' => '#d63638',
            'unknown'  => '#757575',
        );
        $color = ( isset( $status_colors[$payment_status] ) ? $status_colors[$payment_status] : '#757575' );
        return sprintf( '<span style="display: inline-block; padding: 2px 8px; border-radius: 10px; font-size: 12px; font-weight: 500; color: #fff; background: %s;">%s</span>', esc_attr( $color ), esc_html( ucfirst( $payment_status ) ) );
    }

    /**
     * Format email column.
     *
     * @param array $data Submission data.
     * @param int   $submission_id Submission ID.
     * @return string
     */
    private function format_email_column( $data, $submission_id ) {
        if ( empty( $data ) ) {
            return '';
        }
        // Look for email field in the data
        foreach ( $data as $key => $value ) {
            // Skip internal fields
            if ( strpos( $key, '_' ) === 0 || strpos( $key, 'giraforms_' ) === 0 ) {
                continue;
            }
            // Check if this is an email field (key contains 'email' or value looks like an email)
            if ( strpos( $key, 'email' ) !== false || is_string( $value ) && filter_var( $value, FILTER_VALIDATE_EMAIL ) ) {
                $view_url = admin_url( 'admin.php?page=giraforms-submissions&submission_id=' . $submission_id );
                return sprintf( '<a href="%s">%s</a>', esc_url( $view_url ), esc_html( $value ) );
            }
        }
        // No email found
        return '';
    }

    /**
     * Format post column.
     *
     * @param int $post_id Post ID.
     * @return string
     */
    private function format_post_column( $post_id ) {
        if ( !$post_id ) {
            return '—';
        }
        $post = get_post( $post_id );
        if ( !$post ) {
            // translators: %d: post ID
            return sprintf( __( 'Post #%d (deleted)', 'giraforms' ), $post_id );
        }
        $post_title = ( $post->post_title ? $post->post_title : __( '(no title)', 'giraforms' ) );
        $edit_url = get_edit_post_link( $post_id );
        if ( $edit_url ) {
            return sprintf(
                '<a href="%s">%s</a> <small style="color: #666;">(#%d)</small>',
                esc_url( $edit_url ),
                esc_html( $post_title ),
                $post_id
            );
        }
        return sprintf( '%s <small style="color: #666;">(#%d)</small>', esc_html( $post_title ), $post_id );
    }

    /**
     * Display if no items.
     */
    public function no_items() {
        esc_html_e( 'No submissions found.', 'giraforms' );
    }

    /**
     * Display extra navigation (filters).
     *
     * @param string $which Top or bottom.
     */
    protected function extra_tablenav( $which ) {
        if ( 'top' !== $which ) {
            return;
        }
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- These are filter parameters for display only.
        $current_status = ( isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '' );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- These are filter parameters for display only.
        $form_id = ( isset( $_GET['form_id'] ) ? sanitize_text_field( wp_unslash( $_GET['form_id'] ) ) : '' );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Filter parameter for display only.
        $email_search = ( giraforms__fs()->can_use_premium_code__premium_only() && isset( $_GET['email_search'] ) ? sanitize_email( wp_unslash( $_GET['email_search'] ) ) : '' );
        ?>
		<div class="alignleft actions">
			<select name="status" id="filter-by-status">
				<option value=""><?php 
        esc_html_e( 'All Statuses', 'giraforms' );
        ?></option>
				<option value="unread" <?php 
        selected( $current_status, 'unread' );
        ?>><?php 
        esc_html_e( 'Unread', 'giraforms' );
        ?></option>
				<option value="read" <?php 
        selected( $current_status, 'read' );
        ?>><?php 
        esc_html_e( 'Read', 'giraforms' );
        ?></option>
				<?php 
        ?>
			</select>
			<?php 
        ?>
			<?php 
        submit_button(
            __( 'Filter', 'giraforms' ),
            '',
            'filter_action',
            false
        );
        ?>
			<?php 
        if ( !empty( $current_status ) || !empty( $email_search ) ) {
            ?>
				<a href="<?php 
            echo esc_url( admin_url( 'admin.php?page=giraforms-submissions' . (( $form_id ? '&form_id=' . urlencode( $form_id ) : '' )) ) );
            ?>" class="button">
					<?php 
            esc_html_e( 'Reset', 'giraforms' );
            ?>
				</a>
			<?php 
        }
        ?>
		</div>
		<?php 
    }

}
