<?php
/**
 * Load Conversation API
 * Retrieves conversation history with all messages
 * Requires authentication for staff access
 */

session_start();
header('Content-Type: application/json');

// Check authentication
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit();
}

include '../layouts/dbconn.php';

// Get conversation ID from query parameter
$conversation_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($conversation_id <= 0) {
    echo json_encode(['success' => false, 'error' => 'Invalid conversation ID']);
    exit();
}

try {
    // Get conversation details
    $stmt = $conn->prepare("
        SELECT 
            cc.*,
            u.full_name as user_name,
            u.email as user_email,
            u.phone_primary as user_phone
        FROM chatbot_conversations cc
        LEFT JOIN users u ON cc.user_id = u.user_id
        WHERE cc.id = ?
    ");
    $stmt->bind_param("i", $conversation_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'error' => 'Conversation not found']);
        exit();
    }
    
    $conversation = $result->fetch_assoc();
    $stmt->close();
    
    // Get all messages for this conversation
    $stmt = $conn->prepare("
        SELECT 
            id,
            sender_type,
            message_text,
            message_type,
            intent,
            confidence_score,
            metadata,
            created_at
        FROM chatbot_messages
        WHERE conversation_id = ?
        ORDER BY created_at ASC
    ");
    $stmt->bind_param("i", $conversation_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $messages = [];
    while ($row = $result->fetch_assoc()) {
        $messages[] = [
            'id' => $row['id'],
            'sender_type' => $row['sender_type'],
            'message_text' => $row['message_text'],
            'message_type' => $row['message_type'],
            'intent' => $row['intent'],
            'confidence_score' => $row['confidence_score'],
            'metadata' => $row['metadata'] ? json_decode($row['metadata'], true) : null,
            'created_at' => $row['created_at'],
            'formatted_time' => date('M j, Y g:i A', strtotime($row['created_at']))
        ];
    }
    $stmt->close();
    
    // Get analytics if available
    $stmt = $conn->prepare("
        SELECT 
            intent,
            resolved,
            resolution_time,
            escalated,
            user_satisfied,
            session_duration,
            message_count
        FROM chatbot_analytics
        WHERE conversation_id = ?
    ");
    $stmt->bind_param("i", $conversation_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $analytics = null;
    if ($result->num_rows > 0) {
        $analytics = $result->fetch_assoc();
    }
    $stmt->close();
    
    // Calculate session duration if not in analytics
    if (!$analytics || !$analytics['session_duration']) {
        $start = new DateTime($conversation['started_at']);
        $end = new DateTime($conversation['last_activity']);
        $duration = $end->getTimestamp() - $start->getTimestamp();
    } else {
        $duration = $analytics['session_duration'];
    }
    
    // Prepare response
    $output = [
        'success' => true,
        'conversation' => [
            'id' => $conversation['id'],
            'session_id' => $conversation['session_id'],
            'user_id' => $conversation['user_id'],
            'user_name' => $conversation['user_name'] ?: 'Guest User',
            'user_email' => $conversation['user_email'],
            'user_phone' => $conversation['user_phone'],
            'user_type' => $conversation['user_type'],
            'status' => $conversation['status'],
            'started_at' => $conversation['started_at'],
            'last_activity' => $conversation['last_activity'],
            'duration' => $duration,
            'duration_formatted' => formatDuration($duration),
            'ip_address' => $conversation['ip_address'],
            'sentiment_score' => $conversation['sentiment_score']
        ],
        'messages' => $messages,
        'analytics' => $analytics,
        'summary' => [
            'total_messages' => count($messages),
            'user_messages' => count(array_filter($messages, fn($m) => $m['sender_type'] === 'user')),
            'bot_messages' => count(array_filter($messages, fn($m) => $m['sender_type'] === 'bot')),
            'agent_messages' => count(array_filter($messages, fn($m) => $m['sender_type'] === 'agent'))
        ]
    ];
    
    echo json_encode($output);
    
} catch (Exception $e) {
    error_log('Load conversation error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => 'An error occurred while loading the conversation'
    ]);
}

/**
 * Format duration in human-readable format
 */
function formatDuration($seconds) {
    if ($seconds < 60) {
        return $seconds . ' seconds';
    } elseif ($seconds < 3600) {
        $minutes = floor($seconds / 60);
        return $minutes . ' minute' . ($minutes != 1 ? 's' : '');
    } else {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        return $hours . ' hour' . ($hours != 1 ? 's' : '') . 
               ($minutes > 0 ? ' ' . $minutes . ' min' : '');
    }
}
?>