<?php

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

add_action('admin_enqueue_scripts', 'chbk_enqueue_admin_assets');
add_action('wp_enqueue_scripts', 'chbk_enqueue_frontend_assets');

function chbk_is_plugin_admin_screen($screen, $hook_suffix = '')
{
    if (!$screen) {
        $screen = null;
    }

    if ($screen && !empty($screen->post_type) && in_array($screen->post_type, ['chbk_captain', 'chbk_boat', 'chbk_trip', 'chbk_booking'], true)) {
        return true;
    }

    if ($screen && !empty($screen->id) && strpos((string) $screen->id, 'chbk_') !== false) {
        return true;
    }

    if (is_string($hook_suffix) && $hook_suffix !== '' && (strpos($hook_suffix, '_page_chbk_') !== false || $hook_suffix === 'toplevel_page_chbk_dashboard')) {
        return true;
    }

    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only admin page detection.
    if (isset($_GET['page'])) {
        $page = sanitize_key(wp_unslash($_GET['page']));
        if (strpos($page, 'chbk_') === 0) {
            return true;
        }
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended

    return false;
}

function chbk_enqueue_admin_assets($hook_suffix)
{
    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    if (!chbk_is_plugin_admin_screen($screen, $hook_suffix)) {
        return;
    }

    wp_enqueue_script('jquery-ui-datepicker');
    wp_enqueue_script('chbk-datepicker', CHBK_PLUGIN_URL . 'assets/js/datepicker.js', ['jquery', 'jquery-ui-datepicker'], CHBK_VERSION, true);
    wp_enqueue_style('chbk-datepicker', CHBK_PLUGIN_URL . 'assets/css/datepicker.css', [], CHBK_VERSION);
    wp_enqueue_style('chbk-admin-ui', CHBK_PLUGIN_URL . 'assets/css/admin-ui.css', [], CHBK_VERSION);
}

function chbk_enqueue_frontend_assets()
{
    wp_enqueue_script('jquery-ui-datepicker');
    wp_enqueue_script('chbk-datepicker', CHBK_PLUGIN_URL . 'assets/js/datepicker.js', ['jquery', 'jquery-ui-datepicker'], CHBK_VERSION, true);
    wp_enqueue_style('chbk-datepicker', CHBK_PLUGIN_URL . 'assets/css/datepicker.css', [], CHBK_VERSION);
    wp_enqueue_style('chbk-frontend-ui', CHBK_PLUGIN_URL . 'assets/css/frontend-ui.css', [], CHBK_VERSION);
}
