<?php
/**
 * Dynamic CSS Generator for Client Websites
 * Version: 3.0 - Database-driven with proper caching
 * 
 * Fetches client theme settings from client_website_themes table
 * and generates CSS variables for the website.
 */

// Allow HTTP access for localhost (bypass HTTPS redirect)
if (php_sapi_name() !== 'cli' && isset($_SERVER['HTTP_HOST'])) {
    // Allow localhost to work without HTTPS redirect
    if ($_SERVER['HTTP_HOST'] === 'localhost' || $_SERVER['HTTP_HOST'] === '127.0.0.1') {
        // No redirect - stay HTTP
    } elseif (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
        // For external requests, redirect to HTTPS
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// Get client code from query parameter
$client_code = $_GET['client'] ?? '';

// Set proper content type
header('Content-Type: text/css');
header('Cache-Control: public, max-age=3600');
header('X-Content-Type-Options: nosniff');

// If no client specified, return empty CSS
if (empty($client_code)) {
    echo "/* No client specified */\n";
    echo "body { font-family: 'Inter', sans-serif; }\n";
    exit;
}

// Database connection
try {
    require_once '/var/www/secure_configs/newtech_database_wrapper.php';
    $pdo = SecureDB::getConnectionWithFallback('NEWTECH');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    error_log("CSS Generator: DB connection failed - " . $e->getMessage());
    echo "/* Database connection error */\n";
    echo "body { font-family: 'Inter', sans-serif; }\n";
    exit;
}

// Fetch client theme settings
try {
    $stmt = $pdo->prepare("
        SELECT 
            cwt.template_name,
            cwt.primary_color,
            cwt.secondary_color,
            cwt.accent_color,
            cwt.header_bg_color,
            cwt.footer_bg_color,
            cwt.body_bg_color,
            cwt.text_color,
            cwt.heading_font,
            cwt.body_font,
            cwt.button_style,
            cwt.card_style,
            cwt.show_hero_section,
            cwt.show_testimonials,
            cwt.custom_css
        FROM client_website_themes cwt
        INNER JOIN clients c ON c.id = cwt.client_id
        WHERE c.client_code = ?
        LIMIT 1
    ");
    $stmt->execute([$client_code]);
    $theme = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$theme) {
        // No theme found - return minimal fallback
        echo "/* No theme found for client: " . htmlspecialchars($client_code) . " */\n";
        echo ":root {\n";
        echo "    --primary-color: #00aaff;\n";
        echo "    --secondary-color: #005580;\n";
        echo "    --accent-color: #ff6b00;\n";
        echo "}\n\n";
        echo "body {\n";
        echo "    font-family: 'Inter', sans-serif;\n";
        echo "    background-color: #f5f5f5;\n";
        echo "}\n";
        exit;
    }
    
    // Generate CSS variables from theme settings
    echo "/* Generated CSS for client: " . htmlspecialchars($client_code) . " */\n";
    echo "/* Template: " . htmlspecialchars($theme['template_name']) . " */\n";
    echo "/* Generated: " . date('Y-m-d H:i:s') . " */\n\n";
    
    // CSS Custom Properties (Variables)
    echo ":root {\n";
    echo "    --primary-color: " . ($theme['primary_color'] ?? '#00aaff') . ";\n";
    echo "    --secondary-color: " . ($theme['secondary_color'] ?? '#005580') . ";\n";
    echo "    --accent-color: " . ($theme['accent_color'] ?? '#ff6b00') . ";\n";
    echo "    --header-bg-color: " . ($theme['header_bg_color'] ?? '#1a1a2e') . ";\n";
    echo "    --footer-bg-color: " . ($theme['footer_bg_color'] ?? '#172b4d') . ";\n";
    echo "    --body-bg-color: " . ($theme['body_bg_color'] ?? '#f5f7fb') . ";\n";
    echo "    --text-color: " . ($theme['text_color'] ?? '#1a1f36') . ";\n";
    echo "}\n\n";
    
    // Typography
    $heading_font = $theme['heading_font'] ?? 'Inter';
    $body_font = $theme['body_font'] ?? 'Inter';
    echo "/* Typography */\n";
    echo "h1, h2, h3, h4, h5, h6 {\n";
    echo "    font-family: '{$heading_font}', 'Inter', sans-serif;\n";
    echo "}\n\n";
    echo "body {\n";
    echo "    font-family: '{$body_font}', 'Inter', sans-serif;\n";
    echo "    background-color: var(--body-bg-color);\n";
    echo "    color: var(--text-color);\n";
    echo "}\n\n";
    
    // Button Style
    $button_style = $theme['button_style'] ?? 'rounded';
    $border_radius = $button_style === 'pill' ? '999px' : ($button_style === 'rounded' ? '8px' : '2px');
    echo "/* Button Style */\n";
    echo ".btn, .btn-primary, a.btn, a.btn-primary {\n";
    echo "    border-radius: {$border_radius} !important;\n";
    echo "    background-color: var(--primary-color) !important;\n";
    echo "    border-color: var(--primary-color) !important;\n";
    echo "}\n\n";
    
    // Card Style
    $card_style = $theme['card_style'] ?? 'rounded';
    $card_border_radius = $card_style === 'elevated' ? '16px' : ($card_style === 'rounded' ? '12px' : '0px');
    echo "/* Card Style */\n";
    echo ".card, .service-card {\n";
    echo "    border-radius: {$card_border_radius};\n";
    if ($card_style === 'elevated') {
        echo "    box-shadow: 0 8px 20px rgba(0,0,0,0.08);\n";
        echo "    border: none;\n";
    }
    echo "}\n\n";
    
    // Header Background
    echo "/* Header */\n";
    echo "header {\n";
    echo "    background: var(--header-bg-color) !important;\n";
    echo "}\n\n";
    
    // Footer Background
    echo "/* Footer */\n";
    echo "footer {\n";
    echo "    background: var(--footer-bg-color) !important;\n";
    echo "}\n\n";
    
    // Custom CSS from database (if any)
    if (!empty($theme['custom_css'])) {
        echo "/* Custom CSS from theme settings */\n";
        echo $theme['custom_css'] . "\n";
    }
    
} catch (Exception $e) {
    error_log("CSS Generator error for client {$client_code}: " . $e->getMessage());
    echo "/* Error generating CSS: " . addslashes($e->getMessage()) . " */\n";
    echo ":root {\n";
    echo "    --primary-color: #00aaff;\n";
    echo "    --secondary-color: #005580;\n";
    echo "    --accent-color: #ff6b00;\n";
    echo "}\n\n";
    echo "body { font-family: 'Inter', sans-serif; }\n";
}
