CartAbandoned.php
83 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\Reach\Api\Webhooks\Handlers; |
| 4 | |
| 5 | use Hostinger\Reach\Api\Handlers\IntegrationsApiHandler; |
| 6 | use Hostinger\Reach\Api\Handlers\ReachApiHandler; |
| 7 | use Hostinger\Reach\Models\Cart; |
| 8 | use Hostinger\Reach\Dto\Cart as CartDto; |
| 9 | use Hostinger\Reach\Repositories\CartRepository; |
| 10 | use Hostinger\Reach\Repositories\FormRepository; |
| 11 | use Hostinger\Reach\Tracking\RestoreCart; |
| 12 | use WC_Customer; |
| 13 | use Exception; |
| 14 | |
| 15 | class CartAbandoned extends WebhookHandler { |
| 16 | const WEBHOOK_NAME = 'cart.abandoned'; |
| 17 | |
| 18 | private CartRepository $cart_repository; |
| 19 | private IntegrationsApiHandler $integrations_api_handler; |
| 20 | |
| 21 | public function __construct( ReachApiHandler $reach_api_handler, IntegrationsApiHandler $integrations_api_handler, CartRepository $cart_repository, FormRepository $form_repository ) { |
| 22 | parent::__construct( $reach_api_handler, $form_repository ); |
| 23 | $this->integrations_api_handler = $integrations_api_handler; |
| 24 | $this->cart_repository = $cart_repository; |
| 25 | } |
| 26 | |
| 27 | public function get_name(): string { |
| 28 | return self::WEBHOOK_NAME; |
| 29 | } |
| 30 | |
| 31 | public function get_metadata( mixed $data ): array { |
| 32 | if ( ! $data instanceof CartDto ) { |
| 33 | return array(); |
| 34 | } |
| 35 | |
| 36 | $metadata = $data->to_array(); |
| 37 | $metadata['restore_url'] = RestoreCart::get_restore_url( $data->get_hash() ); |
| 38 | |
| 39 | return $metadata; |
| 40 | } |
| 41 | |
| 42 | public function send( string $cart_hash ): void { |
| 43 | try { |
| 44 | $cart = $this->cart_repository->get( $cart_hash ); |
| 45 | $email = $this->get_customer_email( $cart ); |
| 46 | if ( $email ) { |
| 47 | $result = $this->handle( $email, CartDto::from_array( $cart ) ); |
| 48 | if ( $result ) { |
| 49 | $this->cart_repository->set_status( $cart_hash, Cart::STATUS_ABANDONED ); |
| 50 | } else { |
| 51 | $this->cart_repository->set_status( $cart_hash, Cart::STATUS_ERROR ); |
| 52 | } |
| 53 | } |
| 54 | } catch ( Exception $e ) { |
| 55 | return; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | public function get_customer_email( array $cart ): string { |
| 60 | if ( isset( $cart['customer_email'] ) && $cart['customer_email'] ) { |
| 61 | return $cart['customer_email']; |
| 62 | } |
| 63 | |
| 64 | $customer_id = $cart['customer_id'] ?? null; |
| 65 | |
| 66 | if ( $customer_id > 0 ) { |
| 67 | $customer = new WC_Customer( $customer_id ); |
| 68 | |
| 69 | return $customer->get_email(); |
| 70 | } |
| 71 | |
| 72 | return ''; |
| 73 | } |
| 74 | |
| 75 | public function is_enabled(): bool { |
| 76 | return parent::is_enabled() && $this->integrations_api_handler->is_active( 'woocommerce' ); |
| 77 | } |
| 78 | |
| 79 | public function init_hooks(): void { |
| 80 | return; |
| 81 | } |
| 82 | } |
| 83 |