<?php

namespace Salesloo;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

/**
 * Event
 */
class Events
{
    public function run()
    {
        $events = \Salesloo\Models\Event::query('WHERE executed_at IS NULL')->paginate(10)->get();

        foreach ($events as $event) {

            if ($event->name == 'place_order') {
                $this->execute_custom_autoresponder_on_place_order_event($event->data);
            } elseif ($event->name == 'invoice_completed') {
                $this->execute_custom_autoresponder_on_invoice_completed_event($event->data);
            }

            do_action('salesloo/event/' . $event->name, $event->data);

            salesloo_executed_event($event->ID);
        }
    }

    /**
     * execute_custom_autoresponder_on_place_order_event
     *
     * @param  mixed $args
     * @return void
     */
    public function execute_custom_autoresponder_on_place_order_event($args)
    {
        $invoice_id = isset($args['invoice_id']) ? intval($args['invoice_id']) : 0;
        $invoice = salesloo_get_invoice($invoice_id);

        if (!$invoice) return;

        $orders = $invoice->orders();

        foreach ($orders as $order) {
            $product = salesloo_get_product($order->product_id);
            $autoresponder_service_provider = $product->meta('autoresponder_service_provider');

            if ($autoresponder_service_provider == 'custom') {
                $form_data = $product->meta('custom_autoresponder_on_place_order_event');

                $customer = get_userdata($order->user_id);

                salesloo_execute_custom_autoresponder($form_data, $customer);
            }
        }
    }

    /**
     * execute_custom_autoresponder_on_invoice_completed_event
     *
     * @param  mixed $args
     * @return void
     */
    public function execute_custom_autoresponder_on_invoice_completed_event($args)
    {
        $invoice_id = isset($args['invoice_id']) ? intval($args['invoice_id']) : 0;
        $invoice = salesloo_get_invoice($invoice_id);

        if (!$invoice) return;

        $orders = $invoice->orders();

        foreach ($orders as $order) {
            $product = salesloo_get_product($order->product_id);
            $autoresponder_service_provider = $product->meta('autoresponder_service_provider');

            if ($autoresponder_service_provider == 'custom') {
                $form_data = $product->meta('custom_autoresponder_on_invoice_completed_event');

                $customer = get_userdata($order->user_id);

                salesloo_execute_custom_autoresponder($form_data, $customer);
            }
        }
    }

    /**
     * __construct
     *
     * @return void
     */
    public function __construct()
    {
        add_action('salesloo/cron/minute', [$this, 'run']);
    }
}
