<?php

namespace Booktics\Customer\Handlers;

if ( ! defined( 'ABSPATH' ) ) exit;

use Booktics\Models\Customer_Model;

class Customer_Event_Handler {

    /**
     * Send invitation mail on customer creation
     *
     * @param $customer_id
     *
     * @return bool
     */
    public function on_customer_create( $customer_id ) {
        $customer = ( new Customer_Model() )->find( $customer_id );
        $user     = get_user_by( 'ID', $customer_id );
        $reset_key = get_password_reset_key( $user );
        $reset_url = network_site_url( "wp-login.php?action=rp&key=$reset_key&login=" . rawurlencode( $user->user_login ), 'login' );

        add_filter(
            'notification_sdk_email_body', array(
            $this,
            'wrap_email_body',
        ), 10, 1
        );
        do_action(
            'booktics_gln_hook', 'customer_created', array(
                'customer_first_name' => $customer->first_name,
                'customer_last_name'  => $customer->last_name,
                'customer_full_name'  => $customer->display_name,
                'customer_phone'      => $customer->phone,
                'customer_user_name'  => $customer->user_login,
                'customer_email'      => $customer->user_email,
                'password_reset_url'  => $reset_url,
            )
        );

        return true;
    }


    /**
     * Wrap email body content with template and replace variables
     *
     * @param string $message Email body content to be wrapped
     *
     * @return string Modified email body content with template applied
     */
    public function wrap_email_body( $message ) {

        $template_path = BOOKTICS_DIR . '/templates/email/team-member-create.html';

        if ( ! file_exists( $template_path ) ) {
            return $message;
        }
        $template      = file_get_contents( $template_path );
        $default_image = get_template_directory_uri() . '/assets/images/placeholder.jpg';
        $variables     = array(
            '{{MESSAGE}}'         => wp_kses_post( $message ),
            '{{COMPANY_NAME}}'    => booktics_get_option( 'business_name', 'Booktics' ),
            '{{COMPANY_LOGO}}'    => booktics_get_option( 'business_logo', $default_image ),
            '{{COMPANY_ADDRESS}}' => booktics_get_option( 'business_address', 'California, USA' ),
        );

        return str_replace( array_keys( $variables ), array_values( $variables ), $template );
    }
}
