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

require_once 'config.php';

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

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

if (!$data) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid JSON data']);
    exit;
}

$conn = getDBConnection();
$insertedCount = 0;
$duplicateCount = 0;

foreach ($data as $sms) {
    if (!isset($sms['phone_name']) || !isset($sms['id'])) {
        continue;
    }
    
    $phoneName = sanitizeTableName($sms['phone_name']);
    $tableName = $phoneName . '_sms';
    
    // Create table if not exists
    createTableIfNotExists($conn, $phoneName, 'sms');
    
    // Prepare insert statement with duplicate handling
    $stmt = $conn->prepare("INSERT IGNORE INTO `{$tableName}` (sms_id, address, body, date, type, phone_name) VALUES (?, ?, ?, ?, ?, ?)");
    
    if ($stmt) {
        $stmt->bind_param("sssiis", 
            $sms['id'],
            $sms['address'],
            $sms['body'],
            $sms['date'],
            $sms['type'],
            $sms['phone_name']
        );
        
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                $insertedCount++;
            } else {
                $duplicateCount++;
            }
        }
        
        $stmt->close();
    }
}

$conn->close();

echo json_encode([
    'success' => true,
    'inserted' => $insertedCount,
    'duplicates' => $duplicateCount,
    'message' => "SMS sync completed. Inserted: {$insertedCount}, Duplicates: {$duplicateCount}"
]);
?>

