<?php
/**
 * GT BOGO Mobile Optimizer — Device Detection Script
 * Template: sets viewport/device/network cookies via JS.
 * Variables passed from GT_BOGO_Mobile_Optimizer::inject_detection_script()
 *   $cookie_viewport, $cookie_device, $cookie_network, $cookie_ttl, $vw_phone, $vw_tablet
 */
if ( ! defined( 'ABSPATH' ) ) exit;
?>
<script>
(function(){
    try {
        var c = function(name, value, days){
            var d = new Date(); d.setTime(d.getTime() + days*86400000);
            document.cookie = name + "=" + value + ";expires=" + d.toUTCString() + ";path=/;SameSite=Lax";
        };
        var has = function(name){
            return new RegExp("(^|; ?)" + name + "=").test(document.cookie);
        };

        // Viewport width
        var vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
        if (vw > 0) c("<?php echo esc_js( $cookie_viewport ); ?>", vw, <?php echo absint( $cookie_ttl ); ?>);

        // Device class
        var dc = vw <= <?php echo absint( $vw_phone ); ?> ? "phone"
               : (vw <= <?php echo absint( $vw_tablet ); ?> ? "tablet" : "desktop");
        c("<?php echo esc_js( $cookie_device ); ?>", dc, <?php echo absint( $cookie_ttl ); ?>);

        // Network class
        var nw = "fast";
        var conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
        if (conn) {
            if (conn.saveData)              nw = "save_data";
            else if (conn.effectiveType === "slow-2g" || conn.effectiveType === "2g")  nw = "slow";
            else if (conn.effectiveType === "3g")                                      nw = "medium";
            else                                                                       nw = "fast";
        }
        c("<?php echo esc_js( $cookie_network ); ?>", nw, <?php echo absint( $cookie_ttl ); ?>);
    } catch(e) { /* silent */ }
})();
</script>
