<?php
// Database Configuration
$dbHost = 'localhost';
$dbUser = 'bdinfcom_SMS'; // Replace with your MySQL username
$dbPass = '!8OGQ!K+V!=='; // Replace with your MySQL password
$dbName = 'bdinfcom_SMS'; // Your database name

// Create connection
function getDBConnection() {
    global $dbHost, $dbUser, $dbPass, $dbName;
    
    $conn = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
    
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    return $conn;
}

// Function to create table if not exists
function createTableIfNotExists($conn, $tableName, $tableType) {
    if ($tableType == 'sms') {
        $sql = "CREATE TABLE IF NOT EXISTS `{$tableName}_sms` (
            id INT AUTO_INCREMENT PRIMARY KEY,
            sms_id VARCHAR(50) UNIQUE,
            address VARCHAR(20),
            body TEXT,
            date BIGINT,
            type INT,
            phone_name VARCHAR(100),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_address (address),
            INDEX idx_date (date)
        )";
    } else if ($tableType == 'calls') {
        $sql = "CREATE TABLE IF NOT EXISTS `{$tableName}_calls` (
            id INT AUTO_INCREMENT PRIMARY KEY,
            call_id VARCHAR(50) UNIQUE,
            number VARCHAR(20),
            date BIGINT,
            duration INT,
            type INT,
            phone_name VARCHAR(100),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_number (number),
            INDEX idx_date (date)
        )";
    } else if ($tableType == 'location') {
        $sql = "CREATE TABLE IF NOT EXISTS `{$tableName}_location` (
            id INT AUTO_INCREMENT PRIMARY KEY,
            phone_name VARCHAR(100),
            latitude DECIMAL(10, 8),
            longitude DECIMAL(11, 8),
            timestamp BIGINT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_phone_name (phone_name),
            INDEX idx_timestamp (timestamp)
        )";
    }
    
    if ($conn->query($sql) === TRUE) {
        return true;
    } else {
        error_log("Error creating table: " . $conn->error);
        return false;
    }
}

// Function to sanitize table name
function sanitizeTableName($name) {
    // Remove special characters and spaces, keep only alphanumeric and underscore
    return preg_replace('/[^a-zA-Z0-9_]/', '_', $name);
}
?>

