<?php namespace Tussendoor\Reloadify\Concerns;

use Tussendoor\Reloadify\Helpers\HPOSHelper;
use Tussendoor\Reloadify\Models\SubscriptionCheckbox;

trait HasSubscriptionCheckbox
{

    /**
     * Save the checkbox selection from the correct location to the database
     * 
     * @since 1.5.0
     * 
     * @param int $order_id
     * @return void
     */
    public function saveSubscriptionCheckboxSelection(int $order_id)
    {
        if (did_action(current_filter()) > 1) return;

        if ($this->userWantsToAddCheckboxInCheckout()) {
            return $this->saveCheckoutCheckboxSelection($order_id);
        } 

        if ($this->userWantsToAddCheckboxInCart()) {
            return $this->saveCartCheckboxSelection($order_id);
        }
    }

    /**
     * Find the value of the checkbox in the checkout data and save it to the
     * database
     * 
     * @since 1.5.0
     * 
     * @param int $order_id
     * @return void
     */
    protected function saveCheckoutCheckboxSelection(int $order_id)
    {
        $value = isset($_POST[SubscriptionCheckbox::CONSENT_CHECKBOX_NAME]) ? '1' : '0';
        $this->saveCheckboxSelectionToDatabase($order_id, $value);
    }

    /**
     * Find the value of the checkbox in the cart data and save it to the
     * database
     * 
     * @since 1.5.0
     * 
     * @param int $order_id
     * @return void
     */
    protected function saveCartCheckboxSelection(int $order_id)
    {
        $value = '0';

        if (function_exists('WC') && !empty(WC()->session) && WC()->session->has_session()) {
            $value = WC()->session->get(SubscriptionCheckbox::CONSENT_CHECKBOX_SESSION_KEY, '0');
        }

        $this->saveCheckboxSelectionToDatabase($order_id, $value);
    }

    /**
     * Save the given consent value to the meta data of the order and the user
     * 
     * @since 1.5.0
     * 
     * @param int $order_id
     * @param string $value
     * @return void
     */
    protected function saveCheckboxSelectionToDatabase(int $order_id, string $value)
    {
        try {
            // Use HPOSHelper to update order meta, which handles both HPOS and legacy tables
            HPOSHelper::updateOrderMeta($order_id, SubscriptionCheckbox::CONSENT_CHECKBOX_NAME, $value);

            // Save it for the user as well
            if (get_current_user_id() > 0) {
                update_user_meta(get_current_user_id(), SubscriptionCheckbox::CONSENT_CHECKBOX_NAME, $value);
            }
        } catch (\Exception $e) {
            // Log the error
            HPOSHelper::logError('Failed to save subscription checkbox selection: ' . $e->getMessage());

            // Show admin notice if we're in the admin area
            if (is_admin()) {
                HPOSHelper::showAdminNotice(
                    __('Reloadify encountered an error saving subscription data. Please check the WooCommerce logs.', 'tsd-reloadify'),
                    'error'
                );
            }
        }
    }

    /**
     * Add a checkbox to the checkout page
     * 
     * @return void
     */
    public function addSubscriptionCheckbox()
    {
        if ($this->userWantsToAddCheckboxInThisLocation() === false) {
            return;
        }

        woocommerce_form_field(SubscriptionCheckbox::CONSENT_CHECKBOX_NAME, array(
           'type'          => 'checkbox',
           'class'         => array('form-row mycheckbox'),
           'label_class'   => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
           'input_class'   => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
           'label'         => esc_html($this->getCheckboxTextFromSettings()),
           'default'       => $this->getDefaultCheckboxStatusFromSettings(),
        ));    
    }

    /**
     * Check if the user wants to add a checkbox in this location
     * 
     * @return bool
     */
    protected function userWantsToAddCheckboxInThisLocation()
    {
        $userChosenLocation = get_option(SubscriptionCheckbox::CHECKBOX_LOCATION_SETTING, 'woocommerce_proceed_to_checkout');
        return $this->userWantsToAddCheckbox() && ($userChosenLocation === current_filter());
    }

    /**
     * Check if the user wants to add a checkbox in the checkout process
     * 
     * @return bool
     */
    protected function userWantsToAddCheckbox()
    {
        return get_option(SubscriptionCheckbox::ADD_CHECKBOX_SETTING, 'no') === 'yes';
    }

    /**
     * Check if the user wants to add a checkbox in the cart
     * 
     * @return bool
     */
    protected function userWantsToAddCheckboxInCart()
    {
        $userChosenLocation = get_option(SubscriptionCheckbox::CHECKBOX_LOCATION_SETTING, 'woocommerce_proceed_to_checkout');
        return $this->userWantsToAddCheckbox() && ($userChosenLocation === 'woocommerce_proceed_to_checkout');
    }

    /**
     * Check if the user wants to add a checkbox in the checkout
     * 
     * @return bool
     */
    protected function userWantsToAddCheckboxInCheckout()
    {
        $userChosenLocation = get_option(SubscriptionCheckbox::CHECKBOX_LOCATION_SETTING, 'woocommerce_proceed_to_checkout');
        $checkoutLocations  = ['woocommerce_checkout_before_terms_and_conditions', 'woocommerce_checkout_after_terms_and_conditions'];
        return $this->userWantsToAddCheckbox() && in_array($userChosenLocation, $checkoutLocations);
    }

    /**
     * Get the checkbox text from the settings
     * 
     * @return string
     */
    protected function getCheckboxTextFromSettings()
    {
        return get_option(SubscriptionCheckbox::CHECKBOX_LABEL_SETTING, __('Subscribe to our newsletter', 'reloadify'));
    }

    /**
     * Get the checkbox status from the settings
     * 
     * @return string
     */
    protected function getDefaultCheckboxStatusFromSettings()
    {
        $checked = get_option(SubscriptionCheckbox::CHECKBOX_STATUS_SETTING, 'unchecked') === 'checked';
        return $checked ? 1 : 0;
    }

}
