<?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, though GET is preferred for this endpoint
header('Access-Control-Allow-Headers: Content-Type');

require_once 'config.php';

// This endpoint is primarily for GET requests to list tables,
// but we'll keep the POST check minimal if it was previously used for some reason.
// For listing tables, GET is semantically more appropriate.

$conn = getDBConnection();

// Get all tables that match our naming pattern
$result = $conn->query("SHOW TABLES");
$tables = [];

if ($result) {
    while ($row = $result->fetch_array()) {
        $tableName = $row[0];
        
        // Check if table ends with _sms, _calls, or _location
        // and extract phone name and table type
        if (preg_match('/^(.+)_(sms|calls|location)$/', $tableName, $matches)) {
            $phoneName = $matches[1];
            $tableType = $matches[2];
            
            if (!isset($tables[$phoneName])) {
                $tables[$phoneName] = [];
            }
            
            $tables[$phoneName][$tableType] = $tableName;
        }
    }
}

$conn->close();

echo json_encode([
    'success' => true,
    'tables' => $tables
]);
?>
