<?php
if ( ! defined( 'ABSPATH' ) ) exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- template file, variables are local to included scope

global $wpdb;

$group_id  = isset( $_GET['group-id'] ) ? (int) $_GET['group-id'] : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only admin page routing
$is_new    = ( $group_id === 0 );
$group     = null;
$settings  = array(
    'columns'            => 3,
    'image_shape'        => 'circle',
    'per_page'           => 12,
    'show_position'      => true,
    'show_institution'   => true,
    'show_tags'          => true,
    'max_tags'           => 3,
    'show_publications'  => true,
    'show_profile_link'  => true,
    'show_article_image' => false,
);
$view_type = 'feed';
$name      = '';

if ( ! $is_new ) {
    $table_groups = SCHOLAR_SYNC_DB_GROUPS;
    $group = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE group_id = %d', $table_groups, $group_id ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- %i is the WordPress identifier placeholder (WP 6.2+), Read bypasses cache safely
    if ( $group ) {
        $name      = $group->name;
        $view_type = $group->view_type;
        if ( $group->settings ) {
            $decoded = json_decode( $group->settings, true );
            if ( is_array( $decoded ) ) {
                $settings = array_merge( $settings, $decoded );
            }
        }
    }
}

// Fetch all authors for the available / selected lists.
$table_authors = SCHOLAR_SYNC_DB_AUTHORS;
$all_authors = $wpdb->get_results( $wpdb->prepare( 'SELECT author_id, name, directory_link FROM %i ORDER BY name ASC', $table_authors ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- %i is the WordPress identifier placeholder (WP 6.2+), Read bypasses cache safely

// Fetch current group members in sort_order + their saved link_url.
$member_ids   = array();
$member_links = array(); // author_id => link_url saved in junction
if ( ! $is_new && $group ) {
    $table_group_authors = SCHOLAR_SYNC_DB_GROUP_AUTHORS;
    $rows = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- %i is the WordPress identifier placeholder (WP 6.2+), Read bypasses cache safely
        'SELECT author_id, link_url FROM %i WHERE group_id = %d ORDER BY sort_order ASC',
        $table_group_authors,
        $group_id
    ) );
    foreach ( $rows as $row ) {
        $member_ids[]                      = (int) $row->author_id;
        $member_links[ (int) $row->author_id ] = $row->link_url;
    }
}

// Build lookup: author_id => [ name, directory_link ]
$available_authors = array(); // aid => [ name, directory_link ]
$selected_authors  = array();
foreach ( $all_authors as $a ) {
    $entry = array( 'name' => $a->name, 'dir_link' => (string) $a->directory_link );
    if ( in_array( (int) $a->author_id, $member_ids, true ) ) {
        $selected_authors[ (int) $a->author_id ] = $entry;
    } else {
        $available_authors[ (int) $a->author_id ] = $entry;
    }
}
// Preserve sort order for selected authors.
$ordered_selected = array();
foreach ( $member_ids as $mid ) {
    if ( isset( $selected_authors[ $mid ] ) ) {
        $ordered_selected[ $mid ] = $selected_authors[ $mid ];
    }
}

$action_url  = admin_url( 'admin.php?page=scholar-sync-actions-slug' );
$page_title  = $is_new ? __( 'Add New Group', 'scholar-sync' ) : __( 'Edit Group', 'scholar-sync' );
?>
<div class="wrap">
    <h1 class="top-header" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;">
        <span>
            <?php echo esc_html( $page_title ); ?>
            <a href="<?php echo esc_url( admin_url( 'admin.php?page=scholar-sync-groups-slug' ) ); ?>" class="page-title-action">&larr; <?php esc_html_e( 'All Groups', 'scholar-sync' ); ?></a>
        </span>
        <?php if ( ! $is_new ) : ?>
        <a href="<?php echo esc_url( admin_url( 'admin.php?page=scholar-sync-preview-group-slug&group-id=' . $group_id ) ); ?>"
           target="wp-preview-group-<?php echo (int) $group_id; ?>"
           class="button button-secondary"
           style="font-size:13px;display:inline-flex;align-items:center;gap:6px;">
            <?php esc_html_e( 'Preview &amp; Shortcode', 'scholar-sync' ); ?> &#8599;
        </a>
        <?php endif; ?>
    </h1>
    <hr class="wp-header-end">

    <?php if ( ! empty( $_GET['msg'] ) && $_GET['msg'] === 'saved'
               && isset( $_GET['_wpnonce'] )
               && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'scholar_sync_notice' ) ) : ?>
        <div class="notice notice-success is-dismissible">
            <p>
                <?php esc_html_e( 'Group saved.', 'scholar-sync' ); ?>
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=scholar-sync-preview-group-slug&group-id=' . $group_id ) ); ?>"
                   target="wp-preview-group-<?php echo (int) $group_id; ?>"
                   class="button button-small" style="margin-left:10px;">
                    <?php esc_html_e( 'Preview', 'scholar-sync' ); ?>
                </a>
            </p>
        </div>
    <?php endif; ?>

    <form method="POST" action="<?php echo esc_url( $action_url ); ?>" id="group-edit-form">
        <?php wp_nonce_field( 'scholar_sync_save_group' ); ?>
        <input type="hidden" name="action"   value="save-group">
        <input type="hidden" name="group_id" value="<?php echo (int) $group_id; ?>">

        <table class="form-table" role="presentation">
            <tr>
                <th scope="row"><label for="group_name"><?php esc_html_e( 'Group Name', 'scholar-sync' ); ?></label></th>
                <td>
                    <input type="text" id="group_name" name="group_name"
                           value="<?php echo esc_attr( $name ); ?>"
                           class="regular-text" required>
                </td>
            </tr>

            <tr>
                <th scope="row"><?php esc_html_e( 'Group Type', 'scholar-sync' ); ?></th>
                <td>
                    <div class="scholar-sync-view-type-selector">
                        <label class="scholar-sync-view-option <?php echo $view_type === 'feed' ? 'active' : ''; ?>">
                            <input type="radio" name="view_type" value="feed"
                                   <?php checked( $view_type, 'feed' ); ?>>
                            <span class="dashicons dashicons-list-view" style="font-size:36px;width:36px;height:36px;"></span>
                            <span class="scholar-sync-view-label"><?php esc_html_e( 'Research Feed (List)', 'scholar-sync' ); ?></span>
                            <a href="https://scholar-sync.org/researchers-feed" target="_blank" class="scholar-sync-view-example" onclick="event.stopPropagation();"><?php esc_html_e( 'View Example', 'scholar-sync' ); ?></a>
                        </label>
                        <label class="scholar-sync-view-option <?php echo $view_type === 'grid' ? 'active' : ''; ?>">
                            <input type="radio" name="view_type" value="grid"
                                   <?php checked( $view_type, 'grid' ); ?>>
                            <span class="dashicons dashicons-grid-view" style="font-size:36px;width:36px;height:36px;"></span>
                            <span class="scholar-sync-view-label"><?php esc_html_e( 'Staff Directory (Grid)', 'scholar-sync' ); ?></span>
                            <a href="https://scholar-sync.org/researchers-directory" target="_blank" class="scholar-sync-view-example" onclick="event.stopPropagation();"><?php esc_html_e( 'View Example', 'scholar-sync' ); ?></a>
                        </label>
                    </div>
                </td>
            </tr>

            <tr class="scholar-sync-view-only-row scholar-sync-view-only-feed" style="<?php echo $view_type !== 'feed' ? 'display:none;' : ''; ?>">
                <th scope="row"><?php esc_html_e( 'Article images', 'scholar-sync' ); ?></th>
                <td>
                    <label>
                        <input type="checkbox" name="show_article_image" value="1" <?php checked( ! empty( $settings['show_article_image'] ) ); ?>>
                        <?php esc_html_e( 'Show article images', 'scholar-sync' ); ?>
                    </label>
                    <p class="description"><?php esc_html_e( 'Show each article\'s image (e.g. graphical abstract or poster) in the research feed, when one is set.', 'scholar-sync' ); ?></p>
                </td>
            </tr>

            <tr class="scholar-sync-view-only-row scholar-sync-view-only-grid" style="<?php echo $view_type !== 'grid' ? 'display:none;' : ''; ?>">
                <th scope="row"><?php esc_html_e( 'Card Image Shape', 'scholar-sync' ); ?></th>
                <td>
                    <select name="image_shape">
                        <option value="circle"    <?php selected( $settings['image_shape'], 'circle' ); ?>><?php esc_html_e( 'Circle', 'scholar-sync' ); ?></option>
                        <option value="square"    <?php selected( $settings['image_shape'], 'square' ); ?>><?php esc_html_e( 'Square', 'scholar-sync' ); ?></option>
                        <option value="rectangle" <?php selected( $settings['image_shape'], 'rectangle' ); ?>><?php esc_html_e( 'Rectangle (portrait)', 'scholar-sync' ); ?></option>
                    </select>
                </td>
            </tr>

            <tr class="scholar-sync-view-only-row scholar-sync-view-only-grid" style="<?php echo $view_type !== 'grid' ? 'display:none;' : ''; ?>">
                <th scope="row"><?php esc_html_e( 'Columns', 'scholar-sync' ); ?></th>
                <td>
                    <input type="number" name="columns" min="1" max="4" value="<?php echo (int) $settings['columns']; ?>" class="small-text">
                </td>
            </tr>

            <tr class="scholar-sync-view-only-row scholar-sync-view-only-grid" style="<?php echo $view_type !== 'grid' ? 'display:none;' : ''; ?>">
                <th scope="row"><?php esc_html_e( 'Researchers per page', 'scholar-sync' ); ?></th>
                <td>
                    <input type="number" name="per_page" min="4" max="48" value="<?php echo (int) $settings['per_page']; ?>" class="small-text">
                </td>
            </tr>

            <tr class="scholar-sync-view-only-row scholar-sync-view-only-grid" style="<?php echo $view_type !== 'grid' ? 'display:none;' : ''; ?>">
                <th scope="row"><?php esc_html_e( 'Card Fields', 'scholar-sync' ); ?></th>
                <td>
                    <label style="display:block;">
                        <input type="checkbox" name="show_position" value="1" <?php checked( ! empty( $settings['show_position'] ) ); ?>>
                        <?php esc_html_e( 'Show position / title', 'scholar-sync' ); ?>
                    </label>
                    <label style="display:block;">
                        <input type="checkbox" name="show_institution" value="1" <?php checked( ! empty( $settings['show_institution'] ) ); ?>>
                        <?php esc_html_e( 'Show institution (affiliations)', 'scholar-sync' ); ?>
                    </label>
                    <label style="display:block;">
                        <input type="checkbox" name="show_tags" value="1" <?php checked( ! empty( $settings['show_tags'] ) ); ?>>
                        <?php esc_html_e( 'Show research tags (interests)', 'scholar-sync' ); ?>
                    </label>
                    <label style="display:block;">
                        <?php esc_html_e( 'Tags to show before "+N more":', 'scholar-sync' ); ?>
                        <input type="number" name="max_tags" min="1" max="10" value="<?php echo (int) $settings['max_tags']; ?>" class="small-text">
                    </label>
                    <label style="display:block;">
                        <input type="checkbox" name="show_publications" value="1" <?php checked( ! empty( $settings['show_publications'] ) ); ?>>
                        <?php esc_html_e( 'Show publication count', 'scholar-sync' ); ?>
                    </label>
                    <label style="display:block;">
                        <input type="checkbox" name="show_profile_link" value="1" <?php checked( ! empty( $settings['show_profile_link'] ) ); ?>>
                        <?php esc_html_e( 'Show "View Profile" link', 'scholar-sync' ); ?>
                    </label>
                </td>
            </tr>

            <tr>
                <th scope="row"><?php esc_html_e( 'Members', 'scholar-sync' ); ?></th>
                <td>
                    <div class="scholar-sync-members-ui <?php echo $view_type === 'grid' ? 'is-grid' : 'is-feed'; ?>">
                    <table class="scholar-sync-dual-listbox">
                        <colgroup>
                            <col class="wdl-col-list">
                            <col class="wdl-col-btns">
                            <col class="wdl-col-list">
                        </colgroup>
                        <tr>
                            <td><strong><?php esc_html_e( 'Available Authors', 'scholar-sync' ); ?></strong></td>
                            <td></td>
                            <td><strong><?php esc_html_e( 'Selected Members', 'scholar-sync' ); ?></strong></td>
                        </tr>
                        <tr>
                            <td>
                                <input type="text" id="scholar-sync-author-filter"
                                       placeholder="<?php esc_attr_e( 'Filter authors…', 'scholar-sync' ); ?>"
                                       style="width:100%;box-sizing:border-box;">
                            </td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td>
                                <select id="scholar-sync-available" multiple size="10" style="width:100%;">
                                    <?php foreach ( $available_authors as $aid => $adata ) : ?>
                                        <option value="<?php echo (int) $aid; ?>"
                                                data-dir-link="<?php echo esc_attr( $adata['dir_link'] ); ?>">
                                            <?php echo esc_html( $adata['name'] ); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                            <td class="wdl-buttons-cell">
                                <button type="button" id="scholar-sync-add-member"    class="button">&rsaquo;</button>
                                <button type="button" id="scholar-sync-remove-member" class="button">&lsaquo;</button>
                                <button type="button" id="scholar-sync-move-up"       class="button scholar-sync-move-btn">&uarr;</button>
                                <button type="button" id="scholar-sync-move-down"     class="button scholar-sync-move-btn">&darr;</button>
                            </td>
                            <td>
                                <select id="scholar-sync-selected" multiple size="10" style="width:100%;">
                                    <?php foreach ( $ordered_selected as $aid => $adata ) : ?>
                                        <option value="<?php echo (int) $aid; ?>"
                                                data-dir-link="<?php echo esc_attr( $adata['dir_link'] ); ?>">
                                            <?php echo esc_html( $adata['name'] ); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                    </table>
                    <input type="hidden" id="group_author_ids" name="group_author_ids"
                           value="<?php echo esc_attr( implode( ',', array_keys( $ordered_selected ) ) ); ?>">

                    <p class="description">
                        <span class="scholar-sync-reorder-text"><?php esc_html_e( 'Use the arrows to add/remove and reorder members.', 'scholar-sync' ); ?></span>
                        <span class="scholar-sync-simple-text"><?php esc_html_e( 'Use the arrows to add/remove members.', 'scholar-sync' ); ?></span>
                    </p>

                    <?php // Member profile links table ?>
                    <div id="scholar-sync-member-links-section" <?php echo empty( $ordered_selected ) ? 'style="display:none;"' : ''; ?>>
                        <h4 style="margin:20px 0 6px;"><?php esc_html_e( 'Member Profile Links', 'scholar-sync' ); ?></h4>
                        <p class="description" style="margin-bottom:8px;">
                            <?php esc_html_e( 'Optional link shown for each member in the group display. Pre-filled from the author\'s directory link.', 'scholar-sync' ); ?>
                        </p>
                        <table class="widefat" id="scholar-sync-member-links-table">
                            <thead>
                                <tr>
                                    <th style="width:30px;">#</th>
                                    <th><?php esc_html_e( 'Name', 'scholar-sync' ); ?></th>
                                    <th><?php esc_html_e( 'Profile Link', 'scholar-sync' ); ?></th>
                                </tr>
                            </thead>
                            <tbody id="scholar-sync-member-links-body">
                                <?php $i = 1; foreach ( $ordered_selected as $aid => $adata ) :
                                    $link_val = isset( $member_links[ $aid ] ) && $member_links[ $aid ] !== ''
                                        ? $member_links[ $aid ]
                                        : $adata['dir_link'];
                                ?>
                                <tr data-author-id="<?php echo (int) $aid; ?>">
                                    <td><?php echo (int) $i++; ?></td>
                                    <td><?php echo esc_html( $adata['name'] ); ?></td>
                                    <td>
                                        <input type="url"
                                               name="member_links[<?php echo (int) $aid; ?>]"
                                               value="<?php echo esc_attr( $link_val ); ?>"
                                               placeholder="https://"
                                               class="regular-text">
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    </div><!-- /.scholar-sync-members-ui -->
                </td>
            </tr>
        </table>
        <?php submit_button( $is_new ? __( 'Create Group', 'scholar-sync' ) : __( 'Save Group', 'scholar-sync' ) ); ?>
    </form>
</div>
