<?php

namespace Dobare\Core;

use Dobare\Abstracts\Dobare_REST_Controller;
use Dobare\Utils\Dobare_Utils;
use Exception;
use WC_Customer;

class Dobare_Digits_Integration
{
	function __construct()
	{
		add_action("updated_user_meta", array($this, 'create_membership_from_digits_user_meta'), 10, 4);
		add_action("added_user_meta", array($this, 'create_membership_from_digits_user_meta'), 10, 4);
		add_action('wp_login', array($this, 'create_membership_from_digits_wp_login'), 10, 2);
	}

	function create_membership_from_digits_user_meta($meta_id, $user_id, $meta_key, $meta_value)
	{
		if ('digits_phone' === $meta_key || 'digits_phone_no' === $meta_key) {
			$this->create_membership_from_digits($user_id);
		}
	}

	function create_membership_from_digits_wp_login($user_login, $user)
	{
		if ($user) {
			$this->create_membership_from_digits($user->ID);
		}
	}

	function create_membership_from_digits($user_id)
	{

		$phone_number     = get_user_meta($user_id, 'digits_phone', true);
		$normalized_phone = Dobare_Utils::validate_and_normalize_phone_number($phone_number);
		if (empty($normalized_phone)) {
			$phone_number     = get_user_meta($user_id, 'digits_phone_no', true);
			$normalized_phone = Dobare_Utils::validate_and_normalize_phone_number($phone_number);
			if (empty($normalized_phone)) {
				try {
					$customer = new WC_Customer($user_id, true);
				} catch (Exception $e) {
					return;
				}
				$phone_number     = $customer->get_billing_phone() ?: $customer->get_shipping_phone();
				$normalized_phone = Dobare_Utils::validate_and_normalize_phone_number($phone_number);
			}
		}

		if (empty($normalized_phone)) {
			if (! empty($phone_number)) {
				$normalized_phone = $phone_number;
			} else {
				return;
			}
		}
		$user = get_userdata($user_id);
		$user_name = trim($user->first_name . ' ' . $user->last_name);
		if (empty($user_name) and ! empty($customer)) {
			$user_name = $customer->get_billing_first_name() . ' ' . $customer->get_billing_last_name();
		}
		if (empty($user_name)) {
			$user_name  = ''; # empty the username field fully even from whitespaces
		}
		$member_body = Dobare_Core::build_member_request_body($normalized_phone, $user_name);

		$api_key = Dobare_Utils::get_dob_api_key();
		if (! empty($api_key)) {
			Dobare_REST_Controller::dobare_remote_post('v1/members/', $member_body, ['API-KEY' => $api_key]);
		}

		try {
			$customer = new WC_Customer($user_id, true);
			if (empty($customer->get_billing_phone())) {
				$customer->set_billing_phone($phone_number);
				$customer->save();
			}
		} catch (Exception $e) {
			return;
		}
	}
}
