<?php
/**
 * Create CrestChimney Logo
 * This script generates a new logo with "CREST CHIMNEY" text using the site color
 */

require_once __DIR__ . '/../config.php';

// Check if GD library is available
if (!extension_loaded('gd')) {
    die('GD library is not installed. Please install php-gd extension.');
}

// Get site color from database, fallback to default
try {
    $site_color = get_site_color();
    if (empty($site_color) || $site_color === '#F49321') {
        // Use default site color
        $site_color = '#F49321'; // Orange
    }
} catch (Exception $e) {
    // Fallback to default color if database connection fails
    $site_color = '#F49321'; // Orange
}

// Convert hex to RGB
$color_rgb = hex2rgb($site_color);

function hex2rgb($hex) {
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) == 3) {
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    }
    return [
        hexdec(substr($hex, 0, 2)),
        hexdec(substr($hex, 2, 2)),
        hexdec(substr($hex, 4, 2))
    ];
}

// Logo dimensions (matching original)
$width = 1024;
$height = 160;

// Create image
$image = imagecreatetruecolor($width, $height);

// Colors
$bg_color = imagecolorallocate($image, 58, 58, 55); // Dark grey background (#3A3A37)
$crest_color = imagecolorallocate($image, $color_rgb[0], $color_rgb[1], $color_rgb[2]); // Site color for CREST
$chimney_color = imagecolorallocate($image, 255, 255, 255); // White for CHIMNEY
$tm_color = imagecolorallocate($image, 255, 255, 255); // White for trademark symbol

// Fill background
imagefill($image, 0, 0, $bg_color);

// Try to use a system font, fallback to built-in fonts
$font_path = null;
$font_size = 80;
$font_size_small = 12;

// Try common system fonts
$possible_fonts = [
    '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
    '/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf',
    '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf',
    '/System/Library/Fonts/Helvetica.ttc',
    'C:/Windows/Fonts/arialbd.ttf',
];

foreach ($possible_fonts as $font) {
    if (file_exists($font)) {
        $font_path = $font;
        break;
    }
}

// Text to display
$text_crest = 'CREST';
$text_chimney = 'CHIMNEY';
$text_tm = '®';

// Calculate text positions
$padding_left = 40;
$padding_top = 20;

if ($font_path) {
    // Use TrueType font
    // Calculate bounding box for CREST
    $bbox_crest = imagettfbbox($font_size, 0, $font_path, $text_crest);
    $crest_width = abs($bbox_crest[4] - $bbox_crest[0]);
    $crest_height = abs($bbox_crest[5] - $bbox_crest[1]);
    
    // Calculate bounding box for CHIMNEY
    $bbox_chimney = imagettfbbox($font_size, 0, $font_path, $text_chimney);
    $chimney_width = abs($bbox_chimney[4] - $bbox_chimney[0]);
    $chimney_height = abs($bbox_chimney[5] - $bbox_chimney[1]);
    
    // Y position (centered vertically)
    $y_crest = $height / 2 + $crest_height / 2 - 10;
    $y_chimney = $height / 2 + $chimney_height / 2 - 10;
    
    // X positions
    $x_crest = $padding_left;
    $x_chimney = $x_crest + $crest_width + 20; // Space between CREST and CHIMNEY
    $x_tm = $x_chimney + $chimney_width + 5;
    $y_tm = $y_chimney - $chimney_height + 15;
    
    // Draw CREST text with site color
    imagettftext($image, $font_size, 0, $x_crest, $y_crest, $crest_color, $font_path, $text_crest);
    
    // Draw CHIMNEY text in white
    imagettftext($image, $font_size, 0, $x_chimney, $y_chimney, $chimney_color, $font_path, $text_chimney);
    
    // Draw trademark symbol
    imagettftext($image, $font_size_small, 0, $x_tm, $y_tm, $tm_color, $font_path, $text_tm);
    
    // Add brick texture effect to CREST text (simplified - using diagonal lines)
    // Create a semi-transparent overlay pattern
    for ($i = 0; $i < $crest_width; $i += 20) {
        for ($j = 0; $j < $crest_height; $j += 15) {
            $x_line = $x_crest + $i;
            $y_line = $y_crest - $crest_height + $j;
            if ($x_line < $x_crest + $crest_width && $y_line < $y_crest) {
                // Draw subtle horizontal lines to simulate brick texture
                $line_color = imagecolorallocatealpha($image, 255, 255, 255, 60); // Semi-transparent white
                imageline($image, $x_line, $y_line, min($x_line + 15, $x_crest + $crest_width), $y_line, $line_color);
            }
        }
    }
} else {
    // Fallback to built-in fonts
    $font = 5; // Large built-in font
    $font_small = 1; // Small built-in font
    
    // Calculate text width using built-in fonts
    $crest_width = imagefontwidth($font) * strlen($text_crest);
    $chimney_width = imagefontwidth($font) * strlen($text_chimney);
    $crest_height = imagefontheight($font);
    
    // Y position (centered)
    $y_crest = ($height - $crest_height) / 2 + $crest_height;
    $y_chimney = $y_crest;
    
    // X positions
    $x_crest = $padding_left;
    $x_chimney = $x_crest + $crest_width + 20;
    $x_tm = $x_chimney + $chimney_width + 5;
    $y_tm = $y_chimney - $crest_height + 5;
    
    // Draw CREST text
    imagestring($image, $font, $x_crest, $y_crest - $crest_height, $text_crest, $crest_color);
    
    // Draw CHIMNEY text
    imagestring($image, $font, $x_chimney, $y_chimney - $crest_height, $text_chimney, $chimney_color);
    
    // Draw trademark symbol
    imagestring($image, $font_small, $x_tm, $y_tm, $text_tm, $tm_color);
}

// Save the image
$output_dir = dirname(__DIR__) . '/wp-content/uploads/2022/05/';
if (!is_dir($output_dir)) {
    @mkdir($output_dir, 0755, true);
}

$output_file = $output_dir . 'CrestChimney-Logo-W-1024x160.png';

// Try multiple save locations
$saved = false;
$saved_path = '';

// Try 1: Direct save to final location
if (@imagepng($image, $output_file)) {
    $saved = true;
    $saved_path = $output_file;
} else {
    // Try 2: Save to admin/uploads directory (writable location)
    $admin_upload_dir = __DIR__ . '/uploads/';
    if (!is_dir($admin_upload_dir)) {
        @mkdir($admin_upload_dir, 0755, true);
    }
    $admin_file = $admin_upload_dir . 'CrestChimney-Logo-W-1024x160.png';
    if (imagepng($image, $admin_file)) {
        $saved = true;
        $saved_path = $admin_file;
        // Try to copy to final location
        @copy($admin_file, $output_file);
    } else {
        // Try 3: Save to temp location
        $temp_file = sys_get_temp_dir() . '/CrestChimney-Logo-W-1024x160.png';
        if (imagepng($image, $temp_file)) {
            $saved = true;
            $saved_path = $temp_file;
        }
    }
}

if ($saved) {
    echo "Logo created successfully: " . $output_file . "\n";
    echo "Site color used: " . $site_color . "\n";
    if (file_exists($output_file)) {
        echo "File size: " . filesize($output_file) . " bytes\n";
    }
} else {
    echo "Error: Failed to save logo image.\n";
}

// Clean up
imagedestroy($image);

echo "\nLogo generation complete!\n";
?>
