<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Admin\CPT;

use BookiFlex\Core\Contract\PluginInterface;
use BookiFlex\Core\Contract\RoleCapabilitiesInterface;

defined( 'ABSPATH' ) || exit;

abstract class RatePlan extends AbstractCPT
{
    public const POST_TYPE                                         = 'bflex-rate-plan';
    public const FIELD_BOARD_TYPE                                  = 'bflex__rp__board_type';
    public const FIELD_SHORT_CODE                                  = 'bflex__rp__short_code';
    public const FIELD_ACCOMMODATION_TYPES                         = 'bflex__rp__accommodation_types';
    public const FIELD_PAYMENT_TYPES                               = 'bflex__rp__payment_types';
    public const FIELD_CANCELLATION_POLICY                         = 'bflex__rp__cancellation_policy';
    public const FIELD_BOOKING_TERMS                               = 'bflex__rp__booking_terms';
    public const FIELD_INHERITANCE_PRICE_RULES                     = 'bflex__rp__inheritance_price_rules';
    public const FIELD_INHERITANCE_RESTRICTIONS                    = 'bflex__rp__inheritance_restrictions';
    public const FIELD_INHERITANCE_PRICE_RULES_PLACEMENTS          = 'placements';
    public const FIELD_INHERITANCE_PRICE_RULES_STRATEGY_TYPE       = 'strategy_type';
    public const FIELD_INHERITANCE_PRICE_RULES_STRATEGY_ADJUSTMENT = 'strategy_adjustment';
    public const FIELD_INHERITANCE_PRICE_RULES_STRATEGY_VALUE      = 'strategy_value';
    public const FIELD_HIDDEN_FROM_FRONTEND                        = 'bflex__rp__hidden_from_frontend';


    abstract protected function supportInheritance();

    public function register(PluginInterface $plugin): void
    {
        parent::register($plugin);
        $this->plugin->addAction('pre_get_posts', [$this, 'enableMenuOrderSorting']);
        $this->plugin->addAction('add_meta_boxes', [$this, 'addCalendarMetaBox'], 5);
        $this->registerShortCodeAutoGeneration(self::FIELD_SHORT_CODE);
    }

    public function registerPostType(): void
    {
        $labels = [
            'name'                  => _x('Rate plans', 'Post type general name', 'bookiflex'),
            'singular_name'         => _x('Rate plan', 'Post type singular name', 'bookiflex'),
            'menu_name'             => _x('Rate plans', 'Admin Menu text', 'bookiflex'),
            'name_admin_bar'        => _x('Rate plan', 'Add New on Toolbar', 'bookiflex'),
            'add_new'               => __('Add New', 'bookiflex'),
            'add_new_item'          => __('Add New', 'bookiflex'),
            'new_item'              => __('New Rate plan', 'bookiflex'),
            'edit_item'             => __('Edit Rate plan', 'bookiflex'),
            'view_item'             => __('View Rate plan', 'bookiflex'),
            'all_items'             => __('Rate plans', 'bookiflex'),
            'search_items'          => __('Search', 'bookiflex'),
            'parent_item_colon'     => __('Parent Rate plans:', 'bookiflex'),
            'not_found'             => __('Nothing found.', 'bookiflex'),
            'not_found_in_trash'    => __('Nothing found in Trash.', 'bookiflex'),
            'attributes'            => __('Attributes', 'bookiflex'),
        ];

        $args = [
            'labels'             => $labels,
            'public'             => true,
            'publicly_queryable' => false,
            'show_ui'            => true,
            'show_in_menu'       => 'bookiflex',
            'query_var'          => false,
            'rewrite'            => ['slug' => self::POST_TYPE],
            'has_archive'        => false,
            'hierarchical'       => $this->supportInheritance(),
            'menu_position'      => 1,
            'supports'           => ['title'],
            'capability_type'    => self::POST_TYPE,
            'capabilities'       => [
                'edit_post'              => RoleCapabilitiesInterface::MANAGE_CONFIGURATION,
                'read_post'              => RoleCapabilitiesInterface::MANAGE_CONFIGURATION,
                'delete_post'            => RoleCapabilitiesInterface::DELETE_CONFIGURATION,
                'edit_posts'             => RoleCapabilitiesInterface::MANAGE_CONFIGURATION,
                'edit_others_posts'      => RoleCapabilitiesInterface::MANAGE_CONFIGURATION,
                'publish_posts'          => RoleCapabilitiesInterface::MANAGE_CONFIGURATION,
                'read_private_posts'     => RoleCapabilitiesInterface::MANAGE_CONFIGURATION,
                'delete_posts'           => RoleCapabilitiesInterface::DELETE_CONFIGURATION,
                'delete_private_posts'   => RoleCapabilitiesInterface::DELETE_CONFIGURATION,
                'delete_published_posts' => RoleCapabilitiesInterface::DELETE_CONFIGURATION,
                'delete_others_posts'    => RoleCapabilitiesInterface::DELETE_CONFIGURATION,
                'edit_private_posts'     => RoleCapabilitiesInterface::MANAGE_CONFIGURATION,
                'edit_published_posts'   => RoleCapabilitiesInterface::MANAGE_CONFIGURATION,
            ],
            'map_meta_cap' => false,
        ];

        register_post_type(self::POST_TYPE, $args);
    }

    public function addCalendarMetaBox(): void
    {
        global $post;

        // Check if this is an existing post (has ID) or a new one
        if ($post && $post->post_status === 'auto-draft') {
            // New post - show information message
            add_meta_box(
                'bflex__rate_plan_info',
                __('Price calendar', 'bookiflex'),
                [$this, 'renderInfoMessage'],
                self::POST_TYPE,
                'normal',
                'high'
            );
        } else {
            // Existing post - show price calendar
            add_meta_box(
                'bflex__rate_plan_calendar',
                __('Price calendar', 'bookiflex'),
                [$this, 'renderCalendar'],
                self::POST_TYPE,
                'normal',
                'high'
            );
        }
    }

    public function renderCalendar(): void
    {
        echo "<div id='bflex-app--rate-plan-calendar-app'></div>";
    }

    public function renderInfoMessage(): void
    {
        echo '<div style="padding: 20px; background: #f0f6fc; border-left: 4px solid #0073aa; margin: 0;">';
        echo '<h3 style="margin-top: 0; color: #0073aa;">' . esc_html__('Price Calendar Setup', 'bookiflex') . '</h3>';
        echo '<p>' . esc_html__('The price calendar will be available after you save this rate plan. Please configure the basic settings below and save the draft or publish to start setting up your pricing.', 'bookiflex') . '</p>';
        echo '<p style="margin-bottom: 0;"><strong>' . esc_html__('Note:', 'bookiflex') . '</strong> ' . esc_html__('You can save as draft to preserve your work without making the rate plan publicly available.', 'bookiflex') . '</p>';
        echo '</div>';
    }
}
