<?php

namespace Vendtics\App\Providers;

defined( "ABSPATH" ) || exit;

use Vendtics\WpMVC\Contracts\Provider;
use Vendtics\WpMVC\Exceptions\Exception;
use stdClass;

class WooCommerceServiceProvider implements Provider {
    public function boot() {
        add_filter( 'vendtics_single_contact', [$this, 'single_contact'] );
    }

    public function single_contact( stdClass $contact ) {
        $user = get_user_by( 'email', $contact->email );

        if ( ! $user ) {
            return $contact;
        }
    
        // Get user ID from email
        $user_id = $user->ID;
    
        // Get all completed orders for the user
        $orders = wc_get_orders(
            [
                'customer_id' => $user_id,
                'status'      => 'completed',
                'limit'       => -1, // Retrieve all completed orders
            ] 
        );
    
        $lifetime_order_amount = 0;
        $last_order_amount     = 0;
        $total_orders          = 0;
    
        // Calculate lifetime total
        foreach ( $orders as $order ) {
            $lifetime_order_amount += $order->get_total();
            $total_orders++;
        }
    
        // Get the last completed order
        if ( ! empty( $orders ) ) {
            $last_order        = end( $orders );
            $last_order_amount = $last_order->get_total();
        }

        $contact->last_order_amount     += $last_order_amount;
        $contact->lifetime_order_amount += $lifetime_order_amount;
        $contact->total_orders          += $total_orders;

        return $contact;
    }
}