( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ 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/brandDetails.php
<?php
/**
 * API Usage Documentation
 * =======================
 * Base URL: brandDetails.php
 * Authentication: Requires valid session/cookie (handled by dashboard/config.php)
 *
 * 1. Get User's Brands (Owned & Shared)
 *    URL: brandDetails.php?brands=yes
 *    Method: GET
 *    Returns: JSON array of brand objects (including brandkits)
 *
 * 2. Get Templates & Curated Content
 *    URL: brandDetails.php?templates=yes
 *    Method: GET
 *    Parameters:
 *      - brandcreator (string, optional): Context for curated content (e.g., 'Gamer', 'Business'). Defaults to 'Gamer'.
 *      - type (string, optional): Additional context type.
 *      - category (string/int, optional): Filter templates by Category ID (numeric) or Title/Keyword (text).
 *      - query (string, optional): Search templates by Title/Keyword.
 *      - interests (string, optional): Comma-separated keywords for interest-based matching.
 *    Returns: JSON object with sections:
 *      - my_categories: Categories relevant to the creator type.
 *      - curated_templates: List of design templates (post_id, title, design_id, etc.).
 *      - sites: Website templates (cards, headline, cta).
 *      - hero: Hero section configuration.
 *      - creator_interests: Interests string associated with the creator.
 *
 * 3. Get Shared Content (Teams)
 *    URL: brandDetails.php?shared=yes
 *    Method: GET
 *    Returns: JSON object with:
 *      - templates: Shared individual design files.
 *      - folders: Shared folders.
 *      - brandkits: Shared brand kits.
 *
 * 4. Get Specific Folder Contents
 *    URL: brandDetails.php?folder={FOLDER_ID}
 *    Method: GET
 *    Returns: JSON object with:
 *      - stock_images: List of stock images in folder.
 *      - designs: List of designs in folder.
 *
 * 5. Get Specific Brand Details
 *    URL: brandDetails.php?brandid={BRAND_ID}
 *    Method: GET
 *    Returns: JSON object with brand assets (logos, colors, fonts, etc.).
 */

// Include teams config which handles DB connection and session
require_once __DIR__ . '/dashboard/config.php';

header('Content-Type: application/json; charset=utf-8');

// $conn and $userid are defined in dashboard/config.php
$currentUserId = isset($userid) ? (int)$userid : 0;

if (!$currentUserId) {
    echo json_encode(['error' => 'Unauthorized']);
    if (defined('BRANDDETAILS_LIB_ONLY')) {
        return;
    }
    exit;
}

if (!function_exists('bd_maybe_exit')) {
    function bd_maybe_exit(): void {
        if (defined('BRANDDETAILS_LIB_ONLY')) {
            return;
        }
        exit;
    }
}

// Ensure helper function exists (dashboard/config.php should define teams_find_owner_column)
if (!function_exists('findOwnerColumnLocal')) {
    function findOwnerColumnLocal(mysqli $conn, string $table): ?string {
        if (function_exists('teams_find_owner_column')) {
            return teams_find_owner_column($conn, $table);
        }
        $res = $conn->query("SHOW COLUMNS FROM `$table`");
        if (!$res) { return null; }
        $cols = [];
        while ($row = $res->fetch_assoc()) { if (!empty($row['Field'])) { $cols[$row['Field']] = true; } }
        foreach (['catalogid','created_by','user_id','owner_id','account_id'] as $c) { if (isset($cols[$c])) { return $c; } }
        return null;
    }
}

// Global parameter handling
$brand_creator = isset($_GET['brandcreator']) ? (string)$_GET['brandcreator'] : (isset($_GET['creator']) ? (string)$_GET['creator'] : 'Gamer');

if (isset($_GET['brands'])) {
    // 1. Get brands owned by user
    $ownedBrands = [];
    $stmt = $conn->prepare("SELECT id, name, description FROM brands WHERE owner_userid = ?");
    if ($stmt) {
        $stmt->bind_param('i', $currentUserId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $row['is_owner'] = true;
            $row['source'] = 'owned';
            $ownedBrands[$row['id']] = $row;
        }
        $stmt->close();
    }

    // 2. Get brands shared via teams
    $teamsOwnerCol = findOwnerColumnLocal($conn, 'brand_teams');
    $teamIds = [];

    // Query to get team IDs
    $sqlTeams = "";
    if ($teamsOwnerCol) {
        $sqlTeams = "SELECT DISTINCT t.id FROM brand_teams t LEFT JOIN brand_team_members m ON m.team_id=t.id AND m.user_id=? WHERE t.`$teamsOwnerCol`=? OR m.user_id IS NOT NULL";
    } else {
        $sqlTeams = "SELECT DISTINCT t.id FROM brand_teams t JOIN brand_team_members m ON m.team_id=t.id WHERE m.user_id=?";
    }

    $stmt = $conn->prepare($sqlTeams);
    if ($stmt) {
        if ($teamsOwnerCol) {
            $stmt->bind_param('ii', $currentUserId, $currentUserId);
        } else {
            $stmt->bind_param('i', $currentUserId);
        }
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $teamIds[] = (int)$row['id'];
        }
        $stmt->close();
    }

    $sharedBrands = [];
    if (!empty($teamIds)) {
        $inStr = implode(',', $teamIds);
        // Get brands shared with these teams
        $sqlShared = "SELECT b.id, b.name, b.description, btb.team_id 
                      FROM brands b 
                      JOIN brand_team_brands btb ON btb.brand_id = b.id 
                      WHERE btb.team_id IN ($inStr)";
        
        $res = $conn->query($sqlShared);
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $bid = $row['id'];
                if (!isset($ownedBrands[$bid])) {
                    if (!isset($sharedBrands[$bid])) {
                         $row['is_owner'] = false;
                         $row['source'] = 'shared';
                         $row['shared_via_teams'] = [];
                         $sharedBrands[$bid] = $row;
                    }
                    $sharedBrands[$bid]['shared_via_teams'][] = $row['team_id'];
                }
            }
        }
    }

    // Merge brands
    $allBrands = $ownedBrands + $sharedBrands;

    // 3. For each brand, fetch brandkits
    foreach ($allBrands as &$brand) {
        $brand['brandkits'] = [];
        $stmt = $conn->prepare("SELECT id, name, description, created_at FROM brandkits WHERE brand_id = ? ORDER BY id ASC");
        if ($stmt) {
            $stmt->bind_param('i', $brand['id']);
            $stmt->execute();
            $res = $stmt->get_result();
            while ($kit = $res->fetch_assoc()) {
                $brand['brandkits'][] = $kit;
            }
            $stmt->close();
        }
    }
    unset($brand); // break reference

    echo json_encode(array_values($allBrands));
    bd_maybe_exit();
} elseif (isset($_GET['templates']) && $_GET['templates'] === 'yes') {
    $brand_type = isset($_GET['type']) ? (string)$_GET['type'] : '';

    $teams_norm = function($s) {
        $s = strtolower(trim((string)$s));
        $s = preg_replace('/\s+/', ' ', $s);
        return $s;
    };

    $teams_my_categories = [];
    $teams_hero = [];
    $teams_hero_reason = '';
    $teams_creator_for_my_categories = '';

    $teams_my_categories_path = __DIR__ . '/json/data/selected/creator_type_liked_categories.json';
    if (is_file($teams_my_categories_path)) {
        $raw = @file_get_contents($teams_my_categories_path);
        $rows = json_decode((string)$raw, true);
        if (is_array($rows)) {
            $want1 = $teams_norm($brand_creator);
            $want2 = $teams_norm($brand_type);
            foreach ($rows as $row) {
                if (!is_array($row)) { continue; }
                $rowCreator = isset($row['creator']) ? (string)$row['creator'] : '';
                $rowNorm = $teams_norm($rowCreator);
                if (($want1 !== '' && $rowNorm === $want1) || ($want1 === '' && $want2 !== '' && $rowNorm === $want2)) {
                    $teams_creator_for_my_categories = $rowCreator;
                    $liked = $row['liked_categories'] ?? [];
                    if (is_array($liked)) { $teams_my_categories = $liked; }
                    $hero = $row['hero'] ?? [];
                    if (is_array($hero)) { $teams_hero = $hero; }
                    $teams_hero_reason = isset($row['reason']) ? (string)$row['reason'] : '';
                    break;
                }
            }
            if ($teams_creator_for_my_categories === '' && $want1 !== '' && $want2 !== '') {
                foreach ($rows as $row) {
                    if (!is_array($row)) { continue; }
                    $rowCreator = isset($row['creator']) ? (string)$row['creator'] : '';
                    $rowNorm = $teams_norm($rowCreator);
                    if ($rowNorm === $want2) {
                        $teams_creator_for_my_categories = $rowCreator;
                        $liked = $row['liked_categories'] ?? [];
                        if (is_array($liked)) { $teams_my_categories = $liked; }
                        $hero = $row['hero'] ?? [];
                        if (is_array($hero)) { $teams_hero = $hero; }
                        $teams_hero_reason = isset($row['reason']) ? (string)$row['reason'] : '';
                        break;
                    }
                }
            }
        }
    }

    $teams_creator = $teams_creator_for_my_categories !== '' ? $teams_creator_for_my_categories : $brand_creator;
    if ($teams_creator === '' && $brand_type !== '') {
        $teams_creator = $brand_type;
    }

    $teams_creator_interests = '';
    $teams_creator_interests_path = __DIR__ . '/json/data/selected/creatorinterests.json';
    if ($teams_creator !== '' && is_file($teams_creator_interests_path)) {
        $raw = @file_get_contents($teams_creator_interests_path);
        $rows = json_decode((string)$raw, true);
        if (is_array($rows)) {
            $creator_lc = strtolower(trim($teams_creator));
            foreach ($rows as $row) {
                if (!is_array($row)) { continue; }
                $artist = isset($row['artist']) ? strtolower(trim((string)$row['artist'])) : '';
                $cat = isset($row['category']) ? strtolower(trim((string)$row['category'])) : '';
                if (($creator_lc !== '' && $artist === $creator_lc) || ($creator_lc !== '' && $cat === $creator_lc)) {
                    $teams_creator_interests = isset($row['interests']) ? (string)$row['interests'] : '';
                    break;
                }
            }
        }
    }

    // formats_map logic removed


    $teams_sites_liked = [];
    $teams_sites_cards = [];
    $teams_sites_reason = '';
    $teams_sites_headline = 'Curated websites for you';
    $teams_sites_subheadline = 'If you don’t have a website yet, you’re leaving trust and opportunities on the table. Launch a clean, mobile-first site that matches your brand and helps people book, buy, or contact you.';
    $teams_sites_cta = 'Create a website';
    $teams_sites_cta_href = 'https://www.thebrand.ai/sites/welcome.php';

    $teams_sites_liked_path = __DIR__ . '/json/data/selected/brand_sites_creators_liked.json';
    $teams_sites_all_path = __DIR__ . '/json/data/selected/Brand Sites for Every Industry.json';

    if (is_file($teams_sites_liked_path) && is_readable($teams_sites_liked_path)) {
        $raw = @file_get_contents($teams_sites_liked_path);
        $rows = json_decode((string)$raw, true);
        if (is_array($rows)) {
            $want1 = $teams_norm($brand_creator);
            $want2 = $teams_norm($brand_type);
            $selected = null;
            foreach ($rows as $row) {
                if (!is_array($row)) { continue; }
                $creator = isset($row['creator']) ? (string)$row['creator'] : '';
                $n = $teams_norm($creator);
                if (($want1 !== '' && $n === $want1) || ($want1 === '' && $want2 !== '' && $n === $want2)) { $selected = $row; break; }
            }
            if ($selected === null && isset($rows[0]) && is_array($rows[0])) { $selected = $rows[0]; }
            if (is_array($selected)) {
                $teams_sites_liked = (isset($selected['liked_categories']) && is_array($selected['liked_categories'])) ? $selected['liked_categories'] : [];
                $teams_sites_reason = isset($selected['reason']) ? (string)$selected['reason'] : '';
                $hero = (isset($selected['hero']) && is_array($selected['hero'])) ? $selected['hero'] : [];
                if (isset($hero['headline']) && (string)$hero['headline'] !== '') { $teams_sites_headline = (string)$hero['headline']; }
                if (isset($hero['subheadline']) && (string)$hero['subheadline'] !== '') { $teams_sites_subheadline = (string)$hero['subheadline']; }
                if (isset($hero['cta']) && (string)$hero['cta'] !== '') { $teams_sites_cta = (string)$hero['cta']; }
            }
        }
    }

    $teams_sites_all = [];
    if (is_file($teams_sites_all_path) && is_readable($teams_sites_all_path)) {
        $raw = @file_get_contents($teams_sites_all_path);
        $rows = json_decode((string)$raw, true);
        if (is_array($rows)) { $teams_sites_all = $rows; }
    }

    $teams_sites_by_title = [];
    foreach ($teams_sites_all as $row) {
        if (!is_array($row)) { continue; }
        $title = isset($row['Title']) ? trim((string)$row['Title']) : '';
        $img = isset($row['Image']) ? trim((string)$row['Image']) : '';
        if ($title === '' || $img === '') { continue; }
        $teams_sites_by_title[$teams_norm($title)] = ['title' => $title, 'image' => $img];
    }

    $teams_sites_find = function($cat) use ($teams_norm, $teams_sites_by_title, $teams_sites_all) {
        $cat = trim((string)$cat);
        if ($cat === '') { return null; }
        $k = $teams_norm($cat);
        if (isset($teams_sites_by_title[$k])) { return $teams_sites_by_title[$k]; }
        foreach ($teams_sites_all as $row) {
            if (!is_array($row)) { continue; }
            $title = isset($row['Title']) ? trim((string)$row['Title']) : '';
            $img = isset($row['Image']) ? trim((string)$row['Image']) : '';
            if ($title === '' || $img === '') { continue; }
            $t = strtolower($title);
            $c = strtolower($cat);
            if ($c !== '' && ($t === $c || strpos($t, $c) !== false || strpos($c, $t) !== false)) {
                return ['title' => $title, 'image' => $img];
            }
        }
        return null;
    };

    $teams_sites_seen = [];
    foreach ($teams_sites_liked as $cat) {
        $found = $teams_sites_find($cat);
        if (!$found || !is_array($found)) { continue; }
        $key = $teams_norm($found['title']);
        if (isset($teams_sites_seen[$key])) { continue; }
        $teams_sites_seen[$key] = true;
        $teams_sites_cards[] = $found;
        if (count($teams_sites_cards) >= 6) { break; }
    }
    if (!count($teams_sites_cards)) {
        foreach ($teams_sites_all as $row) {
            if (!is_array($row)) { continue; }
            $title = isset($row['Title']) ? trim((string)$row['Title']) : '';
            $img = isset($row['Image']) ? trim((string)$row['Image']) : '';
            if ($title === '' || $img === '') { continue; }
            $teams_sites_cards[] = ['title' => $title, 'image' => $img];
            if (count($teams_sites_cards) >= 6) { break; }
        }
    }

    // Curated Templates Logic (matching files/connect/themes_relevant.php)
    $curatedTemplates = [];
    $categoryFilter = isset($_GET['category']) ? trim((string)$_GET['category']) : '';
    $searchQuery = isset($_GET['query']) ? trim((string)$_GET['query']) : '';
    $interestsInput = isset($_GET['interests']) ? trim((string)$_GET['interests']) : '';
    
    // Fallback to creator interests/name if no explicit input (logic from themes_relevant)
    if ($interestsInput === '' && isset($teams_creator_interests) && $teams_creator_interests !== '') {
        $interestsInput = trim($teams_creator_interests);
    }
    if ($interestsInput === '' && isset($teams_creator) && $teams_creator !== '') {
         $interestsInput = trim($teams_creator);
    }

    // Default query base
    $sql = "SELECT id, title, poster, alias FROM profilepicture WHERE isdisplay='13' AND type='2' AND public='1' AND catalogid=152";
    $params = [];
    $types = "";
    
    $mode = 'default'; // default, query, interests

    if ($categoryFilter !== '') {
        $mode = 'query';
        if (is_numeric($categoryFilter)) {
            $sql .= " AND category = ?";
            $params[] = $categoryFilter;
            $types .= "i";
        } else {
             $sql .= " AND (title LIKE ? OR keywords LIKE ?)";
             $params[] = "%" . $categoryFilter . "%";
             $params[] = "%" . $categoryFilter . "%";
             $types .= "ss";
        }
    } elseif ($searchQuery !== '') {
         $mode = 'query';
         $sql .= " AND (title LIKE ? OR keywords LIKE ?)";
         $params[] = "%" . $searchQuery . "%";
         $params[] = "%" . $searchQuery . "%";
         $types .= "ss";
    } elseif ($interestsInput !== '') {
        $kw_parts = preg_split('/[,;]+/', $interestsInput);
        $keywords = [];
        foreach ($kw_parts as $p) {
             $p2 = preg_replace('/[^A-Za-z0-9\- ]/', '', (string)$p);
             $p2 = trim($p2);
             if ($p2 !== '') { $keywords[] = $p2; }
             if (count($keywords) >= 10) { break; }
        }

        if (!empty($keywords)) {
            $mode = 'interests';
            $where_parts = [];
            foreach ($keywords as $kw) {
                $k = "%" . str_replace(" ", "%", $kw) . "%";
                $where_parts[] = "(title LIKE ? OR keywords LIKE ?)";
                $params[] = $k;
                $params[] = $k;
                $types .= "ss";
            }
            $sql .= " AND (" . implode(' OR ', $where_parts) . ")";
        }
    }

    // Ordering
    if ($mode === 'default') {
        $sql .= " ORDER BY RAND()";
    } elseif ($mode === 'interests') {
        $sql .= " ORDER BY id DESC";
    } else {
        $sql .= " ORDER BY viewnum DESC";
    }

    $sql .= " LIMIT 50";

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            // Encode design ID as in themes.php
            $designId = base64_encode($row['id']);
            $designId = strtr($designId, '+/=', '-_,');
            
            $curatedTemplates[] = [
                'post_id' => $row['id'],
                'post_title' => $row['title'],
                'post_poster' => $row['poster'],
                'post_design' => $designId,
                'post_me' => $row['id'], // seems redundant but matches themes.php
                'post_description' => $row['alias']
            ];
        }
        $stmt->close();
    }

    $response = [
        'my_categories' => $teams_my_categories ?? [],
        'hero' => $teams_hero ?? [],
        'hero_reason' => $teams_hero_reason ?? '',
        'creator_interests' => $teams_creator_interests ?? '',
        'curated_templates' => $curatedTemplates,
        'sites' => [
            'cards' => $teams_sites_cards ?? [],
            'reason' => $teams_sites_reason ?? '',
            'headline' => $teams_sites_headline ?? '',
            'subheadline' => $teams_sites_subheadline ?? '',
            'cta' => $teams_sites_cta ?? '',
            'cta_href' => $teams_sites_cta_href ?? ''
        ]
    ];
    echo json_encode($response);
    bd_maybe_exit();
} elseif (isset($_GET['shared']) && $_GET['shared'] === 'yes') {
    // Shared content logic
    $data = [
        'templates' => [],
        'folders' => [],
        'brandkits' => []
    ];

    $teamsOwnerCol = findOwnerColumnLocal($conn, 'brand_teams');
    $accessSub = "";
    if ($teamsOwnerCol) {
        $accessSub = "SELECT id FROM brand_teams WHERE `$teamsOwnerCol`=$currentUserId UNION SELECT team_id FROM brand_team_members WHERE user_id=$currentUserId";
    } else {
        $accessSub = "SELECT team_id FROM brand_team_members WHERE user_id=$currentUserId";
    }

    // 1. Templates (Shared Pictures)
    // Determine poster column
    $posterColumn = 'poster';
    $colsRes = $conn->query("SHOW COLUMNS FROM profilepicture");
    if ($colsRes) {
        $colNames = [];
        while ($c = $colsRes->fetch_assoc()) { if (isset($c['Field'])) { $colNames[(string)$c['Field']] = true; } }
        if (!isset($colNames['poster']) && isset($colNames['picture'])) { $posterColumn = 'picture'; }
    }

    $sqlTemplates = "SELECT sf.id AS share_id, sf.team_id, sf.file_path AS original_file_id, p.title, p.`$posterColumn` AS poster, p.id AS picture_id, t.name AS team_name
                     FROM brand_team_files sf
                     JOIN profilepicture p ON sf.file_path = p.id
                     JOIN brand_teams t ON t.id = sf.team_id
                     WHERE sf.team_id IN ($accessSub)
                     ORDER BY sf.id DESC LIMIT 200";
    
    $res = $conn->query($sqlTemplates);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $data['templates'][] = $row;
        }
    }

    // 2. Shared Folders
    $sqlFolders = "SELECT ff.folder_id, tf.name AS folder_name, t.name AS team_name, MAX(sf.id) AS last_shared_id
                   FROM brand_team_files sf
                   JOIN brand_teams_folder_files ff ON ff.file_path = sf.file_path
                   JOIN brand_teams_folders tf ON tf.id = ff.folder_id
                   JOIN brand_teams t ON t.id = sf.team_id
                   WHERE sf.team_id IN ($accessSub)
                   GROUP BY sf.team_id, ff.folder_id, tf.name, t.name
                   ORDER BY last_shared_id DESC LIMIT 200";
    
    $res = $conn->query($sqlFolders);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $data['folders'][] = $row;
        }
    }

    // 3. Shared Brandkits
    $sqlBrandkits = "SELECT b.id AS brand_id, b.name AS brand_name,
                     GROUP_CONCAT(DISTINCT t.name ORDER BY t.name SEPARATOR ', ') AS team_names
                     FROM brands b
                     JOIN brand_team_brands btb ON btb.brand_id=b.id
                     JOIN brand_teams t ON t.id=btb.team_id
                     WHERE btb.team_id IN ($accessSub)
                     GROUP BY b.id, b.name
                     ORDER BY b.id DESC LIMIT 200";
    
    $res = $conn->query($sqlBrandkits);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $data['brandkits'][] = $row;
        }
    }

    echo json_encode($data);
} elseif (isset($_GET['folder'])) {
    $folderId = (int)$_GET['folder'];
    
    // Debug logging
    $log = "Folder Request: ID=$folderId, User=$currentUserId\n";
    
    // Access check
    $allowed = false;
    $foldersOwnerCol = findOwnerColumnLocal($conn, 'brand_teams_folders');
    
    if ($foldersOwnerCol) {
        $stmt = $conn->prepare("SELECT 1 FROM brand_teams_folders WHERE id=? AND `$foldersOwnerCol`=? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('ii', $folderId, $currentUserId);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($res && $res->num_rows) { $allowed = true; }
            $stmt->close();
        }
    }
    
    if (!$allowed) {
        $stmt = $conn->prepare("SELECT 1 FROM brand_teams_folder_members WHERE folder_id=? AND user_id=? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('ii', $folderId, $currentUserId);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($res && $res->num_rows) { $allowed = true; }
            $stmt->close();
        }
    }
    
    $log .= "Allowed: " . ($allowed ? 'YES' : 'NO') . "\n";
    
    if (!$allowed) {
        // file_put_contents(__DIR__ . '/logs/debug_log.txt', $log, FILE_APPEND);
        echo json_encode(['error' => 'Forbidden']);
        bd_maybe_exit();
    }

    $data = [
        'stock_images' => [],
        'designs' => []
    ];
    
    $stmt = $conn->prepare("SELECT f.id, f.file_path, f.title, f.url, f.kind, p.title AS p_title, p.poster AS p_poster 
                            FROM brand_teams_folder_files f 
                            LEFT JOIN profilepicture p ON p.id=f.file_path 
                            WHERE f.folder_id=? 
                            ORDER BY f.id DESC LIMIT 200");
                            
    if ($stmt) {
        $stmt->bind_param('i', $folderId);
        $stmt->execute();
        $res = $stmt->get_result();
        $log .= "Rows found: " . ($res ? $res->num_rows : '0') . "\n";
        while ($res && ($row = $res->fetch_assoc())) {
            $kind = (string)($row['kind'] ?? '');
            $poster = (string)($row['url'] ?? '');
            if ($poster === '') { $poster = (string)($row['p_poster'] ?? ''); }
            
            $log .= "Row: ID={$row['id']}, Kind=$kind, Poster=$poster\n";
            
            $title = (string)($row['title'] ?? '');
            if ($title === '') { $title = (string)($row['p_title'] ?? ''); }
            if ($title === '') { $title = 'Untitled'; }
            
            $item = [
                'id' => (int)$row['id'],
                'ref_id' => (int)$row['file_path'],
                'title' => $title,
                'kind' => $kind,
                'file_path' => $poster
            ];
            
            if ($kind === 'stock_image') {
                $item['full_path'] = '/wowX/dashboard/' . $poster;
                $data['stock_images'][] = $item;
            } else {
                $item['full_path'] = '/v/uploads/gallery/' . $poster;
                $data['designs'][] = $item;
            }
        }
        $stmt->close();
    } else {
        $log .= "Query prepare failed: " . $conn->error . "\n";
    }
    
    file_put_contents(__DIR__ . '/debug_log.txt', $log, FILE_APPEND);
    
    echo json_encode($data);
} elseif (isset($_GET['brandid'])) {
    $brandId = (int)$_GET['brandid'];
    
    // Check access
    $hasAccess = false;
    
    // 1. Check ownership
    $stmt = $conn->prepare("SELECT 1 FROM brands WHERE id=? AND owner_userid=? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param('ii', $brandId, $currentUserId);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res && $res->num_rows) { $hasAccess = true; }
        $stmt->close();
    }
    
    // 2. Check team access if not owner
    if (!$hasAccess) {
        $teamsOwnerCol = findOwnerColumnLocal($conn, 'brand_teams');
        if ($teamsOwnerCol) {
            $sql = "SELECT 1 FROM brand_team_brands btb JOIN brand_teams t ON t.id=btb.team_id LEFT JOIN brand_team_members m ON m.team_id=t.id AND m.user_id=? WHERE btb.brand_id=? AND (m.user_id IS NOT NULL OR t.`$teamsOwnerCol`=?) LIMIT 1";
            $stmt = $conn->prepare($sql);
            if ($stmt) {
                $stmt->bind_param('iii', $currentUserId, $brandId, $currentUserId);
                $stmt->execute();
                $res = $stmt->get_result();
                if ($res && $res->num_rows) { $hasAccess = true; }
                $stmt->close();
            }
        } else {
            $stmt = $conn->prepare("SELECT 1 FROM brand_team_brands btb JOIN brand_team_members m ON m.team_id=btb.team_id WHERE btb.brand_id=? AND m.user_id=? LIMIT 1");
            if ($stmt) {
                $stmt->bind_param('ii', $brandId, $currentUserId);
                $stmt->execute();
                $res = $stmt->get_result();
                if ($res && $res->num_rows) { $hasAccess = true; }
                $stmt->close();
            }
        }
    }
    
    if (!$hasAccess) {
        echo json_encode(['error' => 'Forbidden']);
        bd_maybe_exit();
    }
    
    // Fetch default brandkit
    $brandkitId = 0;
    $stmt = $conn->prepare("SELECT id FROM brandkits WHERE brand_id=? ORDER BY id ASC LIMIT 1");
    if ($stmt) {
        $stmt->bind_param('i', $brandId);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            $brandkitId = (int)$row['id'];
        }
        $stmt->close();
    }
    
    if (!$brandkitId) {
        echo json_encode(['error' => 'No brandkit found']);
        bd_maybe_exit();
    }
    
    // Helper for path normalization
    if (!function_exists('normalizeFilePathLocal')) {
        function normalizeFilePathLocal(string $path): string {
            $p = str_replace('\\', '/', $path);
            $pos = strpos($p, 'uploads/');
            if ($pos !== false) { return substr($p, $pos); }
            return ltrim($p, '/');
        }
    }

    $data = [
        'brand_id' => $brandId,
        'brandkit_id' => $brandkitId,
        'logos' => [],
        'colors' => [],
        'voice' => [],
        'photos' => [],
        'graphics' => [],
        'icons' => [],
        'fonts' => [],
        'font_selections' => [],
        'font_styles' => [],
    ];

    foreach ([
        ['logos', 'file_path', 'logos'],
        ['photos', 'file_path', 'photos'],
        ['graphics', 'file_path', 'graphics'],
        ['icons', 'file_path', 'icons'],
    ] as $q) {
        $stmt = $conn->prepare("SELECT id, {$q[1]} FROM {$q[0]} WHERE brandkit_id=? ORDER BY id DESC LIMIT 200");
        if ($stmt) {
            $stmt->bind_param('i', $brandkitId);
            $stmt->execute();
            $res = $stmt->get_result();
            while ($res && ($row = $res->fetch_assoc())) {
                $data[$q[2]][] = ['id' => (int)$row['id'], 'file_path' => normalizeFilePathLocal((string)$row[$q[1]])];
            }
            $stmt->close();
        }
    }

    $stmt = $conn->prepare("SELECT id,color_code FROM brand_colors WHERE brandkit_id=? ORDER BY id DESC LIMIT 200");
    if ($stmt) {
        $stmt->bind_param('i', $brandkitId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($row = $res->fetch_assoc())) {
            $data['colors'][] = ['id' => (int)$row['id'], 'color_code' => (string)$row['color_code']];
        }
        $stmt->close();
    }

    $stmt = $conn->prepare("SELECT id,voice_text FROM brand_voice WHERE brandkit_id=? ORDER BY id DESC LIMIT 50");
    if ($stmt) {
        $stmt->bind_param('i', $brandkitId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($row = $res->fetch_assoc())) {
            $data['voice'][] = ['id' => (int)$row['id'], 'voice_text' => (string)$row['voice_text']];
        }
        $stmt->close();
    }

    $stmt = $conn->prepare("SELECT id,font_name,font_type,file_path FROM fonts WHERE brandkit_id=? ORDER BY id DESC LIMIT 200");
    if ($stmt) {
        $stmt->bind_param('i', $brandkitId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($row = $res->fetch_assoc())) {
            $data['fonts'][] = [
                'id' => (int)$row['id'],
                'font_name' => (string)$row['font_name'],
                'font_type' => (string)$row['font_type'],
                'file_path' => normalizeFilePathLocal((string)$row['file_path']),
            ];
        }
        $stmt->close();
    }
    
    // Legacy fonts logic
    $existingFontKeys = [];
    foreach ($data['fonts'] as $f) {
        $k = strtolower(trim((string)($f['font_name'] ?? '')));
        if ($k !== '') { $existingFontKeys[$k] = true; }
    }

    $hasMyFonts = false;
    $tf = $conn->query("SHOW TABLES LIKE 'myfonts'");
    if ($tf && $tf->num_rows > 0) { $hasMyFonts = true; }

    if ($hasMyFonts) {
        require_once __DIR__ . '/config.php'; // Include config for MAIN_URL
        $cols = [];
        $cr = $conn->query("SHOW COLUMNS FROM myfonts");
        if ($cr) {
            while ($c = $cr->fetch_assoc()) {
                if (!empty($c['Field'])) { $cols[(string)$c['Field']] = true; }
            }
        }

        $idCol = isset($cols['id']) ? 'id' : null;
        $fileCol = isset($cols['file']) ? 'file' : null;
        $fontCol = isset($cols['font']) ? 'font' : null;
        $typeCol = isset($cols['font_type']) ? 'font_type' : (isset($cols['type']) ? 'type' : null);
        $catalogCol = isset($cols['catalogid']) ? 'catalogid' : null;
        $displayCol = isset($cols['isdisplay']) ? 'isdisplay' : null;
        $layerCol = isset($cols['layerid']) ? 'layerid' : null;

        if ($fileCol && $catalogCol) {
            $sql = "SELECT * FROM myfonts WHERE `$catalogCol`=? ";
            if ($displayCol) { $sql .= "AND `$displayCol`=1 "; }
            if ($layerCol) { $sql .= "ORDER BY `$layerCol` DESC LIMIT 500"; }
            else { $sql .= "ORDER BY " . ($idCol ? "`$idCol`" : "`$fileCol`") . " DESC LIMIT 500"; }
            $st = $conn->prepare($sql);
            if ($st) {
                $st->bind_param('i', $currentUserId);
                $st->execute();
                $rr = $st->get_result();
                $fallbackId = 1000000000;
                while ($rr && ($row = $rr->fetch_assoc())) {
                    $fontName = trim((string)($row[$fileCol] ?? ''));
                    if ($fontName === '') { continue; }
                    $k = strtolower($fontName);
                    if (isset($existingFontKeys[$k])) { continue; }

                    $fontFile = '';
                    if ($fontCol && !empty($row[$fontCol])) {
                        $fontFile = (string)$row[$fontCol];
                    } elseif (!empty($row[$fileCol])) {
                        $fontFile = (string)$row[$fileCol];
                    }
                    $fontFile = trim($fontFile);
                    if ($fontFile === '') { continue; }

                    $id = 0;
                    if ($idCol && isset($row[$idCol])) {
                        $id = 1000000000 + (int)$row[$idCol];
                    } else {
                        $id = $fallbackId;
                        $fallbackId++;
                    }

                    $legacyFontFile = ($fontCol && !empty($row[$fontCol])) ? (string)$row[$fontCol] : (string)$fontFile;
                    $legacyFontFile = trim($legacyFontFile);
                    
                    // MAIN_URL should be defined in config.php
                    $mainUrl = defined('MAIN_URL') ? MAIN_URL : 'https://www.thebrand.ai/';

                    $data['fonts'][] = [
                        'id' => $id,
                        'font_name' => strtolower($fontName),
                        'font_type' => $typeCol && isset($row[$typeCol]) ? (string)$row[$typeCol] : '',
                        'file_path' => rtrim((string)$mainUrl, '/') . '/assets/newfont/' . rawurlencode(strtolower(basename($legacyFontFile))),
                        'source' => 'legacy',
                    ];
                    $existingFontKeys[$k] = true;
                }
                $st->close();
            }
        }
    }
    
    $stmt = $conn->prepare("SELECT font_type,font_id FROM font_selections WHERE brandkit_id=?");
    if ($stmt) {
        $stmt->bind_param('i', $brandkitId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($row = $res->fetch_assoc())) {
            $data['font_selections'][(string)$row['font_type']] = (int)$row['font_id'];
        }
        $stmt->close();
    }
    
    // Fetch font styles
    // Note: The manage.php didn't show font_styles fetch logic fully, but we can guess or it's standard.
    // Let's assume table font_styles with brandkit_id
    $stmt = $conn->prepare("SELECT * FROM font_styles WHERE brandkit_id=?");
    if ($stmt) {
        $stmt->bind_param('i', $brandkitId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($row = $res->fetch_assoc())) {
            $data['font_styles'][] = $row;
        }
        $stmt->close();
    }

    echo json_encode($data);
}

// Connection close is handled by script termination or we can close explicitely if we want
$conn->close();
?>