( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ HEX
HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux mail.thebrand.ai 6.8.0-107-generic #107-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 13 19:51:50 UTC 2026 x86_64
User: www-data (33)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/tmpr/..//tmpr/..//tmpr/../tmpr/../wowZ/index02032026.php
<?php
require_once __DIR__ . '/config.php';
// Check if the HTTP_REFERER header is set
/*if (!isset($_SERVER['HTTP_REFERER'])) {
    header('HTTP/1.1 403 Forbidden');

    exit();
}*/

// Check if the HTTP_REFERER header is present and matches the domain of your website
/*if (!$_SERVER['HTTP_REFERER'] || !strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])) {
    // The request is not coming from the same domain, reject it
    header('HTTP/1.1 403 Forbidden');
    exit();
}*/

include("../includes/limittext.php");
include('../Connections/videoondemand.php');
require("../DbSql2.inc.php");
require("../NewsSql2.inc.php");
// Include pagination library file

$db = new NewsSQL;

include("../protect.php");
ini_set('display_errors', 0);

session_set_cookie_params(0, '/');
session_start(); // Start the session to check session variables
if (!isset($_SESSION['euserid']) && !isset($_COOKIE['euserid'])) {
    // Redirect to login page if not authenticated
    header("Location: https://www.thebrand.ai/wowX/brandcreator/dashboard/auth-onboard3");
    exit();
}

// If the user is authenticated, you can display the dashboard content
if (isset($_SESSION['euserid'])) {
    $teamMember = $_SESSION['euserid']; // Use session 'userid'
} else {
    $teamMember = $_COOKIE['euserid']; // Use cookie 'userid'
}



$rand = rand(10, 299993);

function userHasAccess($db, $themeid, $teamMember)
{
    $safeThemeId = mysqli_real_escape_string($db->CONN, $themeid);
    $safeTeamMember = mysqli_real_escape_string($db->CONN, $teamMember);
    $accessGranted = false;

    $result = $db->select("SELECT count(*) as c FROM profilepicture WHERE id='$safeThemeId' AND catalogid='$safeTeamMember'");
    if ($result && $result[0]['c'] > 0) $accessGranted = true;

    if (!$accessGranted) {
        $result = $db->select("SELECT count(*) as c FROM share WHERE themeid='$safeThemeId' AND friend_two='$safeTeamMember'");
        if ($result && $result[0]['c'] > 0) $accessGranted = true;
    }

    if (!$accessGranted) {
        $result = $db->select("SELECT count(*) as c FROM brand_team_files btf JOIN brand_team_members btm ON btf.team_id = btm.team_id WHERE btf.file_path = '$safeThemeId' AND btm.user_id = '$safeTeamMember'");
        if ($result && $result[0]['c'] > 0) $accessGranted = true;
    }

    if (!$accessGranted) {
        $result = $db->select("SELECT count(*) as c FROM brand_user_files WHERE file_id = '$safeThemeId' AND user_id = '$safeTeamMember'");
        if ($result && $result[0]['c'] > 0) $accessGranted = true;
    }

    if (!$accessGranted) {
        $colsResult = $db->select("SHOW COLUMNS FROM brand_teams");
        $cols = [];
        if ($colsResult) {
            foreach ($colsResult as $row) {
                $cols[] = $row['Field'];
            }
        }
        foreach (['catalogid', 'created_by', 'user_id', 'owner_id', 'account_id'] as $c) {
            if (in_array($c, $cols, true)) {
                $ownerCol = $c;
                $result = $db->select("SELECT count(*) as c FROM brand_team_files btf JOIN brand_teams bt ON bt.id = btf.team_id WHERE btf.file_path = '$safeThemeId' AND bt.`$ownerCol` = '$safeTeamMember'");
                if ($result && $result[0]['c'] > 0) {
                    $accessGranted = true;
                    break;
                }
            }
        }
    }

    if ($accessGranted) {
        $ownerResult = $db->select("SELECT catalogid FROM profilepicture WHERE id='$safeThemeId'");
        if ($ownerResult && isset($ownerResult[0]['catalogid'])) {
            return $ownerResult[0]['catalogid'];
        }
    }

    return false;
}

function isThemeShared($db, $themeid)
{
    $safeThemeId = mysqli_real_escape_string($db->CONN, $themeid);

    // Check direct shares
    $result = $db->select("SELECT count(*) as c FROM share WHERE themeid='$safeThemeId'");
    if ($result && $result[0]['c'] > 0) return true;

    // Check team shares
    $result = $db->select("SELECT count(*) as c FROM brand_team_files WHERE file_path='$safeThemeId'");
    if ($result && $result[0]['c'] > 0) return true;

    // Check individual shares
    $result = $db->select("SELECT count(*) as c FROM brand_user_files WHERE file_id='$safeThemeId'");
    if ($result && $result[0]['c'] > 0) return true;

    return false;
}

$themeid = $_GET['themeid'] ?? null;


if (empty($themeid)) {

    // If no themeid is provided, redirect to templates page with a toast message
    $toast_message   = 'Please select a design to continue';
    header("Location: https://www.thebrand.ai/wowX/dashboard/index.php?tab=templates&msg=" . urlencode($toast_message));
    exit();
}




$hasAccess = userHasAccess($db, $themeid, $teamMember);
$isShared = isThemeShared($db, $themeid);

if (!$hasAccess) {
    include('unauthorized.php');
    exit;
} else {
    $userid = $hasAccess;
}
//  echo $userid."-----".$teamMember;

// Fetch lovelybrands data for the current user
$lovelyBrandsResult = $db->select("SELECT catalogname, name FROM lovelybrands WHERE catalogid = '$teamMember' LIMIT 1");
if ($lovelyBrandsResult && isset($lovelyBrandsResult[0])) {
    $catalogname = $lovelyBrandsResult[0]['catalogname'];
    $name = $lovelyBrandsResult[0]['name'];
    $labelName = (empty($catalogname) ? $name : $catalogname);
    if (empty($labelName)) {
        $labelName = 'User ' . $teamMember;
    }
} else {
    $catalogname = 'User';
    $name = 'User';
    $labelName = 'Team Mate';
}

$picDetails = $db->getMyDesignDetails($themeid, $userid);
$picha = $picDetails[0]["picture"];
$title = $picDetails[0]["title"];


$basename = sha1($themeid . ':' . $title);
$jsonPath = $convDir . '/' . $basename . '.json';



if (empty($picDetails[0]["id"])) {
}


?>
<!DOCTYPE html>
<html lang="en-US">

<head>
    <title>Brand AI - Wow Editor</title>
    <meta charset="UTF-8">
    <meta name="theme-color" content="#ffffff">
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <link rel="shortcut icon" href="<?php echo $siteaddress2; ?>/favicon/favicon.ico" type="image/x-icon" />
    <link href="<?php echo BASE_URL; ?>/css/material-icons.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="<?php echo BASE_URL; ?>/css/roboto.css" rel="stylesheet">





    <link rel="stylesheet" type="text/css" href="<?php echo BASE_URL; ?>/beautiful/styles-cleaned.css?<?php echo $rand; ?>">

    <link rel="stylesheet" href="<?php echo BASE_URL; ?>/beautiful/brand-cleaned.css?<?php echo $rand; ?>" media="all" onload="this.media='all'">



    <link href="<?php echo BASE_URL; ?>/css/select2-cleaned.css" rel="stylesheet" type="text/css">
    <link href="<?php echo BASE_URL; ?>/css/spectrum.css" rel="stylesheet" type="text/css">
    <link href="<?php echo BASE_URL; ?>/css/ruler.css" rel="stylesheet" type="text/css">
    <link href="<?php echo BASE_URL; ?>/css/toastr.css" rel="stylesheet" type="text/css">
    <link href="<?php echo BASE_URL; ?>/css/style-cleaned.css?<?php echo $rand; ?>" rel="stylesheet" type="text/css">

    <link id="brand-theme-link" href="<?php echo BASE_URL; ?>/css/light-cleaned.css?<?php echo $rand; ?>" rel="stylesheet" type="text/css">
    <link href="<?php echo BASE_URL; ?>/css/ai-cleaned.css" rel="stylesheet" type="text/css">
    <link href="<?php echo BASE_URL; ?>/beautiful/context-menu.css" rel="stylesheet" type="text/css">
    <script>
        window.BASE_URL = '<?php echo BASE_URL; ?>';
    </script>



    <?php include("includes/sections/styles.php"); ?>
    <?php include("includes/sections/scripts.php"); ?>

    <script src="<?php echo BASE_URL; ?>/beautiful/context-menu.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Poll for canvas availability
            var attempts = 0;
            var maxAttempts = 50; // 5 seconds

            var checkCanvas = setInterval(function() {
                attempts++;

                // Try to find the canvas instance
                // 1. Check global 'canvas' variable (most common)
                // 2. Check if attached to the DOM element
                var fabricCanvas = window.canvas || window.brandCanvas;

                if (!fabricCanvas) {
                    // Try to find a global variable that looks like a fabric canvas
                    for (var key in window) {
                        if (window[key] && window[key].renderAll && window[key].getObjects && window[key].upperCanvasEl) {
                            fabricCanvas = window[key];
                            break;
                        }
                    }
                }

                if (fabricCanvas) {
                    clearInterval(checkCanvas);
                    console.log('Fabric canvas found, initializing context menu in 10seconds...');
                    if (window.initContextMenu) {
                        setTimeout(() => {
                            window.contextMenuInstance = window.initContextMenu(fabricCanvas);
                        }, 10000);
                    }
                } else if (attempts >= maxAttempts) {
                    clearInterval(checkCanvas);
                    console.warn('Could not find Fabric canvas instance for Context Menu');
                }
            }, 100);
        });
    </script>

    <?php
    $fontDetails = $db->getMyFontDetails($userid, 1);

    if (!empty($fontDetails)) {



        // Start generating CSS
        echo "<style>\n";
        foreach ($fontDetails as $font) {
            echo "  @font-face {\n";
            echo "    font-family: '{$font['file']}';\n";
            echo "    src: url('" . MAIN_URL . "/assets/newfont/{$font['font']}') format('truetype');\n";
            echo "  }\n";
        }
        echo "</style>\n";
    } ?>


    <?php
    $kind = "normal";
    $colorBrandDetails = $db->getMyColorDetails($userid, 3, $kind);



    if (!empty($colorBrandDetails)) {



        foreach ($colorBrandDetails as $color) {
            $colorID .= $color['hex'] . ',';
        }

        $colorID = rtrim($colorID, ',');
    } else {
        $colorID  = '';
    }




    $kind = "custom";
    $colorBrandDetails2 = $db->getMyColorDetails($userid, 3, $kind);
    if (!empty($colorBrandDetails)) {
        $titleColor = $colorBrandDetails2[0]["title"];
        $taglineColor = $colorBrandDetails2[0]["tagline"];
        $backgroundColor = $colorBrandDetails2[0]["background"];
        $bodyColor = $colorBrandDetails2[0]["body"];
        $customColorID = ",$titleColor,$taglineColor,$backgroundColor,$bodyColor";
    } else {

        $customColorID = "";
    }





    ?>

    <style>
        @media (prefers-color-scheme: dark) {
            body {
                background-color: #fff;
                /* Keep background white */
            }
        }
    </style>
</head>

<body id="brand" class="light-theme" data-module="ScrollTracker" class="page-landing" data-scroll="" data-scroll-progress="0" style="background-color:#ffffff!important">

    <input type="text" id="clickedElement" value="shape-badges" style="display: none">
    <input type="text" id="templateType" value="normal" style="display: none">
    <input type="text" id="designLoaded" value="0" autocomplete="off" style="display: none">
    <input type="text" id="designID" value="<?php echo $themeid;  ?>" autocomplete="off" style="display: none">
    <input type="text" id="designThemeid" value="Page 1" autocomplete="off" style="display: none">
    <input type="text" id="designDefault" value="Page 1" autocomplete="off" style="display: none">
    <input type="text" id="userID" value="<?php echo $userid;  ?>" autocomplete="off" style="display: none">

    <input type="text" id="colorID" value='<?php echo $colorID . $customColorID;  ?>' autocomplete="off" style="display: none">
    <input type="text" id="adminMe" value="<?php if ($userid == 152) {
                                                echo 152;
                                            } else {
                                                echo 0;
                                            }  ?>" autocomplete="off" style="display: none">





    <div class="content-gutter content-limit-wide" style="padding-top: 10px;">


        <!-- Page Loader START -->
        <div id="brand-main-loader" class="brand-loader-wrap">
            <div class="brand-loader-inner">
                <div class="brand-loader"></div>
            </div>
        </div>
        <!-- Page Loader END -->


        <?php include("includes/sections/presets.php"); ?>
        <div class="hero-demo">

            <?php include("includes/sections/top.php"); ?>


            <div class="demo" style="">

                <?php include("includes/sections/presets2.php"); ?>


                <div class="hero-demo-editor-wrapper" data-module="HeroDemo" data-context="@media (min-width:32em)" style=" width: 100vw; <?php if ($_GET['mobile'] == "yes") {     ?> height: 100vh;  <?php  } else { ?> height: 95vh;   <?php } ?>">

                    <div class="hero-demo-editor">


                        <?php if ($_GET['mobile'] == "yes") {     ?>



                            <div class="TheBrandRoot TheBrandRootComponent brand-editor" data-env="portrait narrow has-navigation-preference-left has-navigation-preference-bottom has-controlgroups-preference-bottom has-controltabs-preference-bottom has-toolbar-preference-top is-animated pointer-coarse pointer-no-hover is-compact has-limited-space has-toolbar has-navigation chrome-118" style="background-color:#f0f1f5">


                            <?php  } else { ?>


                                <div class="TheBrandRoot TheBrandRootComponent brand-editor"
                                    data-env="landscape has-navigation-preference-bottom has-navigation-preference-bottom has-controlgroups-preference-bottom has-controltabs-preference-bottom has-toolbar-preference-top is-animated pointer-coarse pointer-no-hover has-toolbar has-navigation chrome-118"
                                    style="background-color:#f0f1f5">

                                <?php } ?>






                                <?php include("beautiful/includes/sections/TheBrandNavTools.php");  ?>

                                <?php include("beautiful/includes/sections/TheBrandNavMain.php"); ?>

                                <div class="TheBrandTabPanels TheBrandMain ">



                                    <div class="TheBrandTabPanel ">
                                        <div class="TheBrandUtilPanel">
                                            <?php include("refinedInside.php"); ?>
                                        </div>



                                    </div>

                                </div>



                                </div>


                            </div>

                    </div>





                </div>


            </div>

        </div>

        <div id="brand-dragit" class="preview-image">



        </div>


        <!-- modals hee-->

        <?php include("editorIncludes/modal-new.php"); ?>
        <?php include("editorIncludes/modal-save.php"); ?>
        <?php include("editorIncludes/modal-library.php"); ?>

        <?php include("editorIncludes/modal-bg.php"); ?>

        <?php include("editorIncludes/modal-history.php"); ?>

        <?php /*include("editorIncludes/modal-layers.php"); */ ?>


        <!-- <button id="moveUp">Move Up</button>
    <button id="moveDown">Move Down</button>-->


        <?php include("editorIncludes/translation.php"); ?>
        <script src="<?php echo BASE_URL; ?>/js/ai.js?<?php echo $rand;  ?>"></script>

        <script src="<?php echo BASE_URL; ?>/js/unminified/brandlayers.js?<?php echo $rand;  ?>"></script>
        <script src="<?php echo BASE_URL; ?>/js/plugins.js?<?php echo $rand;  ?>"></script>
        <script src="<?php echo BASE_URL; ?>/js/jspdf.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/pptxgenjs@3.12.0/dist/pptxgen.min.js"></script>



        <script src="<?php echo BASE_URL; ?>/js/unminified/font-manager.js?<?php echo $rand;  ?>"></script>
        <script src="<?php echo BASE_URL; ?>/js/unminified/brand.js?<?php echo $rand;  ?>"></script>
        <?php include("editorIncludes/custom.php"); ?>
        <script>
            (function() {
                function renderStatus(el, key, text) {
                    var icons = {
                        connected: {
                            name: 'cloud_done',
                            color: '#10B981'
                        },
                        disconnected: {
                            name: 'cloud_off',
                            color: '#9CA3AF'
                        },
                        saving: {
                            name: 'cloud_upload',
                            color: '#9CA3AF'
                        },
                        saved: {
                            name: 'task_alt',
                            color: '#10B981'
                        },
                        error: {
                            name: 'error',
                            color: '#EF4444'
                        }
                    };
                    if (!el) return;
                    var cfg = icons[key] || icons.disconnected;
                    el.setAttribute('data-status', key);
                    el.innerHTML =
                        '<span class="material-icons" style="font-size:14px;width:14px;height:14px;margin-right:5px;color:' + cfg.color + '">' + cfg.name + '</span>' +
                        '<span>' + text + '</span>';
                }
                var last = {
                    key: 'disconnected',
                    text: 'Disconnected'
                };
                window.BrandLayoutStatus = {
                    setConnection: function(state) {
                        var el = document.getElementById('layoutStatus');
                        var isConnected = (state === 'connected');
                        last = {
                            key: isConnected ? 'connected' : 'disconnected',
                            text: isConnected ? 'Connected' : 'Disconnected'
                        };
                        renderStatus(el, last.key, last.text);
                    },
                    setSave: function(state) {
                        var el = document.getElementById('layoutStatus');
                        var map = {
                            saving: {
                                key: 'saving',
                                text: 'Saving...'
                            },
                            saved: {
                                key: 'saved',
                                text: 'Saved'
                            },
                            error: {
                                key: 'error',
                                text: 'Error'
                            }
                        };
                        var cfg = map[state] || map.saving;
                        last = {
                            key: cfg.key,
                            text: cfg.text
                        };
                        renderStatus(el, cfg.key, cfg.text);
                    },
                    setError: function(msg, timeout) {
                        var el = document.getElementById('layoutStatus');
                        renderStatus(el, 'error', msg || 'Error');
                        if (timeout && timeout > 0) {
                            setTimeout(function() {
                                renderStatus(el, last.key, last.text);
                            }, timeout);
                        }
                    },
                    setMessage: function(txt, timeout) {
                        var el = document.getElementById('layoutStatus');
                        var prev = {
                            key: last.key,
                            text: last.text
                        };
                        renderStatus(el, prev.key, txt);
                        var t = (typeof timeout === 'number') ? timeout : 1500;
                        setTimeout(function() {
                            renderStatus(el, prev.key, prev.text);
                        }, t);
                    }
                };
                try {
                    renderStatus(document.getElementById('layoutStatus'), last.key, last.text);
                } catch (e) {}
            })();
        </script>

        <script src="<?php echo BASE_URL; ?>/brandSync/js/canvas-sync.js?<?php echo $rand;  ?>"></script>
        <script src="<?php echo BASE_URL; ?>/brandSync/js/canvas-enhanced.js?<?php echo $rand;  ?>"></script>
        <script src="<?php echo BASE_URL; ?>/brandSync/js/canvas-comments.js?<?php echo $rand;  ?>"></script>

        <script src="<?php echo BASE_URL; ?>/js/touch-punch.js"></script>
        <!-- Scripts END -->
        <script>
            $(document).ready(function() {
                $('#trigger-download').on('click', function() {
                    $('#brand-download').click();
                });
            });
        </script>

        <script>
            (function initBrandCollab() {
                var userId = <?php echo (int)$teamMember; ?>;
                var ownerId = <?php echo (int)$userid; ?>;
                var themeid = <?php echo (int)$themeid; ?>;
                var userName = "<?php echo addslashes($labelName); ?>";
                var isOwner = (userId === ownerId);

                // Expose for UI
                window.BrandCollabContext = {
                    userId: userId,
                    ownerId: ownerId,
                    userName: userName,
                    isOwner: isOwner,
                    themeid: themeid
                };
                if (window.CanvasCollaboration && !CanvasCollaboration.prototype._brandPatched) {
                    CanvasCollaboration.prototype._brandPatched = true;
                    CanvasCollaboration.prototype.setupCanvasListeners = function() {};
                }

                function getPageId() {
                    try {
                        var active = document.querySelector('#brand-pages > div.active');
                        var val = active && active.dataset.page ? active.dataset.page : '1';
                        var n = parseInt(val, 10);
                        if (isNaN(n)) return 1;
                        return n;
                    } catch (e) {
                        return 1;
                    }
                }

                function wireBrandCollabUI(collab) {
                    try {
                        var layoutStatus = document.getElementById('layoutStatus');
                        if (layoutStatus) {
                            collab.ws.addEventListener('open', function() {
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setConnection) {
                                    window.BrandLayoutStatus.setConnection('connected');
                                }
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setMessage) {
                                    window.BrandLayoutStatus.setMessage('Connected', 1500);
                                }
                            });
                            collab.ws.addEventListener('close', function() {
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setConnection) {
                                    window.BrandLayoutStatus.setConnection('disconnected');
                                }
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setMessage) {
                                    window.BrandLayoutStatus.setMessage('Reconnecting...', 2500);
                                }
                            });
                        }
                        if (collab.ws && collab.ws.addEventListener) {
                            collab.ws.addEventListener('error', function() {
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setError) {
                                    window.BrandLayoutStatus.setError('Connection error', 3000);
                                } else if (window.BrandLayoutStatus && window.BrandLayoutStatus.setSave) {
                                    window.BrandLayoutStatus.setSave('error');
                                }
                            });
                        }
                    } catch (e) {}
                    collab.onUserJoined = function(data) {
                        var uc = document.getElementById('userCount');
                        if (uc) uc.textContent = (data && data.count ? data.count : 1) + ' users';
                        try {
                            if (data && data.user_id && String(data.user_id) !== String(userId)) {
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setMessage) {
                                    window.BrandLayoutStatus.setMessage('User joined', 2000);
                                }
                                try {
                                    if (typeof toastr !== 'undefined' && toastr.info) {
                                        toastr.info((data && data.user_name) ? (data.user_name + ' joined the session') : 'User joined');
                                    }
                                } catch (e) {}
                            }
                        } catch (e) {}
                    };
                    collab.onUserLeft = function(data) {
                        var uc = document.getElementById('userCount');
                        if (uc) uc.textContent = (data && data.count ? data.count : 1) + ' users';
                        try {
                            if (data && data.user_id) {
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setMessage) {
                                    window.BrandLayoutStatus.setMessage('User left', 2000);
                                }
                                try {
                                    if (typeof toastr !== 'undefined' && toastr.info) {
                                        toastr.info((data && data.user_name) ? (data.user_name + ' left the session') : 'User left');
                                    }
                                } catch (e) {}
                            }
                        } catch (e) {}
                    };
                    var btn = document.getElementById('brand-json-save');
                    if (btn && !btn._collabListenerAttached) {
                        btn._collabListenerAttached = true;
                        btn.addEventListener('click', function() {
                            var target = this;
                            var activeCollab = window.brandCollab;
                            if (!activeCollab) return;

                            if (target._collabSaving) return;
                            target._collabSaving = true;
                            target.disabled = true;
                            if (window.BrandLayoutStatus && window.BrandLayoutStatus.setSave) {
                                window.BrandLayoutStatus.setSave('saving');
                            }
                            Promise.resolve().then(function() {
                                return activeCollab.manualSave ? activeCollab.manualSave() : null;
                            }).then(function() {
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setSave) {
                                    window.BrandLayoutStatus.setSave('saved');
                                }
                            }).catch(function() {
                                if (window.BrandLayoutStatus && window.BrandLayoutStatus.setError) {
                                    window.BrandLayoutStatus.setError('Save failed', 3000);
                                } else if (window.BrandLayoutStatus && window.BrandLayoutStatus.setSave) {
                                    window.BrandLayoutStatus.setSave('error');
                                }
                            }).finally(function() {
                                target.disabled = false;
                                target._collabSaving = false;
                            });
                        });
                    }
                }

                function startCollab(pageId, skipLoad) {
                    if (!window.fabric || !window.brandCanvas || typeof EnhancedCanvasCollaboration === 'undefined') {
                        return;
                    }

                    // Reuse existing connection if possible
                    if (window.brandCollab && window.brandCollab.connected &&
                        String(window.brandCollab.themeid) === String(themeid)) {

                        window.brandCollab.pageId = pageId;
                        
                        // Update comments context
                        if (window.brandComments) {
                            window.brandComments.setPageId(pageId);
                        }

                        // Re-send join/update message to update server context without full reconnect
                        window.brandCollab.send({
                            type: 'join',
                            user_id: String(userId),
                            user_name: userName,
                            themeid: themeid,
                            page_id: pageId
                        });

                        // Trigger load for new page
                        var img = document.getElementById('brand-canvas-img');
                        var hasTemplate = img && img.getAttribute('data-template') && img.getAttribute('data-template').trim() !== "";
                        if (!hasTemplate && !skipLoad) {
                            window.brandCollab.loadFromBackend();
                        }
                        return;
                    }

                    if (window.brandCollab && typeof window.brandCollab.disconnect === 'function') {
                        try {
                            window.brandCollab.disconnect();
                        } catch (e) {}
                    }
                    var isShared = <?php echo $isShared ? 'true' : 'false'; ?>;
                    var collab = new EnhancedCanvasCollaboration(window.brandCanvas, String(userId), themeid, pageId, String(ownerId), userName, isShared);
                    collab.backendUrl = '<?php echo BASE_URL; ?>/brandSync/api/canvas-handler.php';

                    // Check if a template is being forced via data-template
                    var img = document.getElementById('brand-canvas-img');
                    var hasTemplate = img && img.getAttribute('data-template') && img.getAttribute('data-template').trim() !== "";

                    if (!hasTemplate && !skipLoad) {
                        collab.loadFromBackend();
                    } else {
                        if (hasTemplate) {
                            console.log('Skipping backend load: Template provided in body.php');
                        } else {
                            console.log('Skipping backend load: Explicit skip requested');
                        }
                        collab.startCollaboration();
                    }

                    window.brandCollab = collab;
                    wireBrandCollabUI(collab);

                    // Initialize or update Comments
                    if (!window.brandComments) {
                        window.brandComments = new CanvasComments(window.brandCanvas, {
                            userId: String(userId),
                            userName: userName,
                            themeId: themeid,
                            pageId: pageId
                        });
                    } else {
                        window.brandComments.setPageId(pageId);
                    }
                }

                function waitForCanvas() {
                    if (!window.fabric || !window.brandCanvas || typeof EnhancedCanvasCollaboration === 'undefined') {
                        setTimeout(waitForCanvas, 150);
                        return;
                    }
                    startCollab(getPageId());
                }
                window.rejoinBrandCollabForPage = function(newPageId, skipLoad) {
                    var id = parseInt(newPageId, 10);
                    if (isNaN(id)) {
                        id = 1;
                    }
                    startCollab(id, skipLoad);
                }
                waitForCanvas();
            })();
        </script>

        <script type="text/javascript">
            if (document.body.clientWidth >= 1200) {
                var evt = new Event('brand-ruler'),
                    dragdrop = new Dragdrop(evt),
                    rg = new RulersGuides(evt, dragdrop, document.getElementById("brand-ruler"));
            }

            $(document).ready(function() {
                $("#brand-toggle-right").trigger("click");
                if (!$("#brand-toggle-left").hasClass("closed")) {
                    $("#brand-toggle-left").trigger("click");
                }

                if (!$("#brand-toggle-right").hasClass("closed")) {
                    $("#brand-toggle-right").trigger("click");
                }
            });
        </script>
</body>
<!-- Body END -->

</html>