<?php
/**
 * SiteStaffr Admin Calls List View
 *
 * Displays the full list of calls using WP_List_Table.
 *
 * @link       https://github.com/sitestaffr/sitestaffr-plugin
 * @since      1.0.0
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/views
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
    die;
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

// Include the calls list table class if not already loaded
require_once SITESTAFFR_PLUGIN_DIR . 'admin/class-sitestaffr-calls-list-table.php';

// View parameter is read-only routing (which tab to show), validated against allowlist below.
$current_view = isset( $_GET['view'] ) ? sanitize_key( wp_unslash( $_GET['view'] ) ) : 'all';
// phpcs:disable WordPress.Security.NonceVerification.Recommended,WordPress.Security.NonceVerification.Missing -- search params read below.
$is_trash_view = ( 'trash' === $current_view );
$is_banned_view = ( 'banned' === $current_view );

// Create the appropriate list table instance
if ( $is_trash_view ) {
    $calls_list_table = new SiteStaffr_Calls_List_Table( array( 'trash' => true ) );
} else {
    $calls_list_table = new SiteStaffr_Calls_List_Table();
}
$calls_list_table->prepare_items();

// Get trash count for tab badge
$trash_count = SiteStaffr_Call_Manager::get_trash_count();

// Get settings for business name
$settings = get_option( 'sitestaffr_settings', array() );
$business_name = isset( $settings['business_name'] ) ? stripslashes( $settings['business_name'] ) : '';

// Build tab URLs (server-side) with nonce verification.
$base_url = admin_url( 'admin.php?page=sitestaffr' );
$all_url = wp_nonce_url( add_query_arg( 'view', 'all', $base_url ), 'sitestaffr_view' );
$trash_url = wp_nonce_url( add_query_arg( 'view', 'trash', $base_url ), 'sitestaffr_view' );
$banned_url = wp_nonce_url( add_query_arg( 'view', 'banned', $base_url ), 'sitestaffr_view' );
?>

<div class="wrap sitestaffr-calls-list-page">
    <div class="sitestaffr-calls-page-wrapper">
        <?php
        $sitestaffr_page_title = __( 'Conversations', 'sitestaffr' );
        include SITESTAFFR_PLUGIN_DIR . 'admin/partials/sitestaffr-header.php';
        ?>

    <?php
    // Display admin notices from nonce-verified redirects.
    if ( isset( $_GET['message'], $_GET['_wpnonce'] )
        && wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), 'sitestaffr_admin_notice' )
    ) {
        $message = sanitize_key( wp_unslash( $_GET['message'] ) );
        $notice_messages = array(
            'marked_read'              => __( 'Conversation marked as read.', 'sitestaffr' ),
            'marked_unread'            => __( 'Conversation marked as unread.', 'sitestaffr' ),
            'deleted'                  => __( 'Conversation deleted.', 'sitestaffr' ),
            'trashed'                  => __( 'Conversation moved to trash.', 'sitestaffr' ),
            'restored'                 => __( 'Conversation restored.', 'sitestaffr' ),
            'permanently_deleted'      => __( 'Conversation permanently deleted.', 'sitestaffr' ),
            'trash_emptied'            => __( 'Trash emptied.', 'sitestaffr' ),
            'bulk_marked_read'         => __( 'Selected conversations marked as read.', 'sitestaffr' ),
            'bulk_marked_unread'       => __( 'Selected conversations marked as unread.', 'sitestaffr' ),
            'bulk_deleted'             => __( 'Selected conversations deleted.', 'sitestaffr' ),
            'bulk_trashed'             => __( 'Selected conversations moved to trash.', 'sitestaffr' ),
            'bulk_restored'            => __( 'Selected conversations restored.', 'sitestaffr' ),
            'bulk_permanently_deleted' => __( 'Selected conversations permanently deleted.', 'sitestaffr' ),
        );

        if ( isset( $notice_messages[ $message ] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $notice_messages[ $message ] ) . '</p></div>';
        }
    }
    ?>

    <?php
    // Get current search value for the tab-inline search form
    $current_search = isset( $_POST['s'] ) ? sanitize_text_field( wp_unslash( $_POST['s'] ) ) :
                     ( isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '' );
    // phpcs:enable WordPress.Security.NonceVerification.Recommended,WordPress.Security.NonceVerification.Missing
    ?>

    <!-- Tab Navigation with inline search -->
    <nav class="nav-tab-wrapper sitestaffr-tabs-with-search">
        <div class="sitestaffr-tab-links">
            <a href="<?php echo esc_url( $all_url ); ?>" class="nav-tab <?php echo ( ! $is_trash_view && ! $is_banned_view ) ? 'nav-tab-active' : ''; ?>" id="tab-all-calls">
                <?php echo esc_html__( 'All Conversations', 'sitestaffr' ); ?>
            </a>
            <a href="<?php echo esc_url( $trash_url ); ?>" class="nav-tab <?php echo $is_trash_view ? 'nav-tab-active' : ''; ?>" id="tab-trash">
                <?php echo esc_html__( 'Trash', 'sitestaffr' ); ?>
                <?php if ( $trash_count > 0 ) : ?>
                    <span class="count">(<?php echo esc_html( $trash_count ); ?>)</span>
                <?php endif; ?>
            </a>
            <a href="<?php echo esc_url( $banned_url ); ?>" class="nav-tab <?php echo $is_banned_view ? 'nav-tab-active' : ''; ?>" id="tab-banned-numbers" data-tab="banned-numbers">
                <?php echo esc_html__( 'Banned Users', 'sitestaffr' ); ?>
            </a>
        </div>
        <div class="sitestaffr-tab-controls">
            <?php if ( ! $is_trash_view && ! $is_banned_view ) : ?>
            <form method="post" class="sitestaffr-tab-search" id="sitestaffr-tab-search-form">
                <input type="hidden" name="page" value="<?php echo esc_attr( 'sitestaffr' ); ?>" />
                <input type="hidden" name="view" value="<?php echo esc_attr( 'all' ); ?>" />
                <input type="search" name="s" value="<?php echo esc_attr( $current_search ); ?>" placeholder="<?php echo esc_attr__( 'Search...', 'sitestaffr' ); ?>" />
                <input type="submit" class="button" value="<?php echo esc_attr__( 'Search Conversations', 'sitestaffr' ); ?>" />
            </form>
            <?php endif; ?>
            <?php if ( $is_trash_view && $trash_count > 0 ) : ?>
            <?php
            $empty_trash_url = wp_nonce_url(
                add_query_arg( array(
                    'action'  => 'empty_trash',
                    'call_id' => 0,
                    'view'    => 'trash',
                ), $base_url ),
                'sitestaffr_empty_trash'
            );
            ?>
            <a href="<?php echo esc_url( $empty_trash_url ); ?>" class="button sitestaffr-tab-empty-trash" onclick="return confirm('<?php echo esc_js( __( 'Are you sure you want to permanently delete all conversations in the trash? This cannot be undone.', 'sitestaffr' ) ); ?>');">
                <?php echo esc_html__( 'Empty Trash', 'sitestaffr' ); ?>
            </a>
            <?php endif; ?>
            <?php if ( $is_banned_view ) : ?>
            <button type="button" class="button button-primary sitestaffr-ban-btn sitestaffr-tab-ban" id="sitestaffr-tab-ban-btn">
                <span class="dashicons dashicons-plus-alt" style="vertical-align: middle;"></span>
                <?php echo esc_html__( 'Ban User', 'sitestaffr' ); ?>
            </button>
            <?php endif; ?>
        </div>
    </nav>

    <?php if ( $is_trash_view ) : ?>
    <!-- Trash Tab Content -->
    <div id="tab-content-trash" class="sitestaffr-tab-content active">

        <form method="post" id="sitestaffr-trash-list-form">
            <?php
            echo '<input type="hidden" name="page" value="' . esc_attr( 'sitestaffr' ) . '" />';
            echo '<input type="hidden" name="view" value="' . esc_attr( 'trash' ) . '" />';
            $calls_list_table->display();
            ?>
        </form>

    </div><!-- #tab-content-trash -->

    <?php elseif ( $is_banned_view ) : ?>
    <!-- Banned Numbers Tab Content -->
    <div id="tab-content-banned-numbers" class="sitestaffr-tab-content active">

        <!-- Banned Numbers Table -->
        <div id="sitestaffr-banned-numbers-container">

            <!-- Loading State -->
            <div id="sitestaffr-banned-loading">
                <span class="spinner is-active"></span>
                <p><?php echo esc_html__( 'Loading banned users...', 'sitestaffr' ); ?></p>
            </div>

            <!-- Table (hidden initially, shown by JavaScript) -->
            <table class="wp-list-table widefat fixed striped sitestaffr-banned-table" id="sitestaffr-banned-table" style="display: none;">
                <thead>
                    <tr>
                        <th scope="col" class="column-phone"><?php echo esc_html__( 'IP / Identifier', 'sitestaffr' ); ?></th>
                        <th scope="col" class="column-date"><?php echo esc_html__( 'Banned Date', 'sitestaffr' ); ?></th>
                        <th scope="col" class="column-reason"><?php echo esc_html__( 'Reason', 'sitestaffr' ); ?></th>
                        <th scope="col" class="column-actions"><?php echo esc_html__( 'Actions', 'sitestaffr' ); ?></th>
                    </tr>
                </thead>
                <tbody id="sitestaffr-banned-table-body">
                    <!-- Rows populated by JavaScript -->
                </tbody>
            </table>

            <!-- Empty State (hidden initially, shown by JavaScript if no banned numbers) -->
            <div id="sitestaffr-banned-empty" class="sitestaffr-empty-state" style="display: none;">
                <div class="sitestaffr-banned-empty-inner">
                    <span class="dashicons dashicons-shield"></span>
                    <p>
                        <?php echo esc_html__( 'No current banned users.', 'sitestaffr' ); ?>
                    </p>
                    <p>
                        <?php echo esc_html__( 'Banned users will appear here.', 'sitestaffr' ); ?>
                    </p>
                </div>
            </div>

        </div>

    </div><!-- #tab-content-banned-numbers -->

    <?php else : ?>
    <!-- All Calls Tab Content -->
    <div id="tab-content-all-calls" class="sitestaffr-tab-content active">

    <form method="post" id="sitestaffr-calls-list-form">
        <?php
        // Add hidden fields to preserve view=all when filtering/sorting
        echo '<input type="hidden" name="page" value="' . esc_attr( 'sitestaffr' ) . '" />';
        echo '<input type="hidden" name="view" value="' . esc_attr( 'all' ) . '" />';

        // Display the list table (search box moved to tab bar above)
        $calls_list_table->display();
        ?>
    </form>

    </div><!-- #tab-content-all-calls -->
    <?php endif; ?>

    </div><!-- .sitestaffr-calls-page-wrapper -->
</div><!-- .wrap -->

<?php if ( $is_banned_view ) : ?>
<!-- Ban User Modal (outside .wrap to avoid WordPress admin containment) -->
<div id="sitestaffr-ban-modal" class="sitestaffr-ban-modal-wrapper" style="display: none;">
    <div class="sitestaffr-ban-modal-overlay"></div>
    <div class="sitestaffr-ban-modal-dialog">

        <!-- Modal Header -->
        <div class="sitestaffr-modal-header">
            <h2><?php echo esc_html__( 'Ban User', 'sitestaffr' ); ?></h2>
            <button type="button" class="sitestaffr-modal-close" id="sitestaffr-close-ban-modal">
                <span class="dashicons dashicons-no-alt"></span>
            </button>
        </div>

        <!-- Modal Body -->
        <div class="sitestaffr-modal-body">

            <!-- Identifier Field -->
            <div class="sitestaffr-form-field">
                <label for="sitestaffr-ban-phone">
                    <?php echo esc_html__( 'Identifier', 'sitestaffr' ); ?>
                    <span class="required">*</span>
                </label>
                <input
                    type="tel"
                    id="sitestaffr-ban-phone"
                    class="regular-text"
                    placeholder="<?php echo esc_attr__( 'IP, phone, or visitor identifier', 'sitestaffr' ); ?>"
                    required
                />
                <p class="description">
                    <?php echo esc_html__( 'Enter an IP, phone number, or visitor identifier.', 'sitestaffr' ); ?>
                </p>
                <p id="sitestaffr-ban-phone-error" class="sitestaffr-error-message" style="display: none;"></p>
            </div>

            <!-- Reason Field -->
            <div class="sitestaffr-form-field">
                <label for="sitestaffr-ban-reason">
                    <?php echo esc_html__( 'Reason (optional)', 'sitestaffr' ); ?>
                </label>
                <textarea
                    id="sitestaffr-ban-reason"
                    class="large-text"
                    rows="3"
                    placeholder="<?php echo esc_attr__( 'e.g., Spam visitor, Harassment, etc.', 'sitestaffr' ); ?>"
                ></textarea>
                <p class="description">
                    <?php echo esc_html__( 'Optional: Provide a reason for banning this number.', 'sitestaffr' ); ?>
                </p>
            </div>

        </div>

        <!-- Modal Footer -->
        <div class="sitestaffr-modal-footer">
            <button type="button" class="button" id="sitestaffr-cancel-ban">
                <?php echo esc_html__( 'Cancel', 'sitestaffr' ); ?>
            </button>
            <button type="button" class="button button-primary sitestaffr-ban-submit-btn" id="sitestaffr-submit-ban">
                <span class="dashicons dashicons-shield" style="vertical-align: middle; margin-right: 4px;"></span>
                <?php echo esc_html__( 'Ban User', 'sitestaffr' ); ?>
            </button>
        </div>

    </div>
</div>
<?php endif; ?>

<?php // Banned visitors JS is enqueued via class-sitestaffr-admin.php. ?>

<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
