<?php
/**
 * Hello Biz functions and definitions
 * 役割：事業統括（内部監査）＋ 店舗ダッシュボード制御 ＋ 車両・ブログ管理
 */

// --- 1. 車両投稿タイプ（cars）の定義 ---
add_action('init', function() {
    register_post_type('cars', [
        'labels' => [
            'name' => '在庫車両',
            'singular_name' => '在庫車両',
            'add_new' => '新しい車両を追加',
            'add_new_item' => '新規車両登録',
        ],
        'public' => true,
        'has_archive' => true,
        'menu_position' => 5,
        'menu_icon' => 'dashicons-car',
        'supports' => ['title', 'editor', 'thumbnail', 'author'],
        'show_in_rest' => true,
    ]);
});

// --- 2. 内部監査：ユーザー一覧に情報を追加 ---
add_action('wp_login', function($user_login, $user) {
    update_user_meta($user->ID, 'last_login', current_time('mysql'));
}, 10, 2);

add_filter('manage_users_columns', function($columns) {
    $columns['last_login'] = '最終ログイン';
    $columns['blog_count'] = 'ブログ数';
    $columns['car_count']  = '在庫車数';
    return $columns;
});

add_filter('manage_users_custom_column', function($value, $column_name, $user_id) {
    if ($column_name == 'last_login') {
        $last_login = get_user_meta($user_id, 'last_login', true);
        return $last_login ? mysql2date('Y/m/d H:i', $last_login) : '未ログイン';
    }
    if ($column_name == 'blog_count') return count_user_posts($user_id, 'post');
    if ($column_name == 'car_count') return count_user_posts($user_id, 'cars');
    return $value;
}, 10, 3);

// --- 3. ログイン・アクセス制御（分離戦略） ---
// ログイン後の着地地点を権限で分ける
add_filter('login_redirect', function($redirect_to, $request, $user) {
    if (isset($user->roles) && is_array($user->roles)) {
        if (in_array('administrator', $user->roles)) return admin_url();
        return home_url('/dashboard/');
    }
    return $redirect_to;
}, 100, 3);

// 加盟店を管理画面（/wp-admin/）から隔離する
add_action('admin_init', function() {
    if (!current_user_can('administrator') && !(defined('DOING_AJAX') && DOING_AJAX)) {
        if (is_user_logged_in()) {
            wp_redirect(home_url('/dashboard/'));
            exit;
        }
    }
});

// --- 4. 既存機能：ACFショートコード & ブログ投稿 ---
add_shortcode('sc_real_acf_form', function() {
    if (!function_exists('acf_form')) return 'ACFが起動していません';
    ob_start();
    acf_form_head();
    acf_form(array(
        'post_id' => 'new_post',
        'new_post' => array('post_type' => 'cars', 'post_status' => 'publish'),
        'field_groups' => array('group_69cccbd745f03'),
        'form' => true,
        'return' => home_url('/dashboard/'), // 登録後の戻り先
        'submit_value' => '在庫車両を登録する',
    ));
    return ob_get_clean();
});

add_shortcode('sc_data', function($atts) {
    $a = shortcode_atts(array('name' => ''), $atts);
    return get_field($a['name']);
});

// ブログ保存処理
add_action('template_redirect', function() {
    if (isset($_POST['post_blog_submit'])) {
        $new_post = array(
            'post_title' => sanitize_text_field($_POST['blog_title']),
            'post_content' => wp_kses_post($_POST['blog_content']),
            'post_status' => 'publish',
            'post_type' => 'post',
            'post_author' => get_current_user_id(),
        );
        $post_id = wp_insert_post($new_post);
        if ($post_id) {
            wp_redirect(home_url('/blog-manage/'));
            exit;
        }
    }
});

// --- 5. セキュリティ・UX調整 ---
add_filter('auth_cookie_expiration', function() { return 86400; }); // 24時間保持
add_action('wp_logout', function() { wp_redirect(home_url('/')); exit; });
.sc-dashboard-wrap {
    margin-top: 80px;
    padding: 40px 20px;
}
/* ダッシュボード */
.sc-dashboard-wrap {
    margin-top: 120px;
    padding: 40px 20px;
    min-height: 100vh;
    background: #f5f5f5;
}
.sc-dashboard-inner {
    max-width: 1100px;
    margin: 0 auto;
}
.sc-dashboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40px;
    padding: 20px 30px;
    background: #fff;
    border-radius: 8px;
}
.sc-dashboard-title {
    font-size: 22px;
    font-weight: 700;
    margin: 0 0 6px;
}
.sc-dashboard-store {
    font-size: 14px;
    color: #666;
    margin: 0;
}
.sc-logout-btn {
    padding: 8px 20px;
    background: #eee;
    border-radius: 4px;
    font-size: 13px;
    color: #333;
    text-decoration: none;
}
.sc-dashboard-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}
.sc-dashboard-card {
    background: #fff;
    border-radius: 8px;
    padding: 30px 20px;
    text-decoration: none;
    color: #333;
    display: block;
    transition: box-shadow 0.2s;
}
.sc-dashboard-card:hover {
    box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
.sc-card-num {
    font-size: 13px;
    color: #0073aa;