<?php

namespace Dobare\Core;

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

class Dobare_Voorodak_Integration
{
    function __construct()
    {
        // Replace wp_login with more specific auth hooks
        add_action('set_auth_cookie', array($this, 'create_membership_from_voorodak_auth'), 10, 6);
        add_action('set_logged_in_cookie', array($this, 'create_membership_from_voorodak_auth'), 10, 6);
        add_action('user_register', array($this, 'create_membership_from_voorodak_registration'), 10, 1);
    }

    /**
     * Create membership when authentication cookies are set
     */
    function create_membership_from_voorodak_auth($auth_cookie, $expire, $expiration, $user_id, $scheme, $token)
    {
        $this->create_membership_from_voorodak($user_id);
    }

    /**
     * Create membership from registration
     */
    function create_membership_from_voorodak_registration($user_id)
    {
        $this->create_membership_from_voorodak($user_id);
    }

    /**
     * Create membership in Voorodak system
     */
    function create_membership_from_voorodak($user_id)
    {
        $phone_number = get_user_meta($user_id, 'billing_phone', true);
        $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);

        try {
            $customer = new WC_Customer($user_id, true);
            if (empty($user_name)) {
                $user_name = $customer->get_billing_first_name() . ' ' . $customer->get_billing_last_name();
            }
        } catch (Exception $e) {
            // Continue with empty user name if customer can't be loaded
        }

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