<?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['calls'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Missing required fields']);
    exit;
}

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

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

function formatDuration($seconds) {
    if ($seconds < 60) {
        return $seconds . 's';
    } elseif ($seconds < 3600) {
        $minutes = floor($seconds / 60);
        $secs = $seconds % 60;
        return $minutes . 'm ' . $secs . 's';
    } else {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        $secs = $seconds % 60;
        return $hours . 'h ' . $minutes . 'm ' . $secs . 's';
    }
}

function getCallType($callResult) {
    switch ($callResult) {
        case 1:
            return 'Answered';
        case 2:
            return 'Missed';
        case 3:
            return 'Declined';
        case 4:
            return 'Busy';
        case 5:
            return 'Video Call';
        default:
            return 'Unknown';
    }
}
?>

