<?php
/** no direct access **/
defined('MECEXEC') or die();

/**
 * Webnus MEC WooCommerce class.
 * @author Webnus <info@webnus.biz>
 */
class MEC_feature_wc extends MEC_base
{
    /**
     * @var MEC_factory
     */
    public $factory;

    /**
     * @var MEC_main
     */
    public $main;

    /**
     * @var array
     */
    public $settings;

    /**
     * Constructor method
     * @author Webnus <info@webnus.biz>
     */
    public function __construct()
    {
        // Import MEC Factory
        $this->factory = $this->getFactory();
        
        // Import MEC Main
        $this->main = $this->getMain();

        // General Options
        $this->settings = $this->main->get_settings();
    }
    
    /**
     * Initialize
     * @author Webnus <info@webnus.biz>
     */
    public function init()
    {
        // Pro version is required
        if(!$this->getPRO()) return false;

        // WC Hooks
        $this->factory->action('init', array($this, 'hooks'));
    }

    public function hooks()
    {
        // WC System
        $WC_status = (isset($this->settings['wc_status']) and $this->settings['wc_status'] and class_exists('WooCommerce')) ? true : false;

        // WC system is disabled
        if(!$WC_status) return false;

        // WC library
        $wc = $this->getWC();

        // WooCommerce
        $this->factory->action('woocommerce_order_status_completed', array($wc, 'completed'), 10, 1);
        $this->factory->action('woocommerce_thankyou', array($wc, 'paid'), 10, 1);
        $this->factory->action('woocommerce_new_order_item', array($wc, 'meta'), 10, 2);
        $this->factory->action('woocommerce_order_status_cancelled', array($wc, 'cancelled'), 10, 1);
        $this->factory->action('woocommerce_order_status_refunded', array($wc, 'cancelled'), 10, 1);
        $this->factory->action('woocommerce_after_checkout_validation', array($this, 'validate'),10,2);

        $this->factory->filter('woocommerce_order_item_display_meta_key', array($this, 'display_key'), 10, 2);
        $this->factory->filter('woocommerce_order_item_display_meta_value', array($this, 'display_value'), 10, 2);
        $this->factory->filter('woocommerce_cart_item_name', array($this, 'display_name'), 10, 2);
        $this->factory->filter('woocommerce_cart_item_thumbnail', array($this, 'display_thumbnail'), 10, 2);
    }

    public function display_key($display_key, $meta)
    {
        if($meta->key == 'mec_event_id') $display_key = __('Event', 'mec');
        elseif($meta->key == 'mec_date') $display_key = __('Date', 'mec');
        elseif($meta->key == 'mec_transaction_id') $display_key = __('Transaction ID', 'mec');

        return $display_key;
    }

    public function display_value($display_value, $meta)
    {
        if($meta->key == 'mec_event_id') $display_value = '<a href="'.get_permalink($meta->value).'">'.get_the_title($meta->value).'</a>';
        elseif($meta->key == 'mec_transaction_id') $display_value = $meta->value;
        elseif($meta->key == 'mec_date')
        {
            $date_format = (isset($this->settings['booking_date_format1']) and trim($this->settings['booking_date_format1'])) ? $this->settings['booking_date_format1'] : 'Y-m-d';
            $time_format = get_option('time_format');

            $dates = explode(':', $meta->value);

            $start_datetime = date($date_format.' '.$time_format, $dates[0]);
            $end_datetime = date($date_format.' '.$time_format, $dates[1]);

            $display_value = sprintf(__('%s to %s', 'mec'), $start_datetime, $end_datetime);
        }

        return $display_value;
    }

    public function display_name($name, $item)
    {
        if(!isset($item['mec_event_id']) or (isset($item['mec_event_id']) and !trim($item['mec_event_id']))) return $name;
        if(!isset($item['mec_date']) or (isset($item['mec_date']) and !trim($item['mec_date']))) return $name;

        $timestamps = explode(':', $item['mec_date']);

        $date_format = (isset($this->settings['booking_date_format1']) and trim($this->settings['booking_date_format1'])) ? $this->settings['booking_date_format1'] : get_option('date_format');
        $start_date = date($date_format, $timestamps[0]);

        $name .= ' ('.$start_date.')';
        return $name;
    }

    public function display_thumbnail($image, $item)
    {
        if(!isset($item['mec_event_id']) or (isset($item['mec_event_id']) and !trim($item['mec_event_id']))) return $image;
        if(!isset($item['product_id']) or (isset($item['product_id']) and !trim($item['product_id']))) return $image;

        $product_id = $item['product_id'];
        if(has_post_thumbnail($product_id)) return $image;

        $event_id = $item['mec_event_id'];
        if(has_post_thumbnail($event_id)) return get_the_post_thumbnail($event_id);

        return $image;
    }

    public function validate($data, $errors)
    {
        // Cart Items
        $items = WC()->cart->get_cart();

        // Book
        $book = $this->getBook();

        foreach($items as $key => $item)
        {
            $event_id = (isset($item['mec_event_id']) ? $item['mec_event_id'] : NULL);

            if(!$event_id) continue;

            $product_id = (isset($item['product_id']) ? $item['product_id'] : NULL);
            $mec_ticket = get_post_meta($product_id, 'mec_ticket', true);

            $ex = explode(':', $mec_ticket);
            $ticket_id = (isset($ex[1]) ? $ex[1] : NULL);

            if(!$ticket_id) continue;

            $date = (isset($item['mec_date']) ? $item['mec_date'] : NULL);
            $ex = explode(':', $date);
            $timestamps = $ex[0];

            $quantity = (isset($item['quantity']) ? $item['quantity'] : 1);
            $availability = $book->get_tickets_availability($event_id, $timestamps);

            $tickets = get_post_meta($event_id, 'mec_tickets', true);

            // Ticket is not available
            if(!isset($availability[$ticket_id]) or (isset($availability[$ticket_id])) and $availability[$ticket_id] < $quantity)
            {
                if($availability[$ticket_id] == '0') $errors->add('validation', sprintf(__('%s ticket is sold out!', 'mec'), $tickets[$ticket_id]['name']));
                else $errors->add('validation', sprintf(__('Only %s slots remained for %s ticket so you cannot book %s ones.', 'mec'), $availability[$ticket_id], $tickets[$ticket_id]['name'], $quantity));
            }
        }
    }
}