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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'config.php';

try {
    $phoneName = $_GET['phone_name'] ?? '';
    $dataType = $_GET['data_type'] ?? 'messages'; // 'messages' or 'calls'
    $limit = (int)($_GET['limit'] ?? 100);
    $offset = (int)($_GET['offset'] ?? 0);
    $search = $_GET['search'] ?? '';
    $dateFrom = $_GET['date_from'] ?? '';
    $dateTo = $_GET['date_to'] ?? '';
    
    if (empty($phoneName)) {
        throw new Exception('Phone name is required');
    }
    
    $conn = getDBConnection();
    $phoneName = sanitizeTableName($phoneName);
    
    if ($dataType === 'messages') {
        $tableName = $phoneName . '_whatsapp_messages';
        $data = getWhatsAppMessages($conn, $tableName, $limit, $offset, $search, $dateFrom, $dateTo);
    } else if ($dataType === 'calls') {
        $tableName = $phoneName . '_whatsapp_calls';
        $data = getWhatsAppCalls($conn, $tableName, $limit, $offset, $search, $dateFrom, $dateTo);
    } else {
        throw new Exception('Invalid data type. Use "messages" or "calls"');
    }
    
    $conn->close();
    
    echo json_encode([
        'success' => true,
        'data' => $data['records'],
        'total' => $data['total'],
        'limit' => $limit,
        'offset' => $offset
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'data' => [],
        'total' => 0
    ]);
}

function getWhatsAppMessages($conn, $tableName, $limit, $offset, $search, $dateFrom, $dateTo) {
    // Check if table exists
    $result = $conn->query("SHOW TABLES LIKE '{$tableName}'");
    if ($result->num_rows === 0) {
        return ['records' => [], 'total' => 0];
    }
    
    // Build WHERE clause
    $whereConditions = [];
    $params = [];
    $types = '';
    
    if (!empty($search)) {
        $whereConditions[] = "(contact LIKE ? OR message_data LIKE ?)";
        $searchParam = '%' . $search . '%';
        $params[] = $searchParam;
        $params[] = $searchParam;
        $types .= 'ss';
    }
    
    if (!empty($dateFrom)) {
        $dateFromTimestamp = strtotime($dateFrom) * 1000; // Convert to milliseconds
        $whereConditions[] = "timestamp >= ?";
        $params[] = $dateFromTimestamp;
        $types .= 'i';
    }
    
    if (!empty($dateTo)) {
        $dateToTimestamp = (strtotime($dateTo) + 86400) * 1000; // End of day in milliseconds
        $whereConditions[] = "timestamp < ?";
        $params[] = $dateToTimestamp;
        $types .= 'i';
    }
    
    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    // Get total count
    $countSql = "SELECT COUNT(*) as total FROM `{$tableName}` {$whereClause}";
    $countStmt = $conn->prepare($countSql);
    
    if (!empty($params)) {
        $countStmt->bind_param($types, ...$params);
    }
    
    $countStmt->execute();
    $totalResult = $countStmt->get_result();
    $total = $totalResult->fetch_assoc()['total'];
    $countStmt->close();
    
    // Get records
    $sql = "SELECT id, contact, message_data, timestamp, from_me, status, created_at 
            FROM `{$tableName}` 
            {$whereClause} 
            ORDER BY timestamp DESC 
            LIMIT ? OFFSET ?";
    
    $stmt = $conn->prepare($sql);
    
    $params[] = $limit;
    $params[] = $offset;
    $types .= 'ii';
    
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $records = [];
    while ($row = $result->fetch_assoc()) {
        $row['formatted_date'] = date('Y-m-d H:i:s', $row['timestamp'] / 1000);
        $row['message_type'] = $row['from_me'] ? 'Sent' : 'Received';
        $records[] = $row;
    }
    
    $stmt->close();
    
    return ['records' => $records, 'total' => $total];
}

function getWhatsAppCalls($conn, $tableName, $limit, $offset, $search, $dateFrom, $dateTo) {
    // Check if table exists
    $result = $conn->query("SHOW TABLES LIKE '{$tableName}'");
    if ($result->num_rows === 0) {
        return ['records' => [], 'total' => 0];
    }
    
    // Build WHERE clause
    $whereConditions = [];
    $params = [];
    $types = '';
    
    if (!empty($search)) {
        $whereConditions[] = "contact LIKE ?";
        $searchParam = '%' . $search . '%';
        $params[] = $searchParam;
        $types .= 's';
    }
    
    if (!empty($dateFrom)) {
        $dateFromTimestamp = strtotime($dateFrom) * 1000; // Convert to milliseconds
        $whereConditions[] = "timestamp >= ?";
        $params[] = $dateFromTimestamp;
        $types .= 'i';
    }
    
    if (!empty($dateTo)) {
        $dateToTimestamp = (strtotime($dateTo) + 86400) * 1000; // End of day in milliseconds
        $whereConditions[] = "timestamp < ?";
        $params[] = $dateToTimestamp;
        $types .= 'i';
    }
    
    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    // Get total count
    $countSql = "SELECT COUNT(*) as total FROM `{$tableName}` {$whereClause}";
    $countStmt = $conn->prepare($countSql);
    
    if (!empty($params)) {
        $countStmt->bind_param($types, ...$params);
    }
    
    $countStmt->execute();
    $totalResult = $countStmt->get_result();
    $total = $totalResult->fetch_assoc()['total'];
    $countStmt->close();
    
    // Get records
    $sql = "SELECT id, contact, timestamp, call_result, duration, created_at 
            FROM `{$tableName}` 
            {$whereClause} 
            ORDER BY timestamp DESC 
            LIMIT ? OFFSET ?";
    
    $stmt = $conn->prepare($sql);
    
    $params[] = $limit;
    $params[] = $offset;
    $types .= 'ii';
    
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $records = [];
    while ($row = $result->fetch_assoc()) {
        $row['formatted_date'] = date('Y-m-d H:i:s', $row['timestamp'] / 1000);
        $row['call_type'] = getCallTypeText($row['call_result']);
        $row['formatted_duration'] = formatDuration($row['duration']);
        $records[] = $row;
    }
    
    $stmt->close();
    
    return ['records' => $records, 'total' => $total];
}

function getCallTypeText($callResult) {
    switch ($callResult) {
        case 1: return 'Answered';
        case 2: return 'Missed';
        case 3: return 'Outgoing';
        default: return 'Unknown';
    }
}

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

