<?php
// includes/facebook-pixel.php
// Meta Pixel Integration with Conversion API

// Check if constants are defined, if not define them
if (!defined('FACEBOOK_PIXEL_ID')) {
    define('FACEBOOK_PIXEL_ID', '');
}
if (!defined('FACEBOOK_ACCESS_TOKEN')) {
    define('FACEBOOK_ACCESS_TOKEN', '');
}
if (!defined('FACEBOOK_CAPI_ENABLED')) {
    define('FACEBOOK_CAPI_ENABLED', false);
}
if (!defined('FACEBOOK_PIXEL_TEST_CODE')) {
    define('FACEBOOK_PIXEL_TEST_CODE', '');
}

if (!function_exists('getClientIp')) {
    function getClientIp() {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if(isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;
    }
}

if (!function_exists('getBrowserInfo')) {
    function getBrowserInfo() {
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $browser = 'Unknown';
        $os = 'Unknown';
        
        if (strpos($user_agent, 'Chrome') !== false) $browser = 'Chrome';
        elseif (strpos($user_agent, 'Firefox') !== false) $browser = 'Firefox';
        elseif (strpos($user_agent, 'Safari') !== false) $browser = 'Safari';
        elseif (strpos($user_agent, 'Edge') !== false) $browser = 'Edge';
        elseif (strpos($user_agent, 'Opera') !== false) $browser = 'Opera';
        
        if (strpos($user_agent, 'Windows') !== false) $os = 'Windows';
        elseif (strpos($user_agent, 'Mac') !== false) $os = 'Mac';
        elseif (strpos($user_agent, 'Linux') !== false) $os = 'Linux';
        elseif (strpos($user_agent, 'Android') !== false) $os = 'Android';
        elseif (strpos($user_agent, 'iPhone') !== false) $os = 'iOS';
        
        return ['browser' => $browser, 'os' => $os];
    }
}

if (!function_exists('getFbc')) {
    function getFbc() {
        $fbc = $_COOKIE['_fbc'] ?? null;
        if (!$fbc && isset($_GET['fbclid'])) {
            $fbc = 'fb.1.' . time() . '.' . $_GET['fbclid'];
            setcookie('_fbc', $fbc, time() + 7776000, '/', '', false, true);
        }
        return $fbc;
    }
}

if (!function_exists('getFbp')) {
    function getFbp() {
        $fbp = $_COOKIE['_fbp'] ?? null;
        if (!$fbp) {
            $fbp = 'fb.1.' . time() . '.' . rand(1000000000, 9999999999);
            setcookie('_fbp', $fbp, time() + 7776000, '/', '', false, true);
        }
        return $fbp;
    }
}

if (!function_exists('getExternalId')) {
    function getExternalId() {
        $external_id = $_SESSION['external_id'] ?? null;
        if (!$external_id) {
            $external_id = bin2hex(random_bytes(16));
            $_SESSION['external_id'] = $external_id;
        }
        return $external_id;
    }
}

if (!function_exists('sendFacebookCAPI')) {
    function sendFacebookCAPI($event_name, $event_data = [], $custom_data = []) {
        global $pdo;
        
        // Check if Pixel ID and Access Token are set
        $pixel_id = FACEBOOK_PIXEL_ID;
        $access_token = FACEBOOK_ACCESS_TOKEN;
        
        if (empty($pixel_id) || empty($access_token)) {
            error_log("Facebook CAPI: Pixel ID or Access Token missing");
            return false;
        }
        
        $ip = getClientIp();
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $browser_info = getBrowserInfo();
        $fbc = getFbc();
        $fbp = getFbp();
        $external_id = getExternalId();
        
        // Build user data
        $user_data = [
            'client_ip_address' => $ip,
            'client_user_agent' => $user_agent,
            'fbc' => $fbc,
            'fbp' => $fbp,
            'external_id' => $external_id,
        ];
        
        // Add email and phone if provided
        if (isset($event_data['email']) && !empty($event_data['email'])) {
            $user_data['em'] = hash('sha256', $event_data['email']);
        }
        if (isset($event_data['phone']) && !empty($event_data['phone'])) {
            $user_data['ph'] = hash('sha256', $event_data['phone']);
        }
        
        // Build event data
        $data = [
            'event_name' => $event_name,
            'event_time' => time(),
            'event_source_url' => $event_data['url'] ?? (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'],
            'action_source' => 'website',
            'user_data' => array_filter($user_data),
            'custom_data' => $custom_data,
        ];
        
        // Add test code if set
        if (FACEBOOK_PIXEL_TEST_CODE) {
            $data['test_event_code'] = FACEBOOK_PIXEL_TEST_CODE;
        }
        
        // Send to Facebook API
        $url = "https://graph.facebook.com/v18.0/" . $pixel_id . "/events?access_token=" . $access_token;
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['data' => [$data]]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // Log the response for debugging
        error_log("Facebook CAPI Response: " . $response . " | Event: " . $event_name);
        
        return $http_code == 200;
    }
}

if (!function_exists('trackFacebookEvent')) {
    function trackFacebookEvent($event_name, $custom_data = [], $user_data = []) {
        global $pdo;
        
        $pixel_id = FACEBOOK_PIXEL_ID;
        
        // Track with Pixel (Client-side)
        if (!empty($pixel_id)) {
            $event_id = uniqid('event_');
            ?>
            <script>
            if (typeof fbq !== 'undefined') {
                fbq('track', '<?php echo $event_name; ?>', <?php echo json_encode($custom_data); ?>, {eventID: '<?php echo $event_id; ?>'});
            }
            </script>
            <?php
        }
        
        // Track with CAPI (Server-side)
        if (FACEBOOK_CAPI_ENABLED && !empty(FACEBOOK_ACCESS_TOKEN)) {
            sendFacebookCAPI($event_name, $user_data, $custom_data);
        }
    }
}
?>