<?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'] ?? '';
    $calls = $input['calls'] ?? [];
    
    if (empty($phoneName)) {
        throw new Exception('Phone name is required');
    }
    
    if (empty($calls)) {
        echo json_encode([
            'success' => true,
            'message' => 'No WhatsApp calls to sync',
            'synced_count' => 0
        ]);
        exit;
    }
    
    $conn = getDBConnection();
    $phoneName = sanitizeTableName($phoneName);
    $tableName = $phoneName . '_whatsapp_calls';
    
    // Create table if not exists
    createWhatsAppCallsTableIfNotExists($conn, $phoneName);
    
    $syncedCount = 0;
    $stmt = $conn->prepare("INSERT IGNORE INTO `{$tableName}` (phone_name, whatsapp_id, contact, timestamp, call_result, duration, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
    
    if (!$stmt) {
        throw new Exception('Failed to prepare statement: ' . $conn->error);
    }
    
    foreach ($calls as $call) {
        $whatsappId = $call['id'] ?? 0;
        $contact = $call['contact'] ?? '';
        $timestamp = $call['timestamp'] ?? 0;
        $callResult = $call['callResult'] ?? 1;
        $duration = $call['duration'] ?? 0;
        
        // Clean contact number (remove @s.whatsapp.net suffix)
        $contact = preg_replace('/@.*$/', '', $contact);
        
        $stmt->bind_param("sisiii", 
            $phoneName,
            $whatsappId,
            $contact,
            $timestamp,
            $callResult,
            $duration
        );
        
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                $syncedCount++;
            }
        } else {
            error_log("Failed to insert WhatsApp call: " . $stmt->error);
        }
    }
    
    $stmt->close();
    $conn->close();
    
    echo json_encode([
        'success' => true,
        'message' => 'WhatsApp calls synced successfully',
        'synced_count' => $syncedCount,
        'total_calls' => count($calls)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

function createWhatsAppCallsTableIfNotExists($conn, $phoneName) {
    $tableName = $phoneName . '_whatsapp_calls';
    
    $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,
        timestamp BIGINT NOT NULL,
        call_result INT DEFAULT 1,
        duration BIGINT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_call (whatsapp_id, contact),
        INDEX idx_timestamp (timestamp),
        INDEX idx_contact (contact),
        INDEX idx_call_result (call_result)
    )";
    
    if (!$conn->query($sql)) {
        throw new Exception('Failed to create WhatsApp calls table: ' . $conn->error);
    }
}
?>

