<?php
/**
 * Frontend/self-edit for unified player profiles.
 *
 * @package Chess_Podium
 */

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

final class ChessPodium_PlayerProfileFrontend
{
    public static function init(): void
    {
        add_shortcode('chess_podium_my_profile', [self::class, 'render_my_profile_shortcode']);
        add_action('init', [self::class, 'handle_post'], 5);
    }

    public static function handle_post(): void
    {
        if (empty($_POST['cp_my_profile_save'])) {
            return;
        }
        if (!is_user_logged_in()) {
            return;
        }
        check_admin_referer('cp_my_profile', 'cp_my_profile_nonce');
        $userId = get_current_user_id();
        $player = ChessPodium_PlayerDirectory::get_by_wp_user_id((int) $userId);
        if (!$player) {
            return;
        }

        $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'] ?? ''));

        $avatarId = isset($player->avatar_attachment_id) ? (int) $player->avatar_attachment_id : 0;
        if (!empty($_FILES['avatar_file']) && is_array($_FILES['avatar_file']) && !empty($_FILES['avatar_file']['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';
            $newId = media_handle_upload('avatar_file', 0);
            if (!is_wp_error($newId)) {
                $avatarId = (int) $newId;
            }
        }

        global $wpdb;
        $table = ChessPodium_PlayerDirectory::get_players_table();
        $wpdb->update($table, [
            'bio' => $bio !== '' ? $bio : null,
            'lichess_username' => $lichess !== '' ? $lichess : null,
            'chesscom_username' => $chesscom !== '' ? $chesscom : null,
            'avatar_attachment_id' => $avatarId > 0 ? $avatarId : null,
            'updated_at' => current_time('mysql'),
        ], ['id' => (int) $player->id], ['%s', '%s', '%s', '%d', '%s'], ['%d']);

        $redirect = isset($_POST['redirect_to']) ? esc_url_raw((string) wp_unslash($_POST['redirect_to'])) : '';
        if ($redirect === '') {
            $redirect = add_query_arg('cp_saved', '1', wp_get_referer() ?: home_url('/'));
        } else {
            $redirect = add_query_arg('cp_saved', '1', $redirect);
        }
        wp_safe_redirect($redirect);
        exit;
    }

    public static function render_my_profile_shortcode(): string
    {
        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('Please log in to edit your profile.', 'chess-podium') . '</p>';
        }
        $player = ChessPodium_PlayerDirectory::get_by_wp_user_id((int) get_current_user_id());
        if (!$player) {
            return '<p>' . esc_html__('No player profile is linked to your account yet. Contact the webmaster.', 'chess-podium') . '</p>';
        }
        $saved = !empty($_GET['cp_saved']);
        $avatarAttachmentId = isset($player->avatar_attachment_id) ? (int) $player->avatar_attachment_id : 0;
        $avatarUrl = $avatarAttachmentId > 0 ? (string) wp_get_attachment_image_url($avatarAttachmentId, 'thumbnail') : '';
        ob_start();
        ?>
        <div class="cp-my-profile" style="max-width:720px;">
            <?php if ($saved): ?>
                <div class="notice notice-success" style="padding:10px 12px;margin:10px 0;"><?php echo esc_html__('Profile saved.', 'chess-podium'); ?></div>
            <?php endif; ?>
            <h2><?php echo esc_html((string) ($player->display_name ?? '')); ?></h2>
            <form method="post" enctype="multipart/form-data">
                <?php wp_nonce_field('cp_my_profile', 'cp_my_profile_nonce'); ?>
                <input type="hidden" name="cp_my_profile_save" value="1">
                <input type="hidden" name="redirect_to" value="<?php echo esc_attr(get_permalink() ?: ''); ?>">

                <p>
                    <label><strong><?php esc_html_e('Avatar', 'chess-podium'); ?></strong></label><br>
                    <?php if ($avatarUrl !== ''): ?>
                        <img src="<?php echo esc_url($avatarUrl); ?>" alt="" style="width:64px;height:64px;border-radius:10px;object-fit:cover;border:1px solid #e5e7eb;">
                    <?php endif; ?>
                    <input type="file" name="avatar_file" accept="image/*">
                </p>

                <p>
                    <label><strong><?php esc_html_e('Lichess username', 'chess-podium'); ?></strong></label><br>
                    <input type="text" name="lichess_username" value="<?php echo esc_attr((string) ($player->lichess_username ?? '')); ?>" class="regular-text">
                </p>
                <p>
                    <label><strong><?php esc_html_e('Chess.com username', 'chess-podium'); ?></strong></label><br>
                    <input type="text" name="chesscom_username" value="<?php echo esc_attr((string) ($player->chesscom_username ?? '')); ?>" class="regular-text">
                </p>

                <p>
                    <label><strong><?php esc_html_e('Biography', 'chess-podium'); ?></strong></label><br>
                    <textarea name="bio" rows="8" class="large-text"><?php echo esc_textarea((string) ($player->bio ?? '')); ?></textarea>
                </p>

                <p><button type="submit" class="button button-primary"><?php esc_html_e('Save', 'chess-podium'); ?></button></p>
            </form>
        </div>
        <?php
        return (string) ob_get_clean();
    }
}

