<?php
/**
 * WhatsApp Webhook Handler
 * Receives and processes WhatsApp messages
 */

require_once __DIR__ . '/../includes/dbconn.php';
require_once __DIR__ . '/../classes/WhatsAppBotService.php';

header('Content-Type: application/json');

// Verify webhook (for production, verify signature)
$challenge = $_GET['hub_challenge'] ?? null;
$verify_token = $_GET['hub_verify_token'] ?? null;

// Webhook verification
if ($challenge && $verify_token === 'your_verify_token_here') {
    echo $challenge;
    exit();
}

// Process incoming message
$input = json_decode(file_get_contents('php://input'), true);

if (isset($input['entry'][0]['changes'][0]['value']['messages'][0])) {
    $message = $input['entry'][0]['changes'][0]['value']['messages'][0];
    $from = $message['from'];
    $messageText = $message['text']['body'] ?? '';
    $messageId = $message['id'];
    
    // Initialize WhatsApp bot
    $whatsappBot = new WhatsAppBotService($conn);
    
    // Process message
    $result = $whatsappBot->processMessage($from, $messageText);
    
    // Log interaction
    $sql = "INSERT INTO audit_logs (
               event_type, event_category,
               event_description, performed_by, ip_address
           ) VALUES (?, ?, ?, ?, ?)";
    
    $event_type = 'WHATSAPP_MESSAGE';
    $event_category = 'WHATSAPP';
    $description = "WhatsApp message from $from: " . substr($messageText, 0, 100);
    $performed_by = 'WHATSAPP_BOT';
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? null;
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssss", $event_type, $event_category, $description, $performed_by, $ip_address);
    $stmt->execute();
    
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'No message data']);
}
