<?php

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

add_action('init', 'chbk_register_cpts', 5);
add_filter('use_block_editor_for_post_type', 'chbk_disable_block_editor_for_chbk_types', 10, 2);

function chbk_register_cpts()
{
    $trips_slug = 'charters';
    if (function_exists('chbk_get_setting')) {
        $configured_slug = (string) chbk_get_setting('trips_slug', 'charters');
        $configured_slug = sanitize_title($configured_slug);
        if ($configured_slug !== '') {
            $trips_slug = $configured_slug;
        }
    }

    register_post_type('chbk_captain', [
        'labels' => [
            'name' => 'Captains',
            'singular_name' => 'Captain',
            'add_new' => 'Add Captain',
            'add_new_item' => 'Add Captain',
            'edit_item' => 'Edit Captain',
            'new_item' => 'New Captain',
            'view_item' => 'View Captain',
            'search_items' => 'Search Captains',
        ],
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => false,
        'supports' => ['title'],
        'capability_type' => 'post',
        'map_meta_cap' => true,
    ]);

    register_post_type('chbk_boat', [
        'labels' => [
            'name' => 'Boats',
            'singular_name' => 'Boat',
            'add_new' => 'Add Boat',
            'add_new_item' => 'Add Boat',
            'edit_item' => 'Edit Boat',
            'new_item' => 'New Boat',
            'view_item' => 'View Boat',
            'search_items' => 'Search Boats',
        ],
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => false,
        'supports' => ['title'],
    ]);

    register_post_type('chbk_trip', [
        'labels' => [
            'name' => 'Trips',
            'singular_name' => 'Trip',
            'add_new' => 'Add Trip',
            'add_new_item' => 'Add Trip',
            'edit_item' => 'Edit Trip',
            'new_item' => 'New Trip',
            'view_item' => 'View Trip',
            'search_items' => 'Search Trips',
        ],
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => false,
        'supports' => ['title', 'editor', 'thumbnail'],
        'has_archive' => $trips_slug,
        'rewrite' => [
            'slug' => $trips_slug,
            'with_front' => false,
        ],
        'show_in_rest' => true,
    ]);

    register_post_type('chbk_booking', [
        'labels' => [
            'name' => 'Bookings',
            'singular_name' => 'Booking',
        ],
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => false,
        'supports' => ['title'],
    ]);

}

function chbk_disable_block_editor_for_chbk_types($use_block_editor, $post_type)
{
    if (in_array($post_type, ['chbk_captain', 'chbk_boat', 'chbk_trip', 'chbk_booking'], true)) {
        return false;
    }

    return $use_block_editor;
}
