@charset "UTF-8";

/*!
Theme Name: Cocoon Child
Description: Cocoon専用の子テーマ
Theme URI: https://wp-cocoon.com/
Author: わいひら
Author URI: https://nelog.jp/
Template:   cocoon-master
Version:    1.1.3
*/

//子テーマ用関数
if ( !defined( 'ABSPATH' ) ) exit;

//子テーマ用のビジュアルエディタースタイルを適用
add_editor_style();

//以下に子テーマ用の関数を書く
function register_salon_post_type() {
    register_post_type( 'salon', [
        'labels' => [
            'name'          => 'サロン',
            'singular_name' => 'サロン',
            'add_new_item'  => '新しいサロンを追加',
            'edit_item'     => 'サロンを編集',
            'all_items'     => 'すべてのサロン',
        ],
        'public'       => true,
        'has_archive'  => true,
        'show_in_rest' => true,
        'menu_icon'    => 'dashicons-store',
        'supports'     => [ 'title', 'editor', 'thumbnail', 'excerpt', 'author' ],
        'rewrite'      => [ 'slug' => 'salon' ],
    ]);
}
add_action( 'init', 'register_salon_post_type' );

// ===== マップ近隣検索 REST API =====
add_action('rest_api_init', function() {
    register_rest_route('salon/v1', '/nearby', [
        'methods'             => 'GET',
        'callback'            => 'salon_nearby_search',
        'permission_callback' => '__return_true',
        'args' => [
            'lat'    => [ 'required' => true, 'validate_callback' => function($v) { return is_numeric($v) && $v >= -90 && $v <= 90; } ],
            'lng'    => [ 'required' => true, 'validate_callback' => function($v) { return is_numeric($v) && $v >= -180 && $v <= 180; } ],
            'radius' => [ 'default' => 5000, 'validate_callback' => function($v) { return is_numeric($v) && $v <= 50000; } ],
        ],
    ]);
});

function salon_nearby_search( WP_REST_Request $request ) {
    $lat    = floatval( $request->get_param('lat') );
    $lng    = floatval( $request->get_param('lng') );
    $radius = intval( $request->get_param('radius') );
    $salons = get_posts([ 'post_type' => 'salon', 'posts_per_page' => 50, 'post_status' => 'publish' ]);
    $results = [];
    foreach ( $salons as $salon ) {
        $salon_lat = floatval( get_post_meta($salon->ID, 'salon_lat', true) );
        $salon_lng = floatval( get_post_meta($salon->ID, 'salon_lng', true) );
        if ( !$salon_lat || !$salon_lng ) continue;
        $distance = salon_calc_distance($lat, $lng, $salon_lat, $salon_lng);
        if ( $distance <= $radius ) {
            $results[] = [
                'id' => $salon->ID, 'name' => $salon->post_title,
                'lat' => $salon_lat, 'lng' => $salon_lng,
                'address' => get_post_meta($salon->ID, 'salon_address', true),
                'catch'   => get_post_meta($salon->ID, 'salon_catch', true),
                'price'   => get_post_meta($salon->ID, 'salon_price', true),
                'gender'  => get_post_meta($salon->ID, 'salon_gender', true),
                'url'     => get_permalink($salon->ID),
                'thumb'   => get_the_post_thumbnail_url($salon->ID, 'medium'),
                'distance'=> round($distance / 1000, 1),
            ];
        }
    }
    usort($results, fn($a, $b) => $a['distance'] <=> $b['distance']);
    return rest_ensure_response($results);
}

function salon_calc_distance($lat1, $lng1, $lat2, $lng2) {
    $R = 6371000;
    $dLat = deg2rad($lat2 - $lat1);
    $dLng = deg2rad($lng2 - $lng1);
    $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLng/2) * sin($dLng/2);
    return $R * 2 * atan2(sqrt($a), sqrt(1-$a));
}

// ===== salon_owner ロールを作成 =====
function create_salon_owner_role() {
    if ( get_role('salon_owner') ) return;
    add_role( 'salon_owner', 'サロンオーナー', [ 'read' => true, 'edit_posts' => false, 'upload_files' => true ] );
}
add_action( 'init', 'create_salon_owner_role' );

// ===== ログイン後のリダイレクト =====
function owner_login_redirect( $redirect_to, $request, $user ) {
    if ( !isset($user->roles) ) return $redirect_to;
    if ( in_array('administrator', $user->roles) ) return $redirect_to;
    if ( in_array('salon_owner', $user->roles) ) return home_url('/owner-dashboard/');
    return $redirect_to;
}
add_filter( 'login_redirect', 'owner_login_redirect', 10, 3 );

// ===== 管理画面アクセス制限 =====
function restrict_admin_for_salon_owner() {
    if ( is_admin() && !wp_doing_ajax() ) {
        $user = wp_get_current_user();
        if ( current_user_can('administrator') ) return;
        if ( in_array('salon_owner', $user->roles) ) { wp_redirect( home_url('/owner-dashboard/') ); exit; }
    }
}
add_action( 'admin_init', 'restrict_admin_for_salon_owner' );

// ===== 管理バーをオーナーのみ非表示 =====
function hide_admin_bar_for_owner() {
    $user = wp_get_current_user();
    if ( current_user_can('administrator') ) return;
    if ( in_array('salon_owner', $user->roles) ) show_admin_bar(false);
}
add_action( 'after_setup_theme', 'hide_admin_bar_for_owner' );

// ===== オーナーとサロンの紐づけ =====
function get_salon_by_owner( $user_id ) {
    $salons = get_posts([ 'post_type' => 'salon', 'author' => $user_id, 'numberposts' => 1, 'post_status' => ['publish','pending','draft'] ]);
    if (!empty($salons)) return $salons[0];
    $salons = get_posts([ 'post_type' => 'salon', 'numberposts' => 1, 'post_status' => ['publish','pending','draft'], 'meta_query' => [[ 'key' => 'salon_owner_id', 'value' => $user_id ]] ]);
    if (!empty($salons)) return $salons[0];
    return null;
}

// ===== オーナーアカウント作成ユーティリティ =====
function create_salon_owner_account( $display_name, $email, $password ) {
    if ( email_exists($email) ) return new WP_Error('exists', 'このメールアドレスはすでに登録されています。');
    $user_id = wp_create_user( sanitize_user($email), $password, sanitize_email($email) );
    if ( is_wp_error($user_id) ) return $user_id;
    $user = new WP_User($user_id);
    $user->set_role('salon_owner');
    wp_update_user([ 'ID' => $user_id, 'display_name' => sanitize_text_field($display_name) ]);
    return $user_id;
}

// ===== Square API リクエスト共通関数 =====
function square_api_request($method, $endpoint, $data = []) {
    $token = defined('SQUARE_ACCESS_TOKEN') ? SQUARE_ACCESS_TOKEN : '';
    $env   = defined('SQUARE_ENV') && SQUARE_ENV === 'sandbox' ? 'connect.squareupsandbox.com' : 'connect.squareup.com';
    if (!$token) return ['errors' => [['detail' => 'Square Access Tokenが設定されていません']]];
    $url  = "https://{$env}/v2/{$endpoint}";
    $args = [
        'method'  => $method,
        'headers' => [
            'Authorization'  => 'Bearer ' . $token,
            'Content-Type'   => 'application/json',
            'Square-Version' => '2024-01-17',
        ],
        'timeout' => 30,
    ];
    if (!empty($data)) $args['body'] = json_encode($data);
    $response = wp_remote_request($url, $args);
    if (is_wp_error($response)) return ['errors' => [['detail' => $response->get_error_message()]]];
    return json_decode(wp_remote_retrieve_body($response), true);
}

// ===== Square 決済リンク作成 REST API =====
add_action('rest_api_init', function() {
    register_rest_route('salon/v1', '/square/checkout', [
        'methods'             => 'POST',
        'callback'            => 'create_square_checkout',
        'permission_callback' => function() { return is_user_logged_in(); },
    ]);
});

function create_square_checkout(WP_REST_Request $request) {
    $current_user = wp_get_current_user();
    $plan         = sanitize_text_field($request->get_param('plan'));
    $salon_id     = intval($request->get_param('salon_id'));
    $location_id  = defined('SQUARE_LOCATION_ID') ? SQUARE_LOCATION_ID : '';

    if (!$location_id) {
        return new WP_REST_Response(['error' => 'SQUARE_LOCATION_IDが設定されていません'], 500);
    }

    $price = $plan === 'ベーシック' ? 300000 : ($plan === 'プレミアム' ? 800000 : 0);
    if (!$price) return new WP_REST_Response(['error' => '無効なプランです'], 400);

    $success_url = home_url('/owner-plan/?payment=success&plan=' . urlencode($plan) . '&salon_id=' . $salon_id);
    $cancel_url  = home_url('/owner-plan/?payment=cancel');

    $checkout = square_api_request('POST', 'online-checkout/payment-links', [
        'idempotency_key' => uniqid('checkout_', true),
        'quick_pay' => [
            'name'        => $plan . 'プラン（月額）',
            'price_money' => [ 'amount' => $price, 'currency' => 'JPY' ],
            'location_id' => $location_id,
        ],
        'checkout_options' => [
            'redirect_url'             => $success_url,
            'ask_for_shipping_address' => false,
        ],
        'pre_populated_data' => [ 'buyer_email' => $current_user->user_email ],
    ]);

    if (isset($checkout['payment_link']['url'])) {
        return new WP_REST_Response([ 'url' => $checkout['payment_link']['url'] ], 200);
    }

    $err = $checkout['errors'][0]['detail'] ?? json_encode($checkout);
    return new WP_REST_Response([ 'error' => $err ], 500);
}

// ===== Square Webhook =====
add_action('rest_api_init', function() {
    register_rest_route('salon/v1', '/square/webhook', [
        'methods'             => 'POST',
        'callback'            => 'handle_square_webhook',
        'permission_callback' => '__return_true',
    ]);
});

function handle_square_webhook(WP_REST_Request $request) {
    $event = json_decode($request->get_body(), true);
    if (!$event) return new WP_REST_Response('Invalid payload', 400);
    if (($event['type'] ?? '') === 'payment.completed') {
        $customer_id = $event['data']['object']['payment']['customer_id'] ?? '';
        $users = get_users([ 'meta_key' => 'square_customer_id', 'meta_value' => $customer_id ]);
        if (!empty($users)) {
            $pending = get_transient('square_pending_' . $users[0]->ID);
            if ($pending) {
                update_post_meta($pending['salon_id'], 'salon_plan', $pending['plan']);
                delete_transient('square_pending_' . $users[0]->ID);
            }
        }
    }
    return new WP_REST_Response('OK', 200);
}

// ===== プラン変更申請 REST API =====
add_action('rest_api_init', function() {
    register_rest_route('salon/v1', '/plan-request', [
        'methods'             => 'POST',
        'callback'            => 'save_plan_request',
        'permission_callback' => function() { return is_user_logged_in(); },
    ]);
});

function save_plan_request(WP_REST_Request $request) {
    $current_user   = wp_get_current_user();
    $salon_id       = intval($request->get_param('salon_id'));
    $requested_plan = sanitize_text_field($request->get_param('plan'));
    if (!$salon_id || !$requested_plan) return new WP_REST_Response(['error' => 'パラメータが不正です'], 400);
    $salon = get_post($salon_id);
    if (!$salon || $salon->post_type !== 'salon') return new WP_REST_Response(['error' => 'サロンが見つかりません'], 404);
    $current_plan = get_post_meta($salon_id, 'salon_plan', true) ?: '無料';
    $requests     = get_option('salon_plan_requests', []);
    $request_id   = 'req_' . time() . '_' . $salon_id;
    $requests[$request_id] = [
        'id' => $request_id, 'salon_id' => $salon_id, 'salon_name' => $salon->post_title,
        'user_id' => $current_user->ID, 'user_name' => $current_user->display_name, 'user_email' => $current_user->user_email,
        'current_plan' => $current_plan, 'requested_plan' => $requested_plan,
        'status' => 'pending', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'),
    ];
    update_option('salon_plan_requests', $requests);
    wp_mail( get_option('admin_email'), '【山梨脱毛ナビ】プラン変更申請：' . $salon->post_title,
        $current_user->display_name . " 様よりプラン変更申請がありました。\n希望プラン：{$requested_plan}\n" . admin_url('admin.php?page=salon_plan_requests') );
    wp_mail( $current_user->user_email, '【山梨脱毛ナビ】プラン変更申請を受け付けました',
        $current_user->display_name . " 様\nプラン変更申請を受け付けました。\n希望プラン：{$requested_plan}\n2営業日以内にご連絡いたします。\n山梨脱毛ナビ" );
    return new WP_REST_Response([ 'success' => true, 'request_id' => $request_id ], 200);
}

// ===== 管理画面：プラン申請管理ページ =====
add_action('admin_menu', function() {
    $requests      = get_option('salon_plan_requests', []);
    $pending_count = count(array_filter($requests, fn($r) => $r['status'] === 'pending'));
    $badge         = $pending_count > 0 ? ' <span class="awaiting-mod">' . $pending_count . '</span>' : '';
    add_menu_page( 'プラン申請管理', 'プラン申請' . $badge, 'administrator', 'salon_plan_requests', 'render_plan_requests_page', 'dashicons-clipboard', 26 );
});

function process_plan_request() {
    if (!isset($_POST['plan_request_action_nonce'])) return;
    if (!wp_verify_nonce($_POST['plan_request_action_nonce'], 'plan_request_action')) return;
    if (!current_user_can('administrator')) return;
    $request_id = sanitize_text_field($_POST['request_id'] ?? '');
    $action     = sanitize_text_field($_POST['request_action'] ?? '');
    $requests   = get_option('salon_plan_requests', []);
    if (!isset($requests[$request_id])) return;
    $req = $requests[$request_id];
    if ($action === 'approve') {
        update_post_meta($req['salon_id'], 'salon_plan', $req['requested_plan']);
        $requests[$request_id]['status']     = 'approved';
        $requests[$request_id]['updated_at'] = date('Y-m-d H:i:s');
        $requests[$request_id]['admin_note'] = sanitize_textarea_field($_POST['admin_note'] ?? '');
        $user = get_user_by('id', $req['user_id']);
        if ($user) wp_mail( $user->user_email, '【山梨脱毛ナビ】プラン変更が承認されました',
            $user->display_name . " 様\n{$req['requested_plan']}プランへの変更が承認されました。\n" . home_url('/owner-dashboard/') );
    } elseif ($action === 'reject') {
        $requests[$request_id]['status']     = 'rejected';
        $requests[$request_id]['updated_at'] = date('Y-m-d H:i:s');
        $requests[$request_id]['admin_note'] = sanitize_textarea_field($_POST['admin_note'] ?? '');
        $user = get_user_by('id', $req['user_id']);
        if ($user) wp_mail( $user->user_email, '【山梨脱毛ナビ】プラン変更申請について',
            $user->display_name . " 様\nプラン変更申請についてご連絡があります。詳細はお問い合わせください。\n山梨脱毛ナビ" );
    } elseif ($action === 'delete') {
        unset($requests[$request_id]);
    }
    update_option('salon_plan_requests', $requests);
}
add_action('admin_init', 'process_plan_request');

function render_plan_requests_page() {
    $requests       = get_option('salon_plan_requests', []);
    uasort($requests, fn($a, $b) => strcmp($b['created_at'], $a['created_at']));
    $filter_status  = sanitize_text_field($_GET['status'] ?? '');
    if ($filter_status) $requests = array_filter($requests, fn($r) => $r['status'] === $filter_status);
    $all            = get_option('salon_plan_requests', []);
    $pending_count  = count(array_filter($all, fn($r) => $r['status'] === 'pending'));
    $approved_count = count(array_filter($all, fn($r) => $r['status'] === 'approved'));
    $rejected_count = count(array_filter($all, fn($r) => $r['status'] === 'rejected'));
    $plan_colors    = [ '無料' => '#888', 'ベーシック' => '#0c5d8a', 'プレミアム' => '#856404' ];
    $status_labels  = [ 'pending' => ['対応中','#e8294a','#fff0f3'], 'approved' => ['承認済','#155724','#d4edda'], 'rejected' => ['却下','#664d03','#fff3cd'] ];
    ?>
    <div class="wrap">
        <h1>📋 プラン変更申請管理
            <?php if ($pending_count > 0) echo '<span style="background:#e8294a;color:#fff;font-size:13px;font-weight:700;padding:4px 14px;border-radius:20px;margin-left:12px;">未対応 ' . $pending_count . '件</span>'; ?>
        </h1>
        <div style="display:flex;gap:10px;margin-bottom:20px;flex-wrap:wrap;">
            <a href="<?php echo admin_url('admin.php?page=salon_plan_requests'); ?>" style="background:<?php echo !$filter_status?'#1a1a2e':'#f0f0f0';?>;color:<?php echo !$filter_status?'#fff':'#333';?>;padding:8px 16px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;">すべて（<?php echo count($all); ?>）</a>
            <a href="<?php echo admin_url('admin.php?page=salon_plan_requests&status=pending'); ?>" style="background:<?php echo $filter_status==='pending'?'#e8294a':'#fff0f3';?>;color:<?php echo $filter_status==='pending'?'#fff':'#e8294a';?>;border:1.5px solid #e8294a;padding:8px 16px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;">対応中（<?php echo $pending_count; ?>）</a>
            <a href="<?php echo admin_url('admin.php?page=salon_plan_requests&status=approved'); ?>" style="background:<?php echo $filter_status==='approved'?'#155724':'#d4edda';?>;color:<?php echo $filter_status==='approved'?'#fff':'#155724';?>;border:1.5px solid #c3e6cb;padding:8px 16px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;">承認済（<?php echo $approved_count; ?>）</a>
            <a href="<?php echo admin_url('admin.php?page=salon_plan_requests&status=rejected'); ?>" style="background:<?php echo $filter_status==='rejected'?'#856404':'#fff3cd';?>;color:<?php echo $filter_status==='rejected'?'#fff':'#856404';?>;border:1.5px solid #ffc107;padding:8px 16px;border-radius:8px;text-decoration:none;font-size:13px;font-weight:700;">却下（<?php echo $rejected_count; ?>）</a>
        </div>
        <?php if (empty($requests)) : ?>
        <div style="background:#f9f9f9;border:1px solid #e0e0e0;border-radius:10px;padding:40px;text-align:center;color:#888;">まだプラン変更申請はありません</div>
        <?php else : ?>
        <table class="widefat fixed striped">
            <thead><tr style="background:#1a1a2e;">
                <th style="color:#fff;width:140px;">申請日時</th>
                <th style="color:#fff;">サロン名</th>
                <th style="color:#fff;width:120px;">申請者</th>
                <th style="color:#fff;width:90px;">現在</th>
                <th style="color:#fff;width:90px;">希望</th>
                <th style="color:#fff;width:70px;">状態</th>
                <th style="color:#fff;width:180px;">操作</th>
            </tr></thead>
            <tbody>
            <?php foreach ($requests as $req) :
                $sl = $status_labels[$req['status']] ?? ['不明','#888','#f0f0f0'];
                $current_plan_actual = get_post_meta($req['salon_id'], 'salon_plan', true) ?: '無料';
            ?>
            <tr>
                <td style="font-size:12px;color:#666;"><?php echo esc_html(date('Y/m/d H:i', strtotime($req['created_at']))); ?></td>
                <td><strong><?php echo esc_html($req['salon_name']); ?></strong><br><span style="font-size:11px;color:#aaa;">実際のプラン：<?php echo esc_html($current_plan_actual); ?></span></td>
                <td style="font-size:12px;"><?php echo esc_html($req['user_name']); ?><br><span style="color:#aaa;font-size:11px;"><?php echo esc_html($req['user_email']); ?></span></td>
                <td><span style="font-size:12px;font-weight:700;color:<?php echo $plan_colors[$req['current_plan']]??'#888';?>;"><?php echo esc_html($req['current_plan']); ?></span></td>
                <td><span style="font-size:13px;font-weight:700;color:<?php echo $plan_colors[$req['requested_plan']]??'#888';?>;"><?php echo esc_html($req['requested_plan']); ?></span></td>
                <td><span style="background:<?php echo $sl[2];?>;color:<?php echo $sl[1];?>;font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px;"><?php echo esc_html($sl[0]); ?></span></td>
                <td>
                <?php if ($req['status'] === 'pending') : ?>
                    <textarea id="note-<?php echo esc_attr($req['id']); ?>" placeholder="メモ" style="width:100%;font-size:11px;border:1px solid #ddd;border-radius:4px;padding:4px;min-height:36px;resize:vertical;margin-bottom:4px;"></textarea>
                    <div style="display:flex;gap:4px;">
                        <form method="post" style="flex:1;"><input type="hidden" name="request_id" value="<?php echo esc_attr($req['id']); ?>"><input type="hidden" name="request_action" value="approve"><input type="hidden" name="admin_note" id="na-<?php echo esc_attr($req['id']); ?>" value=""><?php wp_nonce_field('plan_request_action','plan_request_action_nonce'); ?><button type="submit" onclick="document.getElementById('na-<?php echo esc_attr($req['id']); ?>').value=document.getElementById('note-<?php echo esc_attr($req['id']); ?>').value" style="width:100%;background:#155724;color:#fff;border:none;border-radius:4px;padding:5px;font-size:11px;cursor:pointer;">✅ 承認</button></form>
                        <form method="post" style="flex:1;"><input type="hidden" name="request_id" value="<?php echo esc_attr($req['id']); ?>"><input type="hidden" name="request_action" value="reject"><input type="hidden" name="admin_note" id="nr-<?php echo esc_attr($req['id']); ?>" value=""><?php wp_nonce_field('plan_request_action','plan_request_action_nonce'); ?><button type="submit" onclick="document.getElementById('nr-<?php echo esc_attr($req['id']); ?>').value=document.getElementById('note-<?php echo esc_attr($req['id']); ?>').value" style="width:100%;background:#856404;color:#fff;border:none;border-radius:4px;padding:5px;font-size:11px;cursor:pointer;">❌ 却下</button></form>
                    </div>
                <?php else : ?>
                    <div style="font-size:11px;color:#888;margin-bottom:4px;"><?php echo esc_html(date('Y/m/d', strtotime($req['updated_at']))); ?></div>
                    <div style="display:flex;gap:4px;flex-wrap:wrap;">
                        <?php foreach (['無料','ベーシック','プレミアム'] as $p) : if ($p===$current_plan_actual) continue; ?>
                        <form method="post" style="margin:0;"><input type="hidden" name="request_id" value="<?php echo esc_attr($req['id']); ?>"><input type="hidden" name="request_action" value="approve"><input type="hidden" name="admin_note" value=""><?php wp_nonce_field('plan_request_action','plan_request_action_nonce'); ?><button type="submit" style="background:#f0f0f0;color:#333;border:1px solid #ddd;border-radius:4px;padding:3px 6px;font-size:11px;cursor:pointer;"><?php echo esc_html($p); ?>に変更</button></form>
                        <?php endforeach; ?>
                        <form method="post" style="margin:0;" onsubmit="return confirm('削除しますか？')"><input type="hidden" name="request_id" value="<?php echo esc_attr($req['id']); ?>"><input type="hidden" name="request_action" value="delete"><?php wp_nonce_field('plan_request_action','plan_request_action_nonce'); ?><button type="submit" style="background:#fff0f3;color:#e8294a;border:1px solid #f7c0cb;border-radius:4px;padding:3px 6px;font-size:11px;cursor:pointer;">削除</button></form>
                    </div>
                <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>

        <div style="margin-top:28px;background:#fff;border:1px solid #e0e0e0;border-radius:10px;padding:20px;">
            <h2 style="font-size:15px;font-weight:700;border-left:4px solid #e8294a;padding-left:10px;margin-bottom:14px;">サロンのプランを直接変更</h2>
            <?php $all_salons = get_posts(['post_type'=>'salon','posts_per_page'=>-1,'post_status'=>['publish','draft'],'orderby'=>'title','order'=>'ASC']); ?>
            <form method="post" action="<?php echo admin_url('admin-post.php'); ?>">
                <?php wp_nonce_field('direct_plan_change','direct_plan_nonce'); ?>
                <input type="hidden" name="action" value="direct_plan_change">
                <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;">
                    <div><label style="display:block;font-size:12px;font-weight:700;color:#555;margin-bottom:4px;">サロンを選択</label>
                    <select name="direct_salon_id" style="border:1.5px solid #ddd;border-radius:6px;padding:8px 12px;font-size:13px;min-width:180px;">
                        <?php foreach ($all_salons as $s) : $cp = get_post_meta($s->ID,'salon_plan',true)?:'無料'; ?>
                        <option value="<?php echo esc_attr($s->ID); ?>"><?php echo esc_html($s->post_title); ?>（<?php echo esc_html($cp); ?>）</option>
                        <?php endforeach; ?>
                    </select></div>
                    <div><label style="display:block;font-size:12px;font-weight:700;color:#555;margin-bottom:4px;">変更後のプラン</label>
                    <select name="direct_plan" style="border:1.5px solid #ddd;border-radius:6px;padding:8px 12px;font-size:13px;">
                        <option value="無料">無料プラン</option>
                        <option value="ベーシック">ベーシック（¥3,000/月）</option>
                        <option value="プレミアム">プレミアム（¥8,000/月）</option>
                    </select></div>
                    <div><label style="display:block;font-size:12px;font-weight:700;color:#555;margin-bottom:4px;">メモ（任意）</label>
                    <input type="text" name="direct_note" placeholder="例：お支払い確認しました" style="border:1.5px solid #ddd;border-radius:6px;padding:8px 12px;font-size:13px;min-width:180px;"></div>
                    <button type="submit" style="background:#e8294a;color:#fff;border:none;border-radius:8px;padding:10px 20px;font-size:13px;font-weight:700;cursor:pointer;">プランを変更する</button>
                </div>
            </form>
        </div>
    </div>
    <?php
}

add_action('admin_post_direct_plan_change', function() {
    if (!wp_verify_nonce($_POST['direct_plan_nonce'],'direct_plan_change')) wp_die('不正なリクエスト');
    if (!current_user_can('administrator')) wp_die('権限がありません');
    $salon_id = intval($_POST['direct_salon_id'] ?? 0);
    $new_plan = sanitize_text_field($_POST['direct_plan'] ?? '');
    $note     = sanitize_text_field($_POST['direct_note'] ?? '');
    if ($salon_id && $new_plan) {
        update_post_meta($salon_id, 'salon_plan', $new_plan);
        $salon  = get_post($salon_id);
        $author = get_user_by('id', $salon->post_author);
        if ($author) wp_mail( $author->user_email, '【山梨脱毛ナビ】掲載プランが変更されました',
            $author->display_name . " 様\nプランが{$new_plan}に変更されました。\n" . ($note ? "メモ：{$note}\n" : '') . home_url('/owner-dashboard/') );
    }
    wp_redirect(admin_url('admin.php?page=salon_plan_requests&updated=1'));
    exit;
});

wp_redirect(admin_url('admin.php?page=salon_plan_requests&updated=1'));
    exit;
});