<?php
/**
 * Admin UI for unified player profiles.
 *
 * @package Chess_Podium
 */

if (!defined('ABSPATH')) {
    exit;
}

final class ChessPodium_PlayerProfileAdmin
{
    public static function init(): void
    {
        add_action('admin_menu', [self::class, 'register_menu'], 25);
        add_action('admin_init', [self::class, 'handle_actions'], 5);
    }

    public static function register_menu(): void
    {
        add_submenu_page(
            'chess-podium',
            __('Players', 'chess-podium'),
            __('Players', 'chess-podium'),
            'manage_options',
            'chess-podium-players',
            [self::class, 'render_page']
        );
    }

    public static function handle_actions(): void
    {
        if (!is_admin() || !current_user_can('manage_options')) {
            return;
        }
        if (empty($_POST['cp_player_action'])) {
            return;
        }
        check_admin_referer('cp_player_admin', 'cp_player_nonce');

        $action = sanitize_key((string) wp_unslash($_POST['cp_player_action']));
        if ($action === 'save') {
            $id = (int) ($_POST['player_id'] ?? 0);
            $slug = ChessPodium_PlayerDirectory::sanitize_slug((string) wp_unslash($_POST['slug'] ?? ''));
            $name = sanitize_text_field((string) wp_unslash($_POST['display_name'] ?? ''));
            $fideId = ChessPodium_PlayerDirectory::normalize_fide_id_alias((string) wp_unslash($_POST['fide_id'] ?? ''));
            $country = ChessPodiumPlugin::sanitize_country_code((string) wp_unslash($_POST['country'] ?? ''));
            $bio = sanitize_textarea_field((string) wp_unslash($_POST['bio'] ?? ''));
            $lichess = sanitize_text_field((string) wp_unslash($_POST['lichess_username'] ?? ''));
            $chesscom = sanitize_text_field((string) wp_unslash($_POST['chesscom_username'] ?? ''));
            $wpUserId = (int) ($_POST['wp_user_id'] ?? 0);
            $removeAvatar = !empty($_POST['cp_remove_avatar']);

            if ($name === '') {
                wp_safe_redirect(admin_url('admin.php?page=chess-podium-players&cp_msg=cp_player_error'));
                exit;
            }
            if ($slug === '') {
                $slug = ChessPodium_PlayerDirectory::sanitize_slug($name);
            }
            if ($slug === '') {
                wp_safe_redirect(admin_url('admin.php?page=chess-podium-players&cp_msg=cp_player_error'));
                exit;
            }

            global $wpdb;
            $table = ChessPodium_PlayerDirectory::get_players_table();
            $now = current_time('mysql');

            // Ensure slug is unique.
            $existingId = (int) $wpdb->get_var($wpdb->prepare("SELECT id FROM $table WHERE slug = %s", $slug));
            if ($existingId > 0 && $existingId !== $id) {
                wp_safe_redirect(admin_url('admin.php?page=chess-podium-players&cp_msg=cp_player_slug_taken'));
                exit;
            }

            $avatarId = 0;
            if ($id > 0) {
                $existingRow = ChessPodium_PlayerDirectory::get_by_id($id);
                $avatarId = $existingRow && isset($existingRow->avatar_attachment_id) ? (int) $existingRow->avatar_attachment_id : 0;
            }
            if ($removeAvatar) {
                $avatarId = 0;
            } elseif (!empty($_FILES['cp_player_avatar']['tmp_name']) && is_uploaded_file((string) $_FILES['cp_player_avatar']['tmp_name'])) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
                require_once ABSPATH . 'wp-admin/includes/media.php';
                require_once ABSPATH . 'wp-admin/includes/image.php';
                $uploaded = media_handle_upload('cp_player_avatar', 0);
                if (!is_wp_error($uploaded)) {
                    $avatarId = (int) $uploaded;
                }
            }

            $data = [
                'slug' => $slug,
                'display_name' => $name,
                'fide_id' => $fideId !== '' ? $fideId : null,
                'country' => $country !== '' ? $country : null,
                'bio' => $bio !== '' ? $bio : null,
                'chesscom_username' => $chesscom !== '' ? $chesscom : null,
                'lichess_username' => $lichess !== '' ? $lichess : null,
                'wp_user_id' => $wpUserId > 0 ? $wpUserId : null,
                'avatar_attachment_id' => $avatarId > 0 ? $avatarId : null,
                'updated_at' => $now,
            ];
            if ($id > 0) {
                $wpdb->update($table, $data, ['id' => $id]);
            } else {
                $data['created_at'] = $now;
                $wpdb->insert($table, $data);
                $id = (int) $wpdb->insert_id;
            }

            // Ensure basic aliases.
            if ($id > 0) {
                $ref = ChessPodium_PlayerDirectory::get_by_id($id);
                if ($ref) {
                    // Reuse resolver alias writer.
                    $resolved = ChessPodium_PlayerDirectory::resolve_or_create($name, $fideId, $country);
                    // If resolver created a different row, keep admin-created row authoritative.
                    if ($resolved && (int) $resolved->id !== (int) $ref->id) {
                        // No-op; admin can merge later.
                    }
                }
            }

            wp_safe_redirect(admin_url('admin.php?page=chess-podium-players&player_id=' . (int) $id . '&cp_msg=cp_player_saved'));
            exit;
        }

        if ($action === 'delete') {
            $id = (int) ($_POST['player_id'] ?? 0);
            if ($id > 0) {
                global $wpdb;
                $wpdb->delete(ChessPodium_PlayerDirectory::get_aliases_table(), ['player_id' => $id], ['%d']);
                $wpdb->delete(ChessPodium_PlayerDirectory::get_gp_map_table(), ['player_id' => $id], ['%d']);
                $wpdb->delete(ChessPodium_PlayerDirectory::get_players_table(), ['id' => $id], ['%d']);
            }
            wp_safe_redirect(admin_url('admin.php?page=chess-podium-players&cp_msg=cp_player_deleted'));
            exit;
        }
    }

    public static function render_page(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }
        $id = isset($_GET['player_id']) ? (int) $_GET['player_id'] : 0;
        $msg = isset($_GET['cp_msg']) ? sanitize_key((string) wp_unslash($_GET['cp_msg'])) : '';
        $messages = [
            'cp_player_saved' => __('Player profile saved.', 'chess-podium'),
            'cp_player_deleted' => __('Player profile deleted.', 'chess-podium'),
            'cp_player_error' => __('Please fill in required fields.', 'chess-podium'),
            'cp_player_slug_taken' => __('Slug already in use. Choose another one.', 'chess-podium'),
        ];
        if ($msg && isset($messages[$msg])) {
            $type = in_array($msg, ['cp_player_error', 'cp_player_slug_taken'], true) ? 'error' : 'success';
            echo '<div class="notice notice-' . esc_attr($type) . ' is-dismissible"><p>' . esc_html($messages[$msg]) . '</p></div>';
        }

        global $wpdb;
        $table = ChessPodium_PlayerDirectory::get_players_table();
        $player = $id > 0 ? ChessPodium_PlayerDirectory::get_by_id($id) : null;
        $rows = $wpdb->get_results("SELECT * FROM $table ORDER BY updated_at DESC, id DESC LIMIT 200"); // phpcs:ignore
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Players', 'chess-podium'); ?></h1>

            <div style="display:flex;gap:24px;align-items:flex-start;flex-wrap:wrap;">
                <div style="flex:1;min-width:340px;max-width:520px;">
                    <h2><?php echo $player ? esc_html__('Edit player', 'chess-podium') : esc_html__('Create player', 'chess-podium'); ?></h2>
                    <form method="post" enctype="multipart/form-data">
                        <?php wp_nonce_field('cp_player_admin', 'cp_player_nonce'); ?>
                        <input type="hidden" name="cp_player_action" value="save">
                        <input type="hidden" name="player_id" value="<?php echo (int) ($player->id ?? 0); ?>">
                        <table class="form-table">
                            <tr>
                                <th><?php esc_html_e('Avatar', 'chess-podium'); ?></th>
                                <td>
                                    <?php
                                    $aid = $player && isset($player->avatar_attachment_id) ? (int) $player->avatar_attachment_id : 0;
                                    $aurl = $aid > 0 ? (string) wp_get_attachment_image_url($aid, 'thumbnail') : '';
                                    ?>
                                    <?php if ($aurl !== ''): ?>
                                        <p><img src="<?php echo esc_url($aurl); ?>" alt="" style="width:96px;height:96px;object-fit:cover;border-radius:8px;border:1px solid #ccd0d4;"></p>
                                    <?php endif; ?>
                                    <p><input type="file" name="cp_player_avatar" id="cp_player_avatar" accept="image/*"></p>
                                    <?php if ($player && $aid > 0): ?>
                                        <p><label><input type="checkbox" name="cp_remove_avatar" value="1"> <?php esc_html_e('Remove avatar', 'chess-podium'); ?></label></p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th><label for="cp_display_name"><?php esc_html_e('Name', 'chess-podium'); ?></label></th>
                                <td><input id="cp_display_name" name="display_name" type="text" class="regular-text" value="<?php echo esc_attr((string) ($player->display_name ?? '')); ?>" required></td>
                            </tr>
                            <tr>
                                <th><label for="cp_slug"><?php esc_html_e('Slug', 'chess-podium'); ?></label></th>
                                <td><input id="cp_slug" name="slug" type="text" class="regular-text" value="<?php echo esc_attr((string) ($player->slug ?? '')); ?>" placeholder="<?php esc_attr_e('auto from name', 'chess-podium'); ?>"></td>
                            </tr>
                            <tr>
                                <th><label for="cp_fide_id"><?php esc_html_e('FIDE ID', 'chess-podium'); ?></label></th>
                                <td><input id="cp_fide_id" name="fide_id" type="text" class="regular-text" value="<?php echo esc_attr((string) ($player->fide_id ?? '')); ?>" inputmode="numeric"></td>
                            </tr>
                            <tr>
                                <th><label for="cp_country"><?php esc_html_e('Country', 'chess-podium'); ?></label></th>
                                <td><input id="cp_country" name="country" type="text" value="<?php echo esc_attr((string) ($player->country ?? '')); ?>" maxlength="2" style="width:60px;text-transform:uppercase;"></td>
                            </tr>
                            <tr>
                                <th><label for="cp_lichess"><?php esc_html_e('Lichess username', 'chess-podium'); ?></label></th>
                                <td><input id="cp_lichess" name="lichess_username" type="text" class="regular-text" value="<?php echo esc_attr((string) ($player->lichess_username ?? '')); ?>"></td>
                            </tr>
                            <tr>
                                <th><label for="cp_chesscom"><?php esc_html_e('Chess.com username', 'chess-podium'); ?></label></th>
                                <td><input id="cp_chesscom" name="chesscom_username" type="text" class="regular-text" value="<?php echo esc_attr((string) ($player->chesscom_username ?? '')); ?>"></td>
                            </tr>
                            <tr>
                                <th><label for="cp_wp_user"><?php esc_html_e('WP user ID (owner)', 'chess-podium'); ?></label></th>
                                <td><input id="cp_wp_user" name="wp_user_id" type="number" class="small-text" value="<?php echo esc_attr((string) ((int) ($player->wp_user_id ?? 0))); ?>" min="0"></td>
                            </tr>
                            <tr>
                                <th><label for="cp_bio"><?php esc_html_e('Biography', 'chess-podium'); ?></label></th>
                                <td><textarea id="cp_bio" name="bio" rows="6" class="large-text"><?php echo esc_textarea((string) ($player->bio ?? '')); ?></textarea></td>
                            </tr>
                        </table>
                        <p><button type="submit" class="button button-primary"><?php esc_html_e('Save', 'chess-podium'); ?></button></p>
                    </form>

                    <?php if ($player): ?>
                        <form method="post" onsubmit="return confirm('<?php echo esc_js(__('Delete this player profile?', 'chess-podium')); ?>');">
                            <?php wp_nonce_field('cp_player_admin', 'cp_player_nonce'); ?>
                            <input type="hidden" name="cp_player_action" value="delete">
                            <input type="hidden" name="player_id" value="<?php echo (int) $player->id; ?>">
                            <button type="submit" class="button button-link-delete"><?php esc_html_e('Delete', 'chess-podium'); ?></button>
                        </form>
                        <p class="description"><?php esc_html_e('Public URL:', 'chess-podium'); ?> <code><?php echo esc_html(ChessPodiumPlugin::get_unified_player_profile_url((string) ($player->slug ?? ''))); ?></code></p>
                    <?php endif; ?>
                </div>

                <div style="flex:2;min-width:420px;">
                    <h2><?php esc_html_e('Directory', 'chess-podium'); ?></h2>
                    <table class="wp-list-table widefat fixed striped">
                        <thead>
                            <tr>
                                <th><?php esc_html_e('Name', 'chess-podium'); ?></th>
                                <th><?php esc_html_e('Slug', 'chess-podium'); ?></th>
                                <th><?php esc_html_e('FIDE ID', 'chess-podium'); ?></th>
                                <th><?php esc_html_e('Owner', 'chess-podium'); ?></th>
                                <th><?php esc_html_e('Actions', 'chess-podium'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ((array) $rows as $r): ?>
                                <tr>
                                    <td><strong><?php echo esc_html((string) ($r->display_name ?? '')); ?></strong></td>
                                    <td><code><?php echo esc_html((string) ($r->slug ?? '')); ?></code></td>
                                    <td><?php echo esc_html((string) ($r->fide_id ?? '')); ?></td>
                                    <td><?php echo (int) ($r->wp_user_id ?? 0) > 0 ? esc_html((string) (int) $r->wp_user_id) : '—'; ?></td>
                                    <td>
                                        <a class="button button-small" href="<?php echo esc_url(admin_url('admin.php?page=chess-podium-players&player_id=' . (int) $r->id)); ?>"><?php esc_html_e('Edit', 'chess-podium'); ?></a>
                                        <a class="button button-small" href="<?php echo esc_url(ChessPodiumPlugin::get_unified_player_profile_url((string) ($r->slug ?? ''))); ?>" target="_blank" rel="noopener"><?php esc_html_e('View', 'chess-podium'); ?></a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <p class="description"><?php esc_html_e('Tip: link a WP user ID so the player can edit their own bio later via a shortcode.', 'chess-podium'); ?></p>
                </div>
            </div>
        </div>
        <?php
    }
}

