<?php

namespace Devnet\EBC\Admin;

use Devnet\EBC\Includes\Helper;


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


class EditProduct
{

    private $plugin_name;
    private $version;
    private $booked_dates;

    public function __construct($plugin_name, $version)
    {

        $this->plugin_name = $plugin_name;
        $this->version     = $version;

        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('product_type_options', [$this, 'is_bookable_checkbox']);
        add_action('woocommerce_process_product_meta', [$this, 'save_custom_field']);

        // add_action('woocommerce_after_product_object_save', [$this, 'update_product'], 10, 2);
        add_filter('woocommerce_product_data_tabs', [$this, 'add_tab']);
        add_action('woocommerce_product_data_panels', [$this, 'add_tab_content']);
        //add_action('woocommerce_process_product_meta', [$this, 'save_easy_booking_calendar_field']);

        add_action('admin_head', [$this, 'custom_tab_icon_css']);
    }

    public function enqueue_assets($hook)
    {
        $is_bookable = false;

        if (
            $hook === 'post.php' &&
            isset($_GET['post']) &&
            get_post_type($_GET['post']) === 'product'
        ) {
            $post_id = absint($_GET['post']);

            $is_bookable = Helper::is_bookable($post_id);
        }

        if (!$is_bookable) return;

        global $post;
        $product_id = $post->ID;
        $this->booked_dates = Helper::get_booked_dates($product_id);

        return;

        $theme  = Helper::get_option('theme', 'calendar');
        $locale = Helper::get_option('locale', 'calendar');


        wp_enqueue_style($this->plugin_name, plugin_dir_url(__DIR__) . 'assets/build/admin-product.css', [], $this->version, 'all');

        if ($theme) {
            wp_enqueue_style($this->plugin_name . '-flatpickr-theme', plugin_dir_url(__DIR__) . 'assets/vendor/flatpickr/themes/' . esc_attr($theme) . '.css', [], $this->version, 'all');
        }

        $script_asset_path = plugin_dir_url(__DIR__) . 'assets/build/admin-product.asset.php';
        $script_info       = file_exists($script_asset_path)
            ? include $script_asset_path
            : ['dependencies' => ['jquery'], 'version' => $this->version];

        wp_enqueue_script(
            $this->plugin_name,
            plugin_dir_url(__DIR__) . 'assets/build/admin-product.js',
            $script_info['dependencies'],
            $script_info['version'],
            true
        );

        wp_localize_script($this->plugin_name, 'devnet_ebc_script_data', [
            'ajaxurl'      => admin_url('admin-ajax.php'),
            'nonce'        => wp_create_nonce('easy-booking-calendar-nonce'),
            'booked_dates' => $this->booked_dates,
            'options'      => DEVNET_EBC_OPTIONS['calendar']
        ]);

        if ($locale) {
            wp_enqueue_script(
                $this->plugin_name . '-flatpickr-locale',
                plugin_dir_url(__DIR__) . 'assets/vendor/flatpickr/l10n/' . esc_attr($locale) . '.js',
                [],
                $this->version,
                true
            );
        }
    }

    /**
     * Display the custom checkbox
     */
    public function is_bookable_checkbox($product_type_options)
    {
        $product_type_options['ebc_bookable'] = [
            'id'            => '_ebc_bookable',
            'label'         => esc_html__('Bookable', 'easy-booking-calendar'),
            'wrapper_class' => '',
            'description'   => esc_html__('Enable this option to turn the product into a bookable item', 'easy-booking-calendar'),
            'default'       => 'no'
        ];

        return $product_type_options;
    }

    /**
     * Save the custom field
     */
    public function save_custom_field($post_id)
    {
        $product = wc_get_product($post_id);

        $is_bookable = isset($_POST['_ebc_bookable']) ? 'yes' : 'no';
        $product->update_meta_data('_ebc_bookable', $is_bookable);

        $product->save();
    }


    public function add_tab($tabs)
    {

        global $post;

        if (Helper::is_bookable($post->ID)) {

            $tabs['easy_booking_calendar'] = [
                'label'    => __('Easy Booking Calendar', 'easy-booking-calendar'),
                'target'   => 'easy_booking_calendar_data',
                'class'    => ['easy_booking_calendar_tab'],
                'priority' => 0
            ];
        }

        return $tabs;
    }


    public function add_tab_content()
    {

        echo '<div id="easy_booking_calendar_data" class="panel woocommerce_options_panel">';
        echo '<div class="options_group">';


        if (!empty($this->booked_dates)) {

            // Get WP date format
            $wp_date_format = get_option('date_format');
            $today = new \DateTime();

            $options = DEVNET_EBC_OPTIONS['product'] ?? [];

            $mode = $options['booking_calculation_mode'] ?? 'nights';

            $mode_name = $mode === 'nights' ? __('Nights', 'easy-booking-calendar') : __('Days', 'easy-booking-calendar');


            // Output table
            echo '<table id="ebc-booked-dates" class="widefat striped">';
            echo '<thead><tr>';
            echo '<th>' . esc_html__('From', 'easy-booking-calendar') . '</th>';
            echo '<th>' . esc_html__('To', 'easy-booking-calendar') . '</th>';
            echo '<th>' . esc_html($mode_name) . '</th>';
            echo '<th>' . esc_html__('Order', 'easy-booking-calendar') . '</th>';
            echo '</tr></thead>';
            echo '<tbody>';

            foreach ($this->booked_dates as $props) {

                $_from = $props['from'] ?? '';
                $_to   = $props['to'] ?? '';

                if (!$_from || !$_to) {
                    continue;
                }

                $from = new \DateTime($_from);
                $to   = new \DateTime($_to);
                $diff = $from->diff($to)->days;

                if ($mode === 'days') {
                    $diff = $from->diff($to)->days + 1;
                }

                // Human-readable label
                if ($diff === 0) {
                    $label = 'Same day';
                } else {
                    $unit  = $mode === 'days' ? 'day' : 'night';
                    $label = $diff . ' ' . $unit . ($diff > 1 ? 's' : '');
                }

                // Check if "to" date has passed
                $is_past = $to < $today;
                $tr_style = $is_past ? ' style=opacity:0.5;' : '';

                $order_id = $props['order_id'] ?? null;
                $order = wc_get_order($order_id);

                echo '<tr ' . esc_attr($tr_style) . '>';
                echo '<td>' . esc_html($from->format($wp_date_format)) . '</td>';
                echo '<td>' . esc_html($to->format($wp_date_format)) . '</td>';
                echo '<td>' . esc_html($label) . '</td>';

                if ($order) {
                    echo '<td> <a href="' . $order->get_edit_order_url() . '" target="_blank">' . esc_html('#' . $order_id) . '</a></td>';
                } else {
                    echo '<td>-</td>';
                }
                echo '</tr>';
            }

            echo '</tbody></table>';
        }

        echo '<div id="ebc-wrapper" style="display:none;">';
        echo '<div class="ebc-inner">';
        echo '<input type="date" id="ebc-date-field" name="ebc_date_range" placeholder="' . esc_html__('Booked dates', 'easy-booking-calendar') . '" />';
        echo '</div>';
        echo '</div>';

        echo '</div>';
        echo '</div>';
    }

    public function custom_tab_icon_css()
    {
?>
        <style>
            #woocommerce-product-data ul.wc-tabs li.easy_booking_calendar_tab a:before {
                font-family: 'Dashicons';
                content: '\f145';
            }
        </style>
<?php
    }
}
