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

require_once 'config.php';

$conn = getDBConnection();

// Get parameters from GET request
$phoneName = isset($_GET['phone_name']) ? sanitizeTableName($_GET['phone_name']) : '';
$dataType = isset($_GET['data_type']) ? $_GET['data_type'] : '';
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20; // Default limit
$offset = isset($_GET['offset']) ? intval($_GET['offset']) : 0; // Default offset
$dateFrom = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$dateTo = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

if (empty($phoneName)) {
    http_response_code(400);
    echo json_encode(['error' => 'phone_name parameter is required']);
    exit;
}

if (empty($dataType) || !in_array($dataType, ['sms', 'calls', 'location'])) {
    http_response_code(400);
    echo json_encode(['error' => 'data_type parameter is required and must be "sms", "calls", or "location"']);
    exit;
}

$tableName = sanitizeTableName($phoneName) . '_' . $dataType;

// Check if table exists
$tableExists = $conn->query("SHOW TABLES LIKE '{$tableName}'");
if ($tableExists->num_rows == 0) {
    echo json_encode([
        'success' => true,
        'data' => [],
        'total' => 0,
        'message' => 'Table does not exist for this phone and data type.'
    ]);
    exit;
}

// Build WHERE clause
$whereConditions = [];
$params = [];
$types = '';

// Date filtering
if (!empty($dateFrom)) {
    // Convert YYYY-MM-DD date string to Unix timestamp in milliseconds for comparison with BIGINT 'date' or 'timestamp' columns
    $whereConditions[] = "(date >= ? OR timestamp >= ?)"; // Check both 'date' and 'timestamp' columns
    $params[] = strtotime($dateFrom) * 1000;
    $params[] = strtotime($dateFrom) * 1000;
    $types .= 'ii';
}

if (!empty($dateTo)) {
    // Convert YYYY-MM-DD date string to Unix timestamp in milliseconds
    // Add 86399999 milliseconds (23 hours, 59 minutes, 59 seconds, 999 milliseconds) to include the entire end day
    $whereConditions[] = "(date <= ? OR timestamp <= ?)"; // Check both 'date' and 'timestamp' columns
    $params[] = (strtotime($dateTo) * 1000) + 86399999;
    $params[] = (strtotime($dateTo) * 1000) + 86399999;
    $types .= 'ii';
}


// Search filtering
if (!empty($search)) {
    $searchParam = "%{$search}%";
    if ($dataType == 'sms') {
        $whereConditions[] = "(address LIKE ? OR body LIKE ?)";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $types .= 'ss';
    } else if ($dataType == 'calls') {
        $whereConditions[] = "number LIKE ?";
        $params[] = $searchParam;
        $types .= 's';
    } else if ($dataType == 'location') {
        // Search for location can be based on phone_name, or perhaps latitude/longitude ranges
        // For simplicity, we'll assume search is for phone_name for now if needed,
        // but typically location search is more complex (e.g., bounding box, radius).
        // The phone_name is already part of the table name, so direct search here might be redundant
        // unless you want to search within the phone_name column itself.
        // For now, no specific search on location data columns other than what's implicitly in table name.
    }
}

$whereClause = '';
if (!empty($whereConditions)) {
    $whereClause = 'WHERE ' . implode(' AND ', $whereConditions);
}

// Determine ID column and ORDER BY column based on data type
$idColumn = '';
$orderByColumn = '';
switch ($dataType) {
    case 'sms':
        $idColumn = 'sms_id';
        $orderByColumn = 'date';
        break;
    case 'calls':
        $idColumn = 'call_id';
        $orderByColumn = 'date';
        break;
    case 'location':
        $idColumn = 'id'; // Use auto-increment ID for location
        $orderByColumn = 'timestamp';
        break;
}

// Get total count
$countSql = "SELECT COUNT(*) as total FROM `{$tableName}` {$whereClause}";
$countStmt = $conn->prepare($countSql);

if (!empty($params)) {
    // Need to bind parameters for count query if there are any WHERE conditions
    // and ensure types string matches the number of parameters for the count query
    $countStmt->bind_param($types, ...$params);
}

$countStmt->execute();
$totalResult = $countStmt->get_result();
$total = $totalResult->fetch_assoc()['total'];
$countStmt->close();

// Get data
$sql = "SELECT * FROM `{$tableName}` {$whereClause} ORDER BY {$orderByColumn} DESC LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);

// Append limit and offset parameters and their types
$paramsForDataQuery = array_merge($params, [$limit, $offset]);
$typesForDataQuery = $types . 'ii'; // Add 'ii' for limit and offset

if (!empty($paramsForDataQuery)) {
    $stmt->bind_param($typesForDataQuery, ...$paramsForDataQuery);
}

$stmt->execute();
$result = $stmt->get_result();

$data = [];
while ($row = $result->fetch_assoc()) {
    // Format timestamp for display on the frontend
    if (isset($row['date']) && $dataType !== 'location') { // 'date' for sms/calls
        $row['formatted_date'] = date('Y-m-d H:i:s', $row['date'] / 1000);
    }
    if (isset($row['timestamp']) && $dataType === 'location') { // 'timestamp' for location
        $row['formatted_timestamp'] = date('Y-m-d H:i:s', $row['timestamp'] / 1000);
    }
    $data[] = $row;
}

$stmt->close();
$conn->close();

echo json_encode([
    'success' => true,
    'data' => $data,
    'total' => $total,
    'limit' => $limit,
    'offset' => $offset
]);
?>
