<?php
header('Content-Type: application/json');

require_once 'db_connect.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $deviceName = $_POST['device_name'] ?? '';

    if (empty($deviceName)) {
        $response['success'] = false;
        $response['message'] = 'Device name is required.';
        echo json_encode($response);
        exit;
    }

    // Use the registered_devices table instead of a separate 'devices' table
    // The ensure_registered_devices_table function in add_location.php should handle table creation

    // Check if device name already exists in registered_devices
    $checkDeviceSql = $conn->prepare("SELECT device_id, table_name FROM registered_devices WHERE device_name = ?");
    $checkDeviceSql->bind_param("s", $deviceName);
    $checkDeviceSql->execute();
    $checkDeviceResult = $checkDeviceSql->get_result();

    if ($checkDeviceResult->num_rows > 0) {
        // Device name already exists, return existing device_id and table_name
        $row = $checkDeviceResult->fetch_assoc();
        $deviceId = $row['device_id'];
        $deviceTableName = $row['table_name']; // Get existing table name
        $response['success'] = true;
        $response['message'] = 'Device name already registered.';
        $response['device_id'] = $deviceId;
        $response['table_name'] = $deviceTableName; // Return table name
    } else {
        // New device name, register it in registered_devices
        $deviceId = uniqid('device_', true); // Generate a unique ID
        // Generate the device-specific table name
        // This logic should ideally be consistent with add_location.php's create_safe_table_name
        // For now, let's use a simple approach based on device_id
        $deviceTableName = "device_data_" . str_replace('.', '_', $deviceId); // Simple table name from ID

        $insertDeviceSql = $conn->prepare("INSERT INTO registered_devices (device_id, device_name, table_name) VALUES (?, ?, ?)");
        $insertDeviceSql->bind_param("sss", $deviceId, $deviceName, $deviceTableName);

        if ($insertDeviceSql->execute()) {
            // Create a new table for this device
            // Ensure the database is selected before creating the table
            $db_selected = $conn->select_db($dbname); // Assuming $dbname is available from config.php
            if (!$db_selected) {
                 // Log error and proceed to rollback
                 error_log("register_device.php: Failed to select database '$dbname': " . $conn->error);
                 // Fallback to dropping the registered device entry
                 $deleteDeviceSql = $conn->prepare("DELETE FROM registered_devices WHERE device_id = ?");
                 $deleteDeviceSql->bind_param("s", $deviceId);
                 $deleteDeviceSql->execute();
                 $response['success'] = false;
                 $response['message'] = 'Error selecting database to create device table.';
            } else {
                $createDeviceTableSql = "CREATE TABLE `$deviceTableName` (
                    id INT(11) AUTO_INCREMENT PRIMARY KEY,
                    latitude DECIMAL(10, 8) NOT NULL,
                    longitude DECIMAL(10, 8) NOT NULL,
                    status VARCHAR(50),
                    battery VARCHAR(10) DEFAULT NULL, -- Added battery column
                    timestamp DATETIME NOT NULL, -- Changed to DATETIME
                    INDEX `idx_timestamp` (`timestamp`) -- Added index
                )";

                if ($conn->query($createDeviceTableSql)) {
                    $response['success'] = true;
                    $response['message'] = 'Device registered and table created successfully.';
                    $response['device_id'] = $deviceId;
                    $response['table_name'] = $deviceTableName; // Return table name
                } else {
                    // If table creation fails, remove the device from the registered_devices table
                    $deleteDeviceSql = $conn->prepare("DELETE FROM registered_devices WHERE device_id = ?");
                    $deleteDeviceSql->bind_param("s", $deviceId);
                    $deleteDeviceSql->execute();

                    $response['success'] = false;
                    $response['message'] = 'Error creating device table: ' . $conn->error;
                }
            }
        } else {
            $response['success'] = false;
            $response['message'] = 'Error registering device: ' . $conn->error;
        }
        $insertDeviceSql->close();
    }

    $checkDeviceSql->close();

} else {
    $response['success'] = false;
    $response['message'] = 'Invalid request method.';
}

echo json_encode($response);

$conn->close();
?>
