<?php

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


/**
 * insert event into database
 *
 * @param  array $data
 * @return mixed
 */
function salesloo_insert_event($data = [])
{
    $data = apply_filters('salelsoo/event/insert/data', $data);

    if (empty($data) || !is_array($data)) return false;

    $event_args = [];

    foreach (Salesloo\Models\Event::get_columns() as $key => $type) {

        if (isset($data[$key])) {
            $event_args[$key] = $data[$key];
        }
    }

    return Salesloo\Models\Event::data($event_args)->create();
}

function salesloo_add_event($name, $data)
{
    return salesloo_insert_event([
        'name' => sanitize_text_field($name),
        'data' => $data
    ]);
}

/**
 * salesloo_executed_event
 *
 * @param  integer $event_id
 * @return void
 */
function salesloo_executed_event($event_id)
{
    Salesloo\Models\Event::data(
        ['executed_at' => date('Y-m-d H:i:s')]
    )->update([
        'ID' => intval($event_id)
    ]);
}


function salesloo_execute_custom_autoresponder($form, $customer)
{
    foreach ((array)$form as $data) {
        $body = [
            'email' => $customer->user_email
        ];

        if (!isset($data['action'])) continue;

        if (isset($data['fields'])) {
            foreach ((array)$data['fields'] as $key => $name) {
                if ($name == 'email') continue;
                if ($name == 'full_name' || $name == 'name') {
                    $body[$name] = salesloo_user_get_name($customer);
                }

                if ($name == 'last_name') {
                    $body[$name] = $customer->last_name;
                }

                if ($name == 'first_name') {
                    $body[$name] = $customer->first_name;
                }

                if (in_array($name, ['phone', 'mobile', 'ponsel'])) {
                    $body[$name] = get_user_meta($customer->ID, 'phone', true);
                }
            }
        }

        if (isset($data['method']) && $data['method'] == 'post') {
            $s = wp_remote_post(
                $data['action'],
                array(
                    'method'      => 'POST',
                    'body'        => $body,
                )
            );
        } else {
            $target = add_query_arg($body, $data['action']);
            $s = wp_remote_get($target);
        }
    }
}
