<?php
/**
 * Image Viewer Script
 * Displays uploaded images based on ID parameter
 */

require_once 'connect.php';

/**
 * Sanitize and validate image ID
 */
function validateImageId($id) {
    if (!isset($id) || empty($id)) {
        return ['valid' => false, 'error' => 'Image ID is required'];
    }
    
    if (!is_numeric($id) || $id <= 0) {
        return ['valid' => false, 'error' => 'Invalid image ID format'];
    }
    
    return ['valid' => true, 'id' => (int)$id];
}

/**
 * Get image data from database
 */
function getImageData($pdo, $imageId) {
    try {
        $stmt = $pdo->prepare("SELECT file_path FROM images WHERE id = ?");
        $stmt->execute([$imageId]);
        $result = $stmt->fetch();
        
        if (!$result) {
            return ['found' => false, 'error' => 'Image not found'];
        }
        
        return ['found' => true, 'data' => $result];
        
    } catch (PDOException $e) {
        error_log('Database error in view.php: ' . $e->getMessage());
        return ['found' => false, 'error' => 'Database error occurred'];
    }
}

/**
 * Display error page
 */
function displayError($message) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Error - Image Viewer</title>
        <style>
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                margin: 0;
                padding: 20px;
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .error-container {
                background: white;
                padding: 40px;
                border-radius: 15px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.2);
                text-align: center;
                max-width: 500px;
            }
            .error-icon {
                font-size: 4rem;
                color: #e74c3c;
                margin-bottom: 20px;
            }
            .error-message {
                color: #333;
                font-size: 1.2rem;
                margin-bottom: 20px;
            }
            .back-button {
                background: #3498db;
                color: white;
                padding: 12px 24px;
                border: none;
                border-radius: 8px;
                text-decoration: none;
                display: inline-block;
                transition: background 0.3s;
            }
            .back-button:hover {
                background: #2980b9;
            }
        </style>
    </head>
    <body>
        <div class="error-container">
            <div class="error-icon">⚠️</div>
            <div class="error-message"><?php echo htmlspecialchars($message); ?></div>
            <a href="javascript:history.back()" class="back-button">Go Back</a>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Main logic
try {
    // Check database connection
    if (!checkConnection($con)) {
        displayError('Database connection failed');
    }
    
    // Validate image ID
    $idValidation = validateImageId($_GET['id'] ?? null);
    if (!$idValidation['valid']) {
        displayError($idValidation['error']);
    }
    
    $imageId = $idValidation['id'];
    
    // Get image data
    $imageResult = getImageData($con, $imageId);
    if (!$imageResult['found']) {
        displayError($imageResult['error']);
    }
    
    $imageData = $imageResult['data'];
    
    // Check if image file exists
    if (!file_exists($imageData['file_path'])) {
        displayError('Image file not found on server');
    }
    
} catch (Exception $e) {
    error_log('General error in view.php: ' . $e->getMessage());
    displayError('An unexpected error occurred');
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #000000;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .image-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(255,255,255,0.1);
            padding: 40px;
            text-align: center;
            max-width: 90vw;
            max-height: 90vh;
            overflow: hidden;
        }
        
        .main-image {
            max-width: 100%;
            max-height: 70vh;
            object-fit: contain;
            border-radius: 8px;
        }
    </style>
</head>
<body>
    <div class="image-container">
        <img src="<?php echo htmlspecialchars($imageData['file_path']); ?>" 
             alt="Image" 
             class="main-image">
    </div>
</body>
</html>
