<?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 );
$is_leads_view = ( 'leads' === $current_view );

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

// Tab count badges: All = unread, Leads = total leads, Trash + Banned = totals.
$trash_count  = SiteStaffr_Call_Manager::get_trash_count();
$unread_count = SiteStaffr_Call_Manager::get_calls_count( array( 'is_read' => 0 ) );
$leads_count  = SiteStaffr_Call_Manager::get_calls_count( array( 'qualified_lead' => true ) );
$banned_count = class_exists( 'SiteStaffr_Ban_Manager' ) ? count( SiteStaffr_Ban_Manager::get_bans() ) : 0;

// 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' );
$leads_url = wp_nonce_url( add_query_arg( 'view', 'leads', $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-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' ),
            'all_marked_read'          => __( 'All conversations marked as read.', 'sitestaffr' ),
            'unbanned'                 => __( 'Ban removed.', 'sitestaffr' ),
            'sf_retried'               => __( 'Lead synced to Salesforce.', 'sitestaffr' ),
        );

        $error_messages = array(
            'sf_retry_failed' => __( 'Could not sync the lead to Salesforce. Check the connection under Settings → Integrations, then try again.', 'sitestaffr' ),
        );

        if ( isset( $notice_messages[ $message ] ) ) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $notice_messages[ $message ] ) . '</p></div>';
        } elseif ( isset( $error_messages[ $message ] ) ) {
            echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $error_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 && ! $is_leads_view ) ? 'nav-tab-active' : ''; ?>" id="tab-all-calls">
                <?php echo esc_html__( 'All Conversations', 'sitestaffr' ); ?>
                <?php if ( $unread_count > 0 ) : ?>
                    <span class="count" title="<?php esc_attr_e( 'Unread conversations', 'sitestaffr' ); ?>">(<?php echo esc_html( $unread_count ); ?>)</span>
                <?php endif; ?>
            </a>
            <a href="<?php echo esc_url( $leads_url ); ?>" class="nav-tab <?php echo $is_leads_view ? 'nav-tab-active' : ''; ?>" id="tab-leads">
                <?php echo esc_html__( 'Qualified Leads', 'sitestaffr' ); ?>
                <?php if ( $leads_count > 0 ) : ?>
                    <span class="count">(<?php echo esc_html( $leads_count ); ?>)</span>
                <?php endif; ?>
            </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' ); ?>
                <?php if ( $banned_count > 0 ) : ?>
                    <span class="count">(<?php echo esc_html( $banned_count ); ?>)</span>
                <?php endif; ?>
            </a>
        </div>
        <div class="sitestaffr-tab-controls">
            <?php if ( $is_leads_view && class_exists( 'SiteStaffr_Leads' ) ) : ?>
            <span class="sitestaffr-tab-leadlink">
                <a href="<?php echo esc_url( SiteStaffr_Leads::get_page_url() ); ?>" target="_blank" rel="noopener noreferrer" class="button sitestaffr-view-leads-btn">
                    <span class="dashicons dashicons-external" aria-hidden="true"></span>
                    <?php echo esc_html__( 'Open shareable page', 'sitestaffr' ); ?>
                </a>
            </span>
            <?php endif; ?>
            <?php if ( ! $is_trash_view && ! $is_banned_view && $unread_count > 0 && ! $is_leads_view ) : ?>
            <?php
            $mark_all_url = wp_nonce_url(
                add_query_arg( array(
                    'action'  => 'mark_all_read',
                    'call_id' => 0,
                    'view'    => 'all',
                ), $base_url ),
                'sitestaffr_mark_all_read'
            );
            ?>
            <a href="<?php echo esc_url( $mark_all_url ); ?>" class="button sitestaffr-mark-all-read">
                <?php echo esc_html__( 'Mark all as read', 'sitestaffr' ); ?>
            </a>
            <?php endif; ?>
            <?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( $is_leads_view ? 'leads' : 'all' ); ?>" />
                <input type="search" name="s" value="<?php echo esc_attr( $current_search ); ?>" placeholder="<?php echo esc_attr__( 'Search summaries & contacts…', 'sitestaffr' ); ?>" />
                <input type="submit" class="button" value="<?php echo esc_attr( $is_leads_view ? __( 'Search Leads', 'sitestaffr' ) : __( '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" data-sitestaffr-confirm="<?php echo esc_attr__( 'Are you sure you want to permanently delete all conversations in the trash? This cannot be undone.', 'sitestaffr' ); ?>" data-sitestaffr-confirm-danger>
                <?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" aria-hidden="true"></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 Users Tab Content (server-rendered WP_List_Table like its siblings) -->
    <div id="tab-content-banned-numbers" class="sitestaffr-tab-content active">
        <?php
        $banned_list_table = new SiteStaffr_Banned_List_Table();
        $banned_list_table->prepare_items();
        $banned_list_table->display();
        ?>
    </div><!-- #tab-content-banned-numbers -->

    <?php elseif ( $is_leads_view ) : ?>
    <!-- Qualified Leads Tab Content -->
    <div id="tab-content-leads" class="sitestaffr-tab-content active">

        <p class="sitestaffr-leads-tab-intro">
            <?php echo esc_html__( 'Conversations that captured a name plus a phone or email. This is the same data shown on the shareable leads page linked from your notification emails.', 'sitestaffr' ); ?>
        </p>

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

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

    <?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-modal-overlay" role="dialog" aria-modal="true" aria-labelledby="sitestaffr-ban-modal-title" aria-hidden="true" style="display: none;">
    <div class="sitestaffr-modal" role="document">

        <!-- Modal Header -->
        <div class="sitestaffr-modal-header">
            <h2 id="sitestaffr-ban-modal-title"><?php echo esc_html__( 'Ban User', 'sitestaffr' ); ?></h2>
            <button type="button" class="sitestaffr-modal-close" id="sitestaffr-close-ban-modal" aria-label="<?php esc_attr_e( 'Close', 'sitestaffr' ); ?>">
                <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="text"
                    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 user.', '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" aria-hidden="true"></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 ?>
