<?php
/**
 * analytics_head() — snippets para el <head> de landing/app
 * analytics_body_start() — snippets post-<body> (GTM noscript, PostHog init)
 */

function analytics_head(bool $is_app = false): void {
    // Microsoft Clarity
    $clarity = defined('CLARITY_PROJECT_ID') ? CLARITY_PROJECT_ID : '';
    if ($clarity): ?>
<script type="text/javascript">
(function(c,l,a,r,i,t,y){c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y)})(window,document,"clarity","script","<?=htmlspecialchars($clarity)?>");
</script>
<?php endif;

    // GA4
    $ga4 = defined('GA4_MEASUREMENT_ID') ? GA4_MEASUREMENT_ID : '';
    if ($ga4 && !$is_app): ?>
<script async src="https://www.googletagmanager.com/gtag/js?id=<?=htmlspecialchars($ga4)?>"></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag('js',new Date());gtag('config','<?=htmlspecialchars($ga4)?>');</script>
<?php endif;

    // PostHog (solo en app)
    $posthog = defined('POSTHOG_API_KEY') ? POSTHOG_API_KEY : '';
    if ($posthog && $is_app): ?>
<script>!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]);t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+" (stub)"},o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags addEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init('<?=htmlspecialchars($posthog)?>',{api_host:'https://app.posthog.com'});</script>
<?php endif;
}

/**
 * analytics_identify(array $user) — identifica usuario en PostHog y Crisp después del login
 */
function analytics_identify(array $user): string {
    $posthog = defined('POSTHOG_API_KEY') ? POSTHOG_API_KEY : '';
    $crisp   = defined('CRISP_WEBSITE_ID') ? CRISP_WEBSITE_ID : '';
    $js = '';

    if ($posthog) {
        $uid   = (int)$user['id'];
        $email = addslashes($user['email'] ?? '');
        $name  = addslashes($user['name'] ?? '');
        $plan  = addslashes($user['plan'] ?? 'trial');
        $js .= "if(window.posthog)posthog.identify($uid,{email:'$email',name:'$name',plan:'$plan'});";
    }

    if ($crisp) {
        $email = addslashes($user['email'] ?? '');
        $name  = addslashes($user['name'] ?? '');
        $plan  = addslashes($user['plan'] ?? 'trial');
        $js .= "if(window.\$crisp){\$crisp.push(['set','user:email',['$email']]);\$crisp.push(['set','user:nickname',['$name']]);\$crisp.push(['set','session:segments',[['$plan']]]);}";
    }

    return $js ? "<script>$js</script>" : '';
}
