<?php
/**
 * AI Chat Backend API for Luftglanz Website
 * This script handles SUITABLE SURFACES: All waterproof surfaces (roofs, terraces, facades, etc.)
IMPORTANT: AGO Quart is also SAFE for solar panels! According to the manufacturer: \"Sie können die Solar-Platten bedenkenlos einsprühen. Unser AGO Quart greift dies nicht an. Es wird auch sehr erfolgreich von Firmen eingesetzt, die Solaranlagen reinigen.\"

BENEFITS:nAI API calls securely from the server side
 */

// CORS headers for frontend access
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Get request data
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['message']) || empty(trim($input['message']))) {
    http_response_code(400);
    echo json_encode(['error' => 'Message is required']);
    exit;
}

$userMessage = trim($input['message']);
$conversationHistory = $input['history'] ?? [];

// OpenAI API configuration
$apiKey = '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';
$apiUrl = 'https://api.openai.com/v1/chat/completions';

// Product knowledge base
$productKnowledge = "
LUFTGLANZ PRODUCT KNOWLEDGE BASE:

1. COMPANY: Luftglanz - Professional drone-based roof and surface cleaning services

2. MAIN PRODUCTS:

A) AGO QUART GRÜNBELAGENTFERNER (Green algae and lichen remover)

PRODUCT DETAILS:
- Name: AGO Quart Algenentferner, Grünbelag- und Flechtenentferner
- Function: Highly effective against algae, green deposits, and lichens
- Active period: Up to 18 months continuous protection
- Application: Apply only on dry surfaces, no rain for 8 hours after application
- Coverage: 0.5L bottle covers approximately 100m² surface area
- Price: 19,90 € (39,80 € per liter)

MIXING RATIOS:
- Light deposits: 1:20 with water
- Heavy deposits (black algae, lichens): 1:10 with water

INGREDIENTS: Water, Benzalkonium-Chlorides, Tideceth-8, Cocamidopropyl-Betaine, Isopropyl-Alcohol

APPLICATION PROCESS:
1. Apply only on dry surfaces
2. Ensure no rain for minimum 8 hours after application
3. Works on surface level, not suitable for moss removal in joints/cracks
4. Cleaning duration depends on contamination severity
5. Active for up to 18 months, provides thorough cleaning and prevents recontamination
6. Never rinse with water after application - product must bind with surface

EFFECTIVENESS TIMELINE:
- Green deposits: Disappear within days
- Red/black algae: Several months for significant improvement
- Heavy lichen contamination: Up to 2 years for complete removal

SUITABLE SURFACES: All waterproof surfaces (roofs, terraces, facades, etc.)

BENEFITS:
- No high-pressure cleaning needed
- No scrubbing required
- Chlorine and acid-free
- Gentle cleaning without material damage
- Long-term protection against recontamination
- Self-cleaning effect through weather interaction

B) MELLERUD PHOTOVOLTAIK & SOLARANLAGEN REINIGER KONZENTRAT

PRODUCT DETAILS:
- Name: Mellerud Photovoltaik & Solaranlagen Reiniger Konzentrat
- Size: 0.5L concentrate
- Price: 8,99 € (17,98 € per liter)
- Function: Gentle and effective cleaning solution specifically for solar panels and photovoltaic systems
- Removes: Dust, general dirt, soot residues, fine dust, and pollen
- Special features: Streak-free, residue-free cleaning with water-repellent protection

MIXING RATIO:
- Standard cleaning: 1:20 with water (ideally distilled water)

INGREDIENTS & SPECS:
- Composition: Aqueous mixture of surfactants, complexing agents, and effectiveness enhancers
- pH value: 5.70 - 6.50
- Density: 1.020 kg/l

APPLICATION PROCESS:
1. Remove coarse dirt, leaves, and debris by lightly sweeping (avoid intensive scrubbing)
2. Mix concentrate 1:20 with water (preferably distilled water)
3. Apply carefully with specialized solar/PV equipment, soft sponge, cloth, or squeegee
4. Allow to work briefly
5. Rinse thoroughly with clear water (preferably distilled water)

SUITABLE EQUIPMENT:
- Specialized equipment for solar and PV systems
- Particularly soft sponges
- Soft cloths or squeegees
- Avoid intensive scrubbing to prevent damage

BENEFITS:
- Improves performance and lifespan of solar systems
- Creates sustainable protection against re-contamination through water-repellent effect
- Gentle cleaning without damage to sensitive modules
- Streak-free and residue-free results
- Suitable for all types of solar and PV panels

SAFETY INFORMATION:
- Causes severe eye irritation
- Keep out of reach of children
- Wash hands thoroughly after use
- In case of eye contact: rinse gently with water for several minutes
- Remove contact lenses if present and continue rinsing
- If eye irritation persists: seek medical advice

WHY DISTILLED WATER?
- Minimizes residues and promotes streak-free cleaning
- Supports optimal care of PV and solar systems

DRONE SERVICES:
- Professional application using drones for hard-to-reach areas
- Precise, even distribution of both AGO Quart and Mellerud products
- Safe application on steep roofs and high buildings
- Cost-effective compared to traditional scaffolding methods
- Specialized equipment for solar panel cleaning via drone

SAFETY INFORMATION:
- Use biocides safely
- Always read labeling and product information
- AGO Quart: Causes skin irritation (H315), serious eye damage (H318), very toxic to aquatic organisms (H410)
- Mellerud: Causes severe eye irritation, keep away from children

CONTACT INFORMATION:
AGO: AGO Sauberkeit für Haus und Garten! GmbH & Co. KG, Brilloner Str. 39, 59909 Bestwig
Phone: 02904 / 98 98 98-0, Email: info@agoshop.de

Mellerud: MELLERUD CHEMIE GMBH, Bernhard-Röttgen-Waldweg 20, 41379 Brüggen
Phone: +49 (0) 2163 / 950 90 999, Email: shop@mellerud.de, experten-service@mellerud.de
";

$systemPrompt = "Du bist ein hilfsreicher KI-Assistent für Luftglanz, ein Unternehmen für professionelle Drohnen-basierte Dach- und Oberflächenreinigung. 

WICHTIGE ANWEISUNGEN:
- Antworte immer auf Deutsch
- Verwende IMMER die höfliche Anrede \"Sie\" (niemals \"du\" oder \"dir\")
- Sei freundlich, professionell und hilfsbereit
- Nutze AUSSCHLIESSLICH die bereitgestellten Produktinformationen für präzise Antworten
- Gib konkrete Produktdetails, Preise und Anwendungshinweise aus der Wissensbasis
- Bei Fragen zu Solaranlagen: Erkläre dass SOWOHL AGO Quart ALS AUCH Mellerud geeignet sind
- AGO Quart: Laut Hersteller sicher für Solar-Platten, wird von Reinigungsfirmen eingesetzt
- Mellerud: Speziell für Solaranlagen entwickelt mit schonender Formel
- Bei Fragen zu Algen/Grünbelägen auf Dächern, empfehle AGO Quart
- Erwähne die Vorteile der Drohnen-Anwendung wenn relevant
- Erkläre Unterschiede zwischen den Produkten detailliert basierend auf der Wissensbasis
- Gib konkrete Mischungsverhältnisse und Preise an

WICHTIG: Du kennst diese BEIDEN spezifischen Produkte sehr genau:
1. AGO Quart (19,90€) - für Algen, Grünbeläge, Flechten auf Dächern/Terrassen
2. Mellerud Photovoltaik Reiniger (8,99€) - speziell für Solaranlagen

PRODUKTWISSEN: " . $productKnowledge . "

Beantworte Fragen zu:
- Unterschiede zwischen AGO Quart und Mellerud Produkten
- Spezifische Anwendung für Solaranlagen vs. Dächer
- Konkrete Preise, Mischungsverhältnisse und Reichweiten
- Drohnen-Anwendung beider Produkte
- Sicherheitshinweise für beide Produkte
- Warum destilliertes Wasser bei Mellerud wichtig ist
- Kontaktdaten beider Hersteller";

// Build messages array
$messages = [
    ['role' => 'system', 'content' => $systemPrompt]
];

// Add conversation history (last 10 messages for context)
$recentHistory = array_slice($conversationHistory, -10);
foreach ($recentHistory as $msg) {
    $messages[] = $msg;
}

// Add current user message
$messages[] = ['role' => 'user', 'content' => $userMessage];

// Prepare OpenAI request
$data = [
    'model' => 'gpt-3.5-turbo',
    'messages' => $messages,
    'max_tokens' => 500,
    'temperature' => 0.7,
    'presence_penalty' => 0.1,
    'frequency_penalty' => 0.1
];

// Make API call to OpenAI
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    http_response_code(500);
    echo json_encode(['error' => 'OpenAI API error: ' . $httpCode]);
    exit;
}

$responseData = json_decode($response, true);

if (!isset($responseData['choices'][0]['message']['content'])) {
    http_response_code(500);
    echo json_encode(['error' => 'Invalid response from OpenAI']);
    exit;
}

$assistantMessage = $responseData['choices'][0]['message']['content'];

// Return successful response
echo json_encode([
    'success' => true,
    'message' => $assistantMessage,
    'usage' => $responseData['usage'] ?? null
]);
?>
