<?php
require_once 'config.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);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

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

if (!isset($input['phone_name']) || !isset($input['messages'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Missing required fields']);
    exit;
}

$phone_name = $input['phone_name'];
$messages = $input['messages'];

try {
    $pdo = new PDO($dsn, $username, $password, $options);
    
    // Create table for this phone if it doesn't exist
    $table_name = $phone_name . '_whatsapp_business_messages';
    $create_table_sql = "CREATE TABLE IF NOT EXISTS `$table_name` (
        id BIGINT PRIMARY KEY,
        contact VARCHAR(255),
        message_data TEXT,
        timestamp BIGINT,
        from_me BOOLEAN,
        status INT,
        formatted_date VARCHAR(50),
        message_type VARCHAR(20),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_timestamp (timestamp),
        INDEX idx_contact (contact),
        INDEX idx_from_me (from_me)
    )";
    
    $pdo->exec($create_table_sql);
    
    // Prepare insert statement
    $insert_sql = "INSERT INTO `$table_name` (id, contact, message_data, timestamp, from_me, status, formatted_date, message_type) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?) 
                   ON DUPLICATE KEY UPDATE 
                   contact = VALUES(contact),
                   message_data = VALUES(message_data),
                   timestamp = VALUES(timestamp),
                   from_me = VALUES(from_me),
                   status = VALUES(status),
                   formatted_date = VALUES(formatted_date),
                   message_type = VALUES(message_type)";
    
    $stmt = $pdo->prepare($insert_sql);
    
    $inserted_count = 0;
    foreach ($messages as $message) {
        // Clean contact (remove @s.whatsapp.net suffix)
        $contact = isset($message['contact']) ? $message['contact'] : 'Unknown';
        $contact = str_replace('@s.whatsapp.net', '', $contact);
        
        // Format timestamp
        $timestamp = isset($message['timestamp']) ? $message['timestamp'] : time() * 1000;
        $formatted_date = date('Y-m-d H:i:s', $timestamp / 1000);
        
        // Determine message type
        $from_me = isset($message['fromMe']) ? $message['fromMe'] : false;
        $message_type = $from_me ? 'Sent' : 'Received';
        
        $stmt->execute([
            $message['id'] ?? 0,
            $contact,
            $message['data'] ?? '',
            $timestamp,
            $from_me ? 1 : 0,
            $message['status'] ?? 0,
            $formatted_date,
            $message_type
        ]);
        
        $inserted_count++;
    }
    
    echo json_encode([
        'success' => true, 
        'message' => "WhatsApp Business messages synced successfully",
        'inserted_count' => $inserted_count,
        'table_name' => $table_name
    ]);
    
} catch (PDOException $e) {
    error_log("WhatsApp Business Messages Sync Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>

