<?php
/**
 * @package CleverOgre
 * @subpackage woocommerce-download-template
 * @version 0.1.0
 * @since 0.1.0
 */

namespace WooCommerce\DownloadTemplate\Values;

defined('ABSPATH') || exit;

class User extends Appender {

    public function __construct() {
        $this->priority = 20;
        parent::__construct();
    }

    private function get_user_id($user_id = false):int {
        if (is_object($user_id)) {
            if (is_a($user_id, '\\WP_User')) {
                return intval($user_id->ID);
            } else if (is_a($user_id, '\\WC_Memberships_User_Membership')) {
                return intval($user_id->get_user_id());
            }
        }
        if (is_array($user_id) && isset($user_id['ID'])) return intval($user_id['ID']);
        if (is_string($user_id) && is_numeric($user_id)) return intval($user_id);
        if (is_int($user_id)) return $user_id;
        if (is_user_logged_in()) return get_current_user_id();
        return null;
    }
    private function get_userdata($user_id = false):\WP_User {
        $user_id = $this->get_user_id($user_id);
        if (!is_int($user_id)) return null;

        $userdata = get_userdata($user_id);
        if (!is_a($userdata, '\\WP_User')) return null;
        return $userdata;
    }

    public function get_default_args(array $args = []):array {
        $args['user_id'] = $this->get_user_id();
        return $args;
    }
    public function validate_args(array $args = []):array {
        $args['user_id'] = $this->get_user_id(isset($args['user_id']) ? $args['user_id'] : false);
        return $args;
    }

    public function get(array $values = [], array $args = []):array {
        $user_id = $this->get_user_id(isset($args['user_id']) ? $args['user_id'] : false);
        if (!is_int($user_id)) return [];

        $userdata = $this->get_userdata($user_id);
        if (is_null($userdata)) return [];

        $_values = [
            'name' => $userdata->display_name,
            'fullname' => $userdata->display_name,
            'first_name' => $userdata->first_name,
            'last_name' => $userdata->last_name,
            'email' => $userdata->user_email,
        ];

        $_values = array_merge($_values, $this->get_address($userdata, 'billing_'));
        $_values = array_merge($_values, $this->get_address($userdata, 'shipping_'));

        $_values = array_merge($_values, $this->get_meta($userdata));

        return array_merge($values, apply_filters('wc_download_template_user_values', $_values, $user_id, $userdata));
    }

    public function get_example(array $values = []):array {
        return array_merge($values, $this->get());
    }

    private function get_address(\WP_User $userdata, string $type = 'billing_'):array {
        $country = get_user_meta($userdata->ID, "{$type}country", true);
        if (!$country) $country = WC()->countries->get_base_country();

        $allowed_countries = WC()->countries->get_allowed_countries();
        if (!array_key_exists($country, $allowed_countries)) $country = current(array_keys($allowed_countries));

        $address_fields = WC()->countries->get_address_fields($country, $type);
        $values = [];
        foreach ($address_fields as $key => $field) {
            $value = get_user_meta($userdata->ID, $key, true);
            if (!$value) {
                switch ($key) {
                    case "{$type}first_name":
                        $value = $userdata->first_name;
                        break;
                    case "{$type}last_name":
                        $value = $userdata->last_name;
                        break;
        			case "{$type}email":
        				$value = $userdata->user_email;
        				break;
        		}
            }
            $values[$key] = $value;
        }

        $values["{$type}fulladdress"] = trim(sprintf(
            '%s, %s, %s %s',
            trim(sprintf('%s %s', $values["{$type}address_1"], $values["{$type}address_2"])),
            $values["{$type}city"],
            $values["{$type}state"],
            $values["{$type}postcode"]
        ), ' \n\r\t\v\x00,');

        return apply_filters('wc_download_template_user_address_values', $values, $userdata->ID, $userdata, $type);
    }

    private function get_meta_keys():array {
        return apply_filters('wc_download_template_user_meta_keys', []);
    }
    private function get_meta(\WP_User $userdata):array {
        if (!function_exists('get_field')) return [];

        $meta_keys = $this->get_meta_keys();
        if (empty($meta_keys)) return [];

        $values = [];
        foreach ($meta_keys as $meta_key) {
            $value = get_user_meta($userdata->ID, $meta_key, true);
            if (!$value) $value = '';
            $values[$meta_key] = strval($value);
        }

        return apply_filters('wc_download_template_user_meta_values', $values, $userdata->ID, $userdata);
    }

}

User::instance();
