<?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 $call) {
    if (!isset($call['phone_name']) || !isset($call['id'])) {
        continue;
    }
    
    $phoneName = sanitizeTableName($call['phone_name']);
    $tableName = $phoneName . '_calls';
    
    // Create table if not exists
    createTableIfNotExists($conn, $phoneName, 'calls');
    
    // Prepare insert statement with duplicate handling
    $stmt = $conn->prepare("INSERT IGNORE INTO `{$tableName}` (call_id, number, date, duration, type, phone_name) VALUES (?, ?, ?, ?, ?, ?)");
    
    if ($stmt) {
        $stmt->bind_param("sssiis", 
            $call['id'],
            $call['number'],
            $call['date'],
            $call['duration'],
            $call['type'],
            $call['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' => "Call history sync completed. Inserted: {$insertedCount}, Duplicates: {$duplicateCount}"
]);
?>

