<?php
/**
 * Branding Management Utility
 * Handles dynamic brand name retrieval and updates across the system
 */

/**
 * Extract brand name from full company name
 * e.g., "You Car Drive Car Rental Services" -> "You Car Drive"
 */
function extractBrandFromCompanyName($companyName) {
    // Remove common suffixes (case-insensitive)
    $suffixes = [
        ' Car Rental Services',
        ' Car Rental',
        ' Rental Services',
        ' Services',
        ' Inc.',
        ' Inc',
        ' LLC',
        ' Ltd.',
        ' Ltd',
        ' Corporation',
        ' Corp.'
    ];

    $brandName = $companyName;
    foreach ($suffixes as $suffix) {
        if (stripos($brandName, $suffix) !== false) {
            // Use regex for case-insensitive replacement at the end of the string
            $quotedSuffix = preg_quote($suffix, '/');
            $brandName = preg_replace('/' . $quotedSuffix . '$/i', '', $brandName);
        }
    }

    return trim($brandName);
}

/**
 * Get the current brand/company name from database
 * Returns the exact site name set by user
 */
function getBrandName() {
    static $brandName = null;
    
    if ($brandName !== null) {
        return $brandName;
    }
    
    // Default fallback
    $defaultBrand = 'VeloDrive';

    try {
        if (!function_exists('getDBConnection')) {
            return $defaultBrand;
        }

        $pdo = getDBConnection();
        if (!$pdo) return $defaultBrand;
        
        // Try to get from settings first
        $stmt = $pdo->prepare("SELECT key_value FROM settings WHERE key_name = 'site_name' LIMIT 1");
        $stmt->execute();
        $result = $stmt->fetch();
        
        if ($result && !empty($result['key_value'])) {
            $brandName = $result['key_value'];
        } else {
            // Fallback to company_info
            $stmt = $pdo->prepare("SELECT company_name FROM company_info WHERE id = 1 LIMIT 1");
            $stmt->execute();
            $result = $stmt->fetch();
            
            if ($result && !empty($result['company_name'])) {
                $brandName = $result['company_name'];
            } else {
                // Ultimate fallback
                $brandName = $defaultBrand;
            }
        }
    } catch (Throwable $e) {
        // Fallback on error
        $brandName = $defaultBrand;
    }
    
    return $brandName;
}

/**
 * Get the current site logo from database
 */
function getAppLogo() {
    static $logoUrl = null;

    if ($logoUrl !== null) {
        return $logoUrl;
    }

    try {
        if (!function_exists('getDBConnection')) {
            return null;
        }

        $pdo = getDBConnection();
        if (!$pdo) return null;

        $stmt = $pdo->prepare("SELECT key_value FROM settings WHERE key_name = 'site_logo' LIMIT 1");
        $stmt->execute();
        $result = $stmt->fetch();

        if ($result && !empty($result['key_value'])) {
            $logoUrl = $result['key_value'];
        }
    } catch (Throwable $e) {
        // Fallback on error
        $logoUrl = null;
    }

    return $logoUrl;
}

/**
 * Get short brand name (first word only)
 * Useful for compact displays
 */
function getShortBrandName() {
    $fullName = getBrandName();
    $words = explode(' ', trim($fullName));
    return $words[0];
}

/**
 * Update brand name across all files in the system
 * @param string $newBrand The new brand name to use
 * @param array $extraOldBrands Additional strings to replace (e.g. ['VeloDrive', 'DriveAdmin'])
 */
function updateBrandAcrossFiles($newBrand, $extraOldBrands = []) {
    $rootDir = dirname(dirname(__DIR__));
    $errors = [];
    $updated = [];
    
    // Get current brand to replace it too
    $currentBrand = getBrandName();

    // Build list of strings to search for
    $searchStrings = array_unique(array_merge([$currentBrand], $extraOldBrands, ['VeloDrive', 'DriveAdmin', 'Cariton']));
    // Remove empty or the new brand itself from search list
    $searchStrings = array_filter($searchStrings, function($s) use ($newBrand) {
        return !empty($s) && $s !== $newBrand;
    });

    // Automatically find all .html, .js and .css files in user, admin and driver folders
    // We avoid .php files to prevent Remote Code Execution and breaking code logic
    $userFiles = glob($rootDir . '/user/*.{html,js,css}', GLOB_BRACE) ?: [];
    $adminFiles = glob($rootDir . '/admin/*.{html,js,css}', GLOB_BRACE) ?: [];
    $adminIncludes = glob($rootDir . '/admin/includes/*.{html,js,css}', GLOB_BRACE) ?: [];
    $driverFiles = glob($rootDir . '/driver/*.{html,js,css}', GLOB_BRACE) ?: [];

    $allFiles = array_unique(array_merge($userFiles, $adminFiles, $adminIncludes, $driverFiles));
    
    foreach ($allFiles as $filePath) {
        $relativePath = str_replace($rootDir . '/', '', $filePath);
        
        // Skip this file to avoid replacing the replacement logic itself
        if ($relativePath === 'admin/includes/branding.php') {
            continue;
        }
        
        // Read file content
        $content = @file_get_contents($filePath);
        
        if ($content === false) {
            $errors[] = "Could not read file: $relativePath";
            continue;
        }
        
        $newContent = $content;
        $totalOccurrences = 0;
        
        foreach ($searchStrings as $old) {
            $count = substr_count($newContent, $old);
            if ($count > 0) {
                $newContent = str_replace($old, $newBrand, $newContent);
                $totalOccurrences += $count;
            }
        }

        if ($totalOccurrences > 0) {
            // Write back to file
            if (@file_put_contents($filePath, $newContent) !== false) {
                $updated[] = "$relativePath ($totalOccurrences occurrences)";
            } else {
                $errors[] = "Could not write to file: $relativePath";
            }
        }
    }
    
    return [
        'success' => empty($errors),
        'updated' => $updated,
        'errors' => $errors
    ];
}

/**
 * Get all brand-related settings
 */
function getBrandSettings() {
    try {
        $pdo = getDBConnection();
        if (!$pdo) throw new Exception("No DB");
        
        $stmt = $pdo->prepare("SELECT key_value FROM settings WHERE key_name = 'site_name' LIMIT 1");
        $stmt->execute();
        $siteName = $stmt->fetchColumn();
        
        $stmt = $pdo->prepare("SELECT company_name, email FROM company_info WHERE id = 1 LIMIT 1");
        $stmt->execute();
        $companyInfo = $stmt->fetch(PDO::FETCH_ASSOC);
        
        return [
            'site_name' => $siteName ?: 'VeloDrive',
            'company_name' => $companyInfo['company_name'] ?? 'VeloDrive Car Rental Services',
            'company_email' => $companyInfo['email'] ?? 'info@velodrive.com'
        ];
    } catch (Exception $e) {
        return [
            'site_name' => 'VeloDrive',
            'company_name' => 'VeloDrive Car Rental Services',
            'company_email' => 'info@velodrive.com'
        ];
    }
}
?>
