<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'config.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    $phoneName = $input['phone_name'] ?? '';
    $messages = $input['messages'] ?? [];
    
    if (empty($phoneName)) {
        throw new Exception('Phone name is required');
    }
    
    if (empty($messages)) {
        echo json_encode([
            'success' => true,
            'message' => 'No WhatsApp messages to sync',
            'synced_count' => 0
        ]);
        exit;
    }
    
    $conn = getDBConnection();
    $phoneName = sanitizeTableName($phoneName);
    $tableName = $phoneName . '_whatsapp_messages';
    
    // Create table if not exists
    createWhatsAppMessagesTableIfNotExists($conn, $phoneName);
    
    $syncedCount = 0;
    $stmt = $conn->prepare("INSERT IGNORE INTO `{$tableName}` (phone_name, whatsapp_id, contact, message_data, timestamp, from_me, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
    
    if (!$stmt) {
        throw new Exception('Failed to prepare statement: ' . $conn->error);
    }
    
    foreach ($messages as $message) {
        $whatsappId = $message['id'] ?? 0;
        $contact = $message['contact'] ?? '';
        $messageData = $message['data'] ?? '';
        $timestamp = $message['timestamp'] ?? 0;
        $fromMe = $message['fromMe'] ?? false;
        $status = $message['status'] ?? 0;
        
        // Clean contact number (remove @s.whatsapp.net suffix)
        $contact = preg_replace('/@.*$/', '', $contact);
        
        $stmt->bind_param("sissiis", 
            $phoneName,
            $whatsappId,
            $contact,
            $messageData,
            $timestamp,
            $fromMe ? 1 : 0,
            $status
        );
        
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                $syncedCount++;
            }
        } else {
            error_log("Failed to insert WhatsApp message: " . $stmt->error);
        }
    }
    
    $stmt->close();
    $conn->close();
    
    echo json_encode([
        'success' => true,
        'message' => 'WhatsApp messages synced successfully',
        'synced_count' => $syncedCount,
        'total_messages' => count($messages)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

function createWhatsAppMessagesTableIfNotExists($conn, $phoneName) {
    $tableName = $phoneName . '_whatsapp_messages';
    
    $sql = "CREATE TABLE IF NOT EXISTS `{$tableName}` (
        id INT AUTO_INCREMENT PRIMARY KEY,
        phone_name VARCHAR(50) NOT NULL,
        whatsapp_id BIGINT NOT NULL,
        contact VARCHAR(255) NOT NULL,
        message_data TEXT,
        timestamp BIGINT NOT NULL,
        from_me TINYINT(1) DEFAULT 0,
        status INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_message (whatsapp_id, contact),
        INDEX idx_timestamp (timestamp),
        INDEX idx_contact (contact),
        INDEX idx_from_me (from_me)
    )";
    
    if (!$conn->query($sql)) {
        throw new Exception('Failed to create WhatsApp messages table: ' . $conn->error);
    }
}
?>

