1<?php
2/**
3 * WHMCS Unified Tracking Hook
4 * Handles GTM, Google Ads Config, and Enhanced Purchase Conversions
5 * Records ALL conversions regardless of user age or history.
6 */
7
8use Illuminate\Database\Capsule\Manager as Capsule;
9
10// 1. Inject Tracking Scripts into the <head>
11add_hook('ClientAreaHeadOutput', 1, function($vars) {
12 return <<<HTML
13 <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
14 new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
15 j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
16 'https://www.googletagmanager.com/gtm.js?id=GTM-KFPNT7FS'+dl;f.parentNode.insertBefore(j,f);
17 })(window,document,'script','dataLayer','GTM-KFPNT7FS');</script>
18
19 <script async src="https://www.googletagmanager.com/gtag/js?id=AW-16687996918"></script>
20 <script>
21 window.dataLayer = window.dataLayer || [];
22 function gtag(){dataLayer.push(arguments);}
23 gtag('js', new Date());
24 // Enable Enhanced Conversions at the config level
25 gtag('config', 'AW-16687996918', {'allow_enhanced_conversions': true});
26 </script>
27HTML;
28});
29
30// 2. Handle the Purchase Event on the Checkout Complete Page
31add_hook('ShoppingCartCheckoutCompletePage', 1, function($vars) {
32 try {
33 $orderId = $vars['orderid'];
34
35 // Fetch order amount and full client details for Enhanced Conversions
36 $orderData = Capsule::table('tblorders')
37 ->join('tblclients', 'tblorders.userid', '=', 'tblclients.id')
38 ->where('tblorders.id', $orderId)
39 ->select('tblorders.amount', 'tblclients.currency', 'tblclients.email', 'tblclients.phonenumber', 'tblclients.postcode')
40 ->first();
41
42 if ($orderData) {
43 $amount = $orderData->amount;
44
45 // Get the 3-letter currency code (USD, etc.)
46 $currency = Capsule::table('tblcurrencies')
47 ->where('id', $orderData->currency)
48 ->value('code');
49
50 return <<<HTML
51 <script>
52 // A. DataLayer Push for GTM
53 window.dataLayer = window.dataLayer || [];
54 window.dataLayer.push({
55 'event': 'purchase_gemini',
56 'transaction_id': '{$orderId}',
57 'value': '{$amount}',
58 'currency': '{$currency}',
59 'user_email': '{$orderData->email}',
60 'user_phone': '{$orderData->phonenumber}',
61 'user_postcode': '{$orderData->postcode}'
62 });
63
64 // B. Direct Google Ads Conversion with FULL Enhanced Conversion Data
65 gtag('event', 'conversion', {
66 'send_to': 'AW-16687996918/DY9ECJi2yqcbEPa_upU-',
67 'value': '{$amount}',
68 'currency': '{$currency}',
69 'transaction_id': '{$orderId}',
70 'user_data': {
71 'email': '{$orderData->email}',
72 'phone_number': '{$orderData->phonenumber}',
73 'address': {
74 'postal_code': '{$orderData->postcode}'
75 }
76 }
77 });
78 </script>
79HTML;
80 }
81 } catch (\Exception $e) {
82 logActivity("Tracking Hook Error: " . $e->getMessage());
83 }
84});