<?php

namespace Dobare\Core;

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

class Dobare_Mobits_Integration
{
    function __construct()
    {
        add_action("dlr_after_login", array($this, 'create_membership_from_mobits'), 10, 1);
        add_action('dlr_after_create_user', array($this, 'create_membership_from_mobits_user_meta'), 10, 1);
    }

    function create_membership_from_mobits($user)
    {
        if ($user) {
            $this->create_membership_from_mobits_user_meta($user->ID);
        }
    }

    function create_membership_from_mobits_user_meta($user_id)
    {
        $phone_number = get_user_meta($user_id, 'mobits_mobile_number', true);
        $normalized_phone = Dobare_Utils::validate_and_normalize_phone_number($phone_number);

        if (empty($normalized_phone)) {
            $phone_number = get_user_meta($user_id, 'mobits_mobile', true);
            $normalized_phone = Dobare_Utils::validate_and_normalize_phone_number($phone_number);

            if (empty($normalized_phone)) {
                // Fall back to WooCommerce customer data
                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) && !empty($customer)) {
            $user_name = $customer->get_billing_first_name() . ' ' . $customer->get_billing_last_name();
        }
        if (empty($user_name)) {
            $user_name = '';
        }

        $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;
        }
    }
}
