<?php
require_once 'includes/init.php';

// Check if user is authenticated
if (!isAuthenticated()) {
    redirect(APP_URL . '/login.php');
}

// Handle icon download requests
if (isset($_GET['download']) && isset($_GET['format'])) {
    $format = strtolower($_GET['format']);
    $text = $_GET['text'] ?? 'QR';
    $bgColor = $_GET['bg_color'] ?? '#1162d4';
    $bgColor2 = $_GET['bg_color_2'] ?? '#0d4fa8';
    $textColor = $_GET['text_color'] ?? '#ffffff';
    $size = intval($_GET['size'] ?? 128);
    
    // Validate inputs
    $text = substr($text, 0, 3); // Max 3 characters
    $size = in_array($size, [32, 64, 128, 256, 512]) ? $size : 128;
    
    // Set content type based on format
    switch ($format) {
        case 'png':
            header('Content-Type: image/png');
            header('Content-Disposition: attachment; filename="icon-' . $size . 'x' . $size . '.png');
            echo generatePNG($text, $bgColor, $bgColor2, $textColor, $size);
            break;
            
        case 'svg':
            header('Content-Type: image/svg+xml');
            header('Content-Disposition: attachment; filename="icon-' . $size . 'x' . $size . '.svg');
            echo generateSVG($text, $bgColor, $bgColor2, $textColor, $size);
            break;
            
        case 'ico':
            header('Content-Type: image/x-icon');
            header('Content-Disposition: attachment; filename="icon-' . $size . 'x' . $size . '.ico');
            echo generateICO($text, $bgColor, $bgColor2, $textColor, $size);
            break;
            
        default:
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Unsupported format']);
            break;
    }
    exit;
}

// Generate PNG icon using GD library
function generatePNG($text, $bgColor, $bgColor2, $textColor, $size) {
    $image = imagecreatetruecolor($size, $size);
    
    // Create gradient
    for ($y = 0; $y < $size; $y++) {
        $color1 = hexToRgb($bgColor);
        $color2 = hexToRgb($bgColor2);
        
        $r1 = $color1['r'] + ($color2['r'] - $color1['r']) * ($y / ($size - 1));
        $g1 = $color1['g'] + ($color2['g'] - $color1['g']) * ($y / ($size - 1));
        $b1 = $color1['b'] + ($color2['b'] - $color1['b']) * ($y / ($size - 1));
        
        $color = imagecolorallocate($image, $r1, $g1, $b1);
        imageline($image, 0, $y, $size - 1, $y, $color);
    }
    
    // Add text
    $textColorRgb = hexToRgb($textColor);
    $textColor = imagecolorallocate($image, $textColor['r'], $textColor['g'], $textColor['b']);
    
    $fontSize = $size * 0.4;
    $fontFile = 'C:\\Windows\\Fonts\\arial.ttf';
    
    // Try to load font
    if (file_exists($fontFile)) {
        $font = imagettfbbox($fontFile, $fontSize, 0, 0, $fontSize, 0);
        imagettft($image, $fontSize, 0, 0, $fontSize, $fontSize, $textColor, $font);
    } else {
        // Fallback to built-in font
        imagettft($image, $fontSize, 0, 0, $fontSize, $fontSize, $textColor, $font);
    }
    
    // Center text
    $textBox = imagettfbbox($image, $fontSize, 0, 0, $fontSize, $fontSize);
    $textWidth = imagettfbbox($image, $fontSize, 0, 0, $fontSize, $fontSize, $text);
    imagettft($image, $fontSize, 0, ($size - $textWidth) / 2, $fontSize, $textColor, $font);
    
    imagettft($image, $fontSize, 0, ($size - $textWidth) / 2, $fontSize, $textColor, $font);
    
    // Output image
    imagepng($image);
    imagedestroy($image);
}

// Generate SVG icon
function generateSVG($text, $bgColor, $bgColor2, $textColor, $size) {
    $svg = <<<SVG
<svg width="{$size}" height="{$size}" xmlns="http://www.w3.org/2000/svg">
    <defs>
        <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" style="stop-color:{$bgColor}"/>
            <stop offset="100%" style="stop-color:{$bgColor2}"/>
        </linearGradient>
    </defs>
    <rect width="{$size}" height="{$size}" fill="url(#gradient)" rx="{$size * 0.2}"/>
    <text x="50%" y="50%" text-anchor="middle" dy=".3em" 
          font-family="Arial" font-size="{$size * 0.4}" font-weight="bold" 
          fill="{$textColor}" text-anchor="middle">{$text}</text>
</svg>
SVG;
    
    return $svg;
}

// Generate ICO icon (simplified version)
function generateICO($text, $bgColor, $bgColor2, $textColor, $size) {
    // For simplicity, we'll create a PNG and suggest using online converters
    return generatePNG($text, $bgColor, $bgColor2, $textColor, $size);
}

// Convert hex color to RGB
function hexToRgb($hex) {
    $hex = ltrim($hex, '#');
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    
    return ['r' => $r, 'g' => $g, 'b' => $b];
}

include 'includes/footer.php';
?>
