<?php
class Encryption {
    private static $key = 'your_encryption_key';
    private static $method = 'AES-256-CBC';
    
    public static function encrypt($data) {
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(self::$method));
        $encrypted = openssl_encrypt($data, self::$method, self::$key, 0, $iv);
        
        return base64_encode($iv . $encrypted);
    }
    
    public static function decrypt($encrypted_data) {
        $data = base64_decode($encrypted_data);
        $iv_length = openssl_cipher_iv_length(self::$method);
        $iv = substr($data, 0, $iv_length);
        $encrypted = substr($data, $iv_length);
        
        return openssl_decrypt($encrypted, self::$method, self::$key, 0, $iv);
    }
    
    public static function hashPassword($password) {
        return password_hash($password, PASSWORD_DEFAULT);
    }
    
    public static function verifyPassword($password, $hash) {
        return password_verify($password, $hash);
    }
}

function sanitizeInput($input) {
    global $con;
    return $con->real_escape_string($input);
}

function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

function generateDeviceId() {
    return 'ESP32-' . strtoupper(bin2hex(random_bytes(6)));
}

function sendJSONResponse($data, $status_code = 200) {
    http_response_code($status_code);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit();
}

function logError($message, $context = '') {
    $log_message = date('Y-m-d H:i:s') . ' - ' . $message;
    if ($context) {
        $log_message .= ' - Context: ' . $context;
    }
    
    error_log($log_message);
}

function getDeviceById($device_id) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    $sql = "SELECT * FROM devices WHERE device_id = '$device_id'";
    $result = $con->query($sql);
    
    return $result->fetch_assoc() ?? null;
}

function getUserDevices($user_id) {
    global $con;
    
    $sql = "SELECT * FROM devices WHERE owner_id = $user_id ORDER BY last_seen DESC";
    $result = $con->query($sql);
    
    $devices = [];
    while ($row = $result->fetch_assoc()) {
        $devices[] = $row;
    }
    
    return $devices;
}

function updateDeviceStatus($device_id, $status) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    $status = sanitizeInput($status);
    
    $sql = "UPDATE devices SET status = '$status', last_seen = NOW() WHERE device_id = '$device_id'";
    return $con->query($sql);
}

function saveSensorData($device_id, $sensor_id, $value, $unit = '') {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    $sensor_id = sanitizeInput($sensor_id);
    $value = sanitizeInput($value);
    $unit = sanitizeInput($unit);
    
    $sql = "INSERT INTO sensor_data (device_id, sensor_id, value, unit) 
            VALUES ('$device_id', '$sensor_id', '$value', '$unit')";
    
    return $con->query($sql);
}

function saveButtonEvent($device_id, $button_id, $action) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    $button_id = sanitizeInput($button_id);
    $action = sanitizeInput($action);
    
    $sql = "INSERT INTO button_events (device_id, button_id, action) 
            VALUES ('$device_id', '$button_id', '$action')";
    
    return $con->query($sql);
}

function getLatestSensorData($device_id, $limit = 100) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    $limit = (int)$limit;
    
    $sql = "SELECT * FROM sensor_data 
            WHERE device_id = '$device_id' 
            ORDER BY timestamp DESC 
            LIMIT $limit";
    
    $result = $con->query($sql);
    
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    
    return $data;
}

function getDeviceStatistics($device_id) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    
    $sql = "SELECT * FROM device_statistics WHERE device_id = '$device_id'";
    $result = $con->query($sql);
    
    return $result->fetch_assoc() ?? null;
}

function updateDeviceStatistics($device_id, $stats) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    
    $set_clauses = [];
    foreach ($stats as $key => $value) {
        $set_clauses[] = "$key = " . (is_numeric($value) ? $value : "'$value'");
    }
    
    $sql = "UPDATE device_statistics SET " . implode(', ', $set_clauses) . ", updated_at = NOW() WHERE device_id = '$device_id'";
    
    return $con->query($sql);
}

function initializeDeviceStatistics($device_id) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    
    $sql = "INSERT INTO device_statistics (device_id, total_reads, total_events, uptime_hours, data_points, created_at) 
            VALUES ('$device_id', 0, 0, 0, 0, NOW())
            ON DUPLICATE KEY UPDATE device_id = device_id";
    
    return $con->query($sql);
}

function getDeviceStatisticsSummary($device_id) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    
    $sql = "SELECT 
                ds.*,
                d.device_name,
                d.status as device_status
            FROM device_statistics ds
            LEFT JOIN devices d ON ds.device_id = d.device_id
            WHERE ds.device_id = '$device_id'";
    
    $result = $con->query($sql);
    
    return $result->fetch_assoc() ?? null;
}

function getSensorDataHistory($device_id, $sensor_id = null, $limit = 100) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    
    $sql = "SELECT * FROM sensor_data WHERE device_id = '$device_id'";
    
    if ($sensor_id) {
        $sensor_id = sanitizeInput($sensor_id);
        $sql .= " AND sensor_id = '$sensor_id'";
    }
    
    $sql .= " ORDER BY timestamp DESC LIMIT $limit";
    
    $result = $con->query($sql);
    
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    
    return $data;
}

function getButtonEventHistory($device_id, $button_id = null, $limit = 100) {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    
    $sql = "SELECT * FROM button_events WHERE device_id = '$device_id'";
    
    if ($button_id) {
        $button_id = sanitizeInput($button_id);
        $sql .= " AND button_id = '$button_id'";
    }
    
    $sql .= " ORDER BY timestamp DESC LIMIT $limit";
    
    $result = $con->query($sql);
    
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    
    return $data;
}

function deleteDeviceData($device_id, $data_type = 'all') {
    global $con;
    
    $device_id = sanitizeInput($device_id);
    
    switch ($data_type) {
        case 'sensor_data':
            $sql = "DELETE FROM sensor_data WHERE device_id = '$device_id'";
            break;
        case 'button_events':
            $sql = "DELETE FROM button_events WHERE device_id = '$device_id'";
            break;
        case 'statistics':
            $sql = "DELETE FROM device_statistics WHERE device_id = '$device_id'";
            break;
        case 'all':
            $sql = "DELETE FROM sensor_data WHERE device_id = '$device_id';
                   DELETE FROM button_events WHERE device_id = '$device_id';
                   DELETE FROM device_statistics WHERE device_id = '$device_id'";
            break;
        default:
            return false;
    }
    
    return $con->query($sql);
}
?>
