<?php

// Sing Wei API
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Content-Type: application/json");

// 1. Capture Dynamic Data
$external_id = $_REQUEST['user_id'] ?? null;
$event_type = $_REQUEST['event'] ?? null; 

// 2. Strict Validation & Mapping
// Stop the script if no user_id or event is provided
if (empty($external_id) || empty($event_type)) {
    die(json_encode(["status" => "ignored", "message" => "Missing user_id or event type."]));
}

if ($event_type === 'reg') {
    $meta_event = 'CompleteRegistration';
} elseif ($event_type === 'deposit') {
    $meta_event = 'Purchase';
} elseif ($event_type === 'start_trial') {
    $meta_event = 'StartTrial';
}  else {
    // Stop the script if the event name is not recognized
    die(json_encode(["status" => "ignored", "message" => "Invalid event name. Only 'reg', 'deposit', and 'start_trial' are accepted."]));
}

// Meta Credentials
$pixel_id = '940521795555137';
$access_token = 'EAANIY4AIk3ABRZAWbyOv9AQtIz0UpHDTyOnwrUZAaVgMV48VN1geZAFxIzfstlEuzDj33uItb7bAHScqfGyvhpODPCDEsYlwRVYtX07RGJoVu3ORt1W9CL2KMEMDOfsGN5sdsB3j38aVGR4Sihxd5noFovUrHZAJQ8EdvhOcRUI9M6OMLEIEEFn2MwJhVZCDDHwZDZD';

$event_time = time();
$client_ip = $_SERVER['REMOTE_ADDR'];
$client_user_agent = $_SERVER['HTTP_USER_AGENT'];
$event_source_url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

$url = "https://graph.facebook.com/v19.0/{$pixel_id}/events";

// 3. Prepare Event Data
$data = [
    'data' => [
        [
            'event_name' => $meta_event,
            'event_time' => $event_time,
            'user_data' => [
                'client_ip_address' => $client_ip,
                'client_user_agent' => $client_user_agent,
                'external_id' => hash('sha256', $external_id),
            ],
            'event_source_url' => $event_source_url,
            'action_source' => 'website',
        ],
    ],
    'access_token' => $access_token,
];

// 4. Send to Meta via cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>