<?php
/**
 * Autohaus-spezifische WhatsApp-Benachrichtigungen mit HelloMateo API
 * Erweiterte Version mit Multi-Autohaus-Unterstützung
 */

require_once '../config/database.php';

class AutohausWhatsAppNotifications {
    private $db;
    private $conn;
    private $autohausId;
    private $autohausSettings;
    
    public function __construct($autohausId = null) {
        $this->db = new Database();
        $this->conn = $this->db->getConnection();
        $this->autohausId = $autohausId;
        $this->autohausSettings = $this->getAutohausSettings();
    }
    
    /**
     * Sendet eine WhatsApp-Benachrichtigung für Terminstatusänderungen
     */
    public function sendAppointmentNotification($appointmentId, $action) {
        try {
            // Hole Termindetails
            $appointment = $this->getAppointmentDetails($appointmentId);
            if (!$appointment) {
                return ['success' => false, 'error' => 'Termin nicht gefunden'];
            }
            
            // Prüfe ob Telefonnummer vorhanden ist
            if (empty($appointment['phone'])) {
                return ['success' => false, 'error' => 'Keine Telefonnummer für Termin vorhanden'];
            }
            
            // Prüfe ob WhatsApp-Benachrichtigungen aktiviert sind
            if (!$this->isWhatsAppNotificationsEnabled()) {
                return ['success' => true, 'message' => 'WhatsApp-Benachrichtigungen deaktiviert'];
            }
            
            // Erstelle WhatsApp-Nachricht basierend auf Aktion
            $message = $this->createWhatsAppMessage($appointment, $action);
            
            // Debug: Log WhatsApp-Details
            error_log("WhatsApp (Autohaus) - Sende Nachricht an: " . $appointment['phone']);
            error_log("WhatsApp (Autohaus) - Nachricht: " . $message);
            error_log("WhatsApp (Autohaus) - Aktion: " . $action);
            error_log("WhatsApp (Autohaus) - Autohaus: " . $this->autohausSettings['name']);
            
            // Sende WhatsApp-Nachricht
            $result = $this->sendWhatsAppMessage($appointment['phone'], $message);
            
            error_log("WhatsApp (Autohaus) - Nachricht-Ergebnis: " . json_encode($result));
            
            return $result;
            
        } catch (Exception $e) {
            error_log("WhatsApp (Autohaus) - Nachricht-Fehler: " . $e->getMessage());
            return ['success' => false, 'error' => 'WhatsApp-Nachricht konnte nicht gesendet werden: ' . $e->getMessage()];
        }
    }
    
    /**
     * Holt Autohaus-spezifische WhatsApp-Einstellungen
     */
    private function getAutohausSettings() {
        if (!$this->autohausId) {
            // Fallback auf globale Einstellungen
            return $this->getGlobalWhatsAppSettings();
        }
        
        $stmt = $this->conn->prepare("
            SELECT a.*, 
                   a.whatsapp_notifications_enabled,
                   a.whatsapp_api_key,
                   a.whatsapp_phone_number,
                   a.whatsapp_business_name,
                   a.whatsapp_template_id,
                   a.whatsapp_test_mode
            FROM autohaus a 
            WHERE a.id = ?
        ");
        $stmt->execute([$this->autohausId]);
        $autohaus = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$autohaus) {
            return $this->getGlobalWhatsAppSettings();
        }
        
        // Verwende Autohaus-spezifische Einstellungen oder Fallback auf globale
        $globalSettings = $this->getGlobalWhatsAppSettings();
        
        return [
            'id' => $autohaus['id'],
            'name' => $autohaus['name'],
            'short_name' => $autohaus['short_name'],
            'notifications_enabled' => $autohaus['whatsapp_notifications_enabled'] ?? $globalSettings['notifications_enabled'],
            'api_key' => $autohaus['whatsapp_api_key'] ?? $globalSettings['api_key'],
            'phone_number' => $autohaus['whatsapp_phone_number'] ?? $globalSettings['phone_number'],
            'business_name' => $autohaus['whatsapp_business_name'] ?? $autohaus['name'],
            'template_id' => $autohaus['whatsapp_template_id'] ?? $globalSettings['template_id'],
            'test_mode' => $autohaus['whatsapp_test_mode'] ?? $globalSettings['test_mode']
        ];
    }
    
    /**
     * Holt globale WhatsApp-Einstellungen als Fallback
     */
    private function getGlobalWhatsAppSettings() {
        $stmt = $this->conn->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'whatsapp_%'");
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        return [
            'id' => null,
            'name' => 'Global',
            'short_name' => 'Global',
            'notifications_enabled' => $results['whatsapp_notifications_enabled'] ?? '0',
            'api_key' => $results['whatsapp_api_key'] ?? '',
            'phone_number' => $results['whatsapp_phone_number'] ?? '',
            'business_name' => $results['whatsapp_business_name'] ?? 'Boxenstop',
            'template_id' => $results['whatsapp_template_id'] ?? '',
            'test_mode' => $results['whatsapp_test_mode'] ?? '1'
        ];
    }
    
    /**
     * Holt Termindetails aus der Datenbank
     */
    private function getAppointmentDetails($appointmentId) {
        $stmt = $this->conn->prepare("
            SELECT a.*, e.name as event_name, e.event_date, e.start_time, e.end_time,
                   ah.name as autohaus_name, ah.short_name as autohaus_short_name
            FROM appointments a 
            LEFT JOIN events e ON a.event_id = e.id 
            LEFT JOIN autohaus ah ON a.autohaus_id = ah.id
            WHERE a.id = ?
        ");
        $stmt->execute([$appointmentId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Prüft ob WhatsApp-Benachrichtigungen aktiviert sind
     */
    private function isWhatsAppNotificationsEnabled() {
        return $this->autohausSettings['notifications_enabled'] == '1' || $this->autohausSettings['notifications_enabled'] == 1;
    }
    
    /**
     * Erstellt WhatsApp-Nachricht basierend auf Terminaktion
     */
    private function createWhatsAppMessage($appointment, $action) {
        $eventDate = date('d.m.Y', strtotime($appointment['event_date']));
        $eventTime = date('H:i', strtotime($appointment['slot_time']));
        $autohausName = $appointment['autohaus_name'] ?? $this->autohausSettings['name'];
        
        switch ($action) {
            case 'approved':
                return "✅ *Termin bestätigt!*\n\n" .
                       "Hallo " . $appointment['customer_name'] . ",\n\n" .
                       "Ihr Termin wurde erfolgreich bestätigt:\n\n" .
                       "🏢 *Autohaus:* " . $autohausName . "\n" .
                       "📅 *Event:* " . $appointment['event_name'] . "\n" .
                       "📅 *Datum:* " . $eventDate . "\n" .
                       "🕐 *Zeit:* " . $eventTime . "\n" .
                       "🚗 *Fahrzeug:* " . $appointment['license_plate'] . "\n" .
                       "🔢 *Einlagerungsnummer:* " . $appointment['storage_number'] . "\n\n" .
                       "Wir freuen uns auf Ihren Besuch!\n\n" .
                       "Mit freundlichen Grüßen\n" .
                       "Ihr " . $autohausName . " Team";
                       
            case 'rejected':
                return "❌ *Termin abgelehnt*\n\n" .
                       "Hallo " . $appointment['customer_name'] . ",\n\n" .
                       "Leider können wir Ihren Termin nicht bestätigen:\n\n" .
                       "🏢 *Autohaus:* " . $autohausName . "\n" .
                       "📅 *Event:* " . $appointment['event_name'] . "\n" .
                       "📅 *Datum:* " . $eventDate . "\n" .
                       "🕐 *Zeit:* " . $eventTime . "\n" .
                       "🚗 *Fahrzeug:* " . $appointment['license_plate'] . "\n\n" .
                       "Bitte kontaktieren Sie uns für alternative Termine.\n\n" .
                       "Mit freundlichen Grüßen\n" .
                       "Ihr " . $autohausName . " Team";
                       
            case 'rescheduled':
                return "📅 *Termin verschoben*\n\n" .
                       "Hallo " . $appointment['customer_name'] . ",\n\n" .
                       "Ihr Termin wurde verschoben:\n\n" .
                       "🏢 *Autohaus:* " . $autohausName . "\n" .
                       "📅 *Event:* " . $appointment['event_name'] . "\n" .
                       "📅 *Neues Datum:* " . date('d.m.Y', strtotime($appointment['slot_date'])) . "\n" .
                       "🕐 *Neue Zeit:* " . date('H:i', strtotime($appointment['slot_time'])) . "\n" .
                       "🚗 *Fahrzeug:* " . $appointment['license_plate'] . "\n\n" .
                       "Grund: " . ($appointment['reschedule_reason'] ?? 'Termin verschoben') . "\n\n" .
                       "Mit freundlichen Grüßen\n" .
                       "Ihr " . $autohausName . " Team";
                       
            case 'reminder':
                return "🔔 *Terminerinnerung*\n\n" .
                       "Hallo " . $appointment['customer_name'] . ",\n\n" .
                       "Erinnerung an Ihren Termin:\n\n" .
                       "🏢 *Autohaus:* " . $autohausName . "\n" .
                       "📅 *Event:* " . $appointment['event_name'] . "\n" .
                       "📅 *Datum:* " . $eventDate . "\n" .
                       "🕐 *Zeit:* " . $eventTime . "\n" .
                       "🚗 *Fahrzeug:* " . $appointment['license_plate'] . "\n\n" .
                       "Wir freuen uns auf Ihren Besuch!\n\n" .
                       "Mit freundlichen Grüßen\n" .
                       "Ihr " . $autohausName . " Team";
                       
            default:
                return "📱 *Termin-Update*\n\n" .
                       "Hallo " . $appointment['customer_name'] . ",\n\n" .
                       "Update zu Ihrem Termin:\n\n" .
                       "🏢 *Autohaus:* " . $autohausName . "\n" .
                       "📅 *Event:* " . $appointment['event_name'] . "\n" .
                       "📅 *Datum:* " . $eventDate . "\n" .
                       "🕐 *Zeit:* " . $eventTime . "\n" .
                       "🚗 *Fahrzeug:* " . $appointment['license_plate'] . "\n\n" .
                       "Status: " . ucfirst($action) . "\n\n" .
                       "Mit freundlichen Grüßen\n" .
                       "Ihr " . $autohausName . " Team";
        }
    }
    
    /**
     * Sendet WhatsApp-Nachricht über HelloMateo API
     */
    private function sendWhatsAppMessage($phoneNumber, $message) {
        try {
            $settings = $this->autohausSettings;
            
            // Test-Modus oder kein API Key
            if ($settings['test_mode'] || empty($settings['api_key'])) {
                return $this->sendWhatsAppTest($phoneNumber, $message, $settings);
            }
            
            // HelloMateo API Anfrage
            $data = [
                'to' => $phoneNumber,
                'message' => $message,
                'type' => 'text'
            ];
            
            // Template verwenden falls konfiguriert
            if (!empty($settings['template_id'])) {
                $data['template_id'] = $settings['template_id'];
                $data['type'] = 'template';
            }
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://integration.getmateo.com/api/v1/messages');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Authorization: Bearer ' . $settings['api_key'],
                'Content-Type: application/json'
            ]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200) {
                error_log("WhatsApp (Autohaus) - Nachricht erfolgreich gesendet an: " . $phoneNumber);
                return ['success' => true, 'message' => 'WhatsApp-Nachricht erfolgreich gesendet an ' . $phoneNumber];
            } else {
                error_log("WhatsApp (Autohaus) - Nachricht-Fehler für: " . $phoneNumber . " (HTTP: " . $httpCode . ")");
                return ['success' => false, 'error' => 'WhatsApp API Fehler (HTTP: ' . $httpCode . ')'];
            }
            
        } catch (Exception $e) {
            $errorMsg = 'WhatsApp-Fehler: ' . $e->getMessage();
            error_log("WhatsApp (Autohaus) - Nachricht-Fehler für " . $phoneNumber . ": " . $errorMsg);
            return ['success' => false, 'error' => $errorMsg];
        }
    }
    
    /**
     * Test-Modus für WhatsApp (ohne API)
     */
    private function sendWhatsAppTest($phoneNumber, $message, $settings = []) {
        try {
            // Simuliere WhatsApp-Versendung
            error_log("WhatsApp Test (Autohaus) - Nachricht an " . $phoneNumber . ": " . $message);
            error_log("WhatsApp Test (Autohaus) - Einstellungen: " . json_encode($settings));
            
            // Hier würde normalerweise die HelloMateo API aufgerufen werden
            // Für den Test simulieren wir eine erfolgreiche Versendung
            
            $mode = $settings['test_mode'] ? 'Test-Modus' : 'Kein API-Key';
            return ['success' => true, 'message' => 'WhatsApp-Nachricht erfolgreich gesendet an ' . $phoneNumber . ' (' . $mode . ')'];
            
        } catch (Exception $e) {
            error_log("WhatsApp Test (Autohaus) - Fehler für " . $phoneNumber . ": " . $e->getMessage());
            return ['success' => false, 'error' => 'WhatsApp Test-Fehler: ' . $e->getMessage()];
        }
    }
    
    /**
     * Sendet Terminerinnerungen für alle anstehenden Termine
     */
    public function sendAppointmentReminders($hoursBefore = 24) {
        try {
            $reminderTime = date('Y-m-d H:i:s', strtotime("+{$hoursBefore} hours"));
            
            $stmt = $this->conn->prepare("
                SELECT a.*, e.name as event_name, e.event_date, e.start_time, e.end_time,
                       ah.name as autohaus_name, ah.short_name as autohaus_short_name
                FROM appointments a 
                LEFT JOIN events e ON a.event_id = e.id 
                LEFT JOIN autohaus ah ON a.autohaus_id = ah.id
                WHERE a.status = 'approved' 
                AND a.slot_date = CURDATE()
                AND a.slot_time BETWEEN TIME_SUB(CURTIME(), INTERVAL 1 HOUR) AND TIME_ADD(CURTIME(), INTERVAL 1 HOUR)
                AND a.autohaus_id = ?
            ");
            $stmt->execute([$this->autohausId]);
            $appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $results = [];
            foreach ($appointments as $appointment) {
                $result = $this->sendAppointmentNotification($appointment['id'], 'reminder');
                $results[] = [
                    'appointment_id' => $appointment['id'],
                    'customer_name' => $appointment['customer_name'],
                    'result' => $result
                ];
            }
            
            return ['success' => true, 'reminders_sent' => count($results), 'results' => $results];
            
        } catch (Exception $e) {
            error_log("WhatsApp (Autohaus) - Erinnerungen-Fehler: " . $e->getMessage());
            return ['success' => false, 'error' => 'Erinnerungen konnten nicht gesendet werden: ' . $e->getMessage()];
        }
    }
}
?>
