<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Room Images Management - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
// Current file: /HMSPOS/rooms/rooms/images.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 2) - should go up two levels to root
$base_path = dirname(__DIR__, 2);

// Method 2: If init.php doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/init.php')) {
    // Manual calculation: /HMSPOS/rooms/rooms/ -> /HMSPOS/
    $base_path = dirname(dirname(__DIR__));
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/init.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define audit constants if not defined
if (!defined('AUDIT_UPLOAD')) define('AUDIT_UPLOAD', 'upload');
if (!defined('AUDIT_DELETE')) define('AUDIT_DELETE', 'delete');

// Define format_bytes function if it doesn't exist
if (!function_exists('format_bytes')) {
    function format_bytes($bytes) {
        if ($bytes >= 1073741824) {
            return number_format($bytes / 1073741824, 2) . ' GB';
        } elseif ($bytes >= 1048576) {
            return number_format($bytes / 1048576, 2) . ' MB';
        } elseif ($bytes >= 1024) {
            return number_format($bytes / 1024, 2) . ' KB';
        } else {
            return $bytes . ' bytes';
        }
    }
}

// Define upload_file function if it doesn't exist
if (!function_exists('upload_file')) {
    function upload_file($file, $upload_dir, $allowed_extensions) {
        $result = ['success' => false, 'filename' => '', 'errors' => []];
        
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $result['errors'][] = 'File upload error: ' . $file['error'];
            return $result;
        }
        
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, $allowed_extensions)) {
            $result['errors'][] = 'Invalid file type. Allowed: ' . implode(', ', $allowed_extensions);
            return $result;
        }
        
        $filename = uniqid() . '_' . preg_replace('/[^a-zA-Z0-9.]/', '_', $file['name']);
        $destination = $upload_dir . $filename;
        
        if (move_uploaded_file($file['tmp_name'], $destination)) {
            $result['success'] = true;
            $result['filename'] = $filename;
        } else {
            $result['errors'][] = 'Failed to move uploaded file';
        }
        
        return $result;
    }
}

// Check permission (commented out for now)
// if (function_exists('require_permission')) {
//     require_permission('rooms.images');
// }

// Set page title
$page_title = 'Room Images';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

if (!$user_id) {
    if (function_exists('redirect')) {
        redirect('login.php');
    } else {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Get room ID from URL
$room_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$room_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid room ID');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get room data
$room = null;
try {
    $room = db_fetch_one("
        SELECT r.*, rt.type_name 
        FROM rooms r 
        JOIN room_types rt ON r.room_type_id = rt.room_type_id 
        WHERE r.room_id = ?
    ", [$room_id]);
} catch (Exception $e) {
    error_log("Error fetching room: " . $e->getMessage());
}

if (!$room) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Room not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Handle image upload
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = true;
    if (function_exists('verify_csrf_token')) {
        $csrf_name = defined('CSRF_TOKEN_NAME') ? CSRF_TOKEN_NAME : 'csrf_token';
        $token = $_POST[$csrf_name] ?? '';
        if (!verify_csrf_token($token)) {
            $csrf_valid = false;
            $error = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'upload':
                if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
                    $files = $_FILES['images'];
                    $uploaded = 0;
                    $failed = 0;
                    
                    for ($i = 0; $i < count($files['name']); $i++) {
                        $file = [
                            'name' => $files['name'][$i],
                            'type' => $files['type'][$i],
                            'tmp_name' => $files['tmp_name'][$i],
                            'error' => $files['error'][$i],
                            'size' => $files['size'][$i]
                        ];
                        
                        $upload_result = upload_file(
                            $file,
                            $base_path . '/uploads/room_images/',
                            ['jpg', 'jpeg', 'png', 'gif', 'webp']
                        );
                        
                        if ($upload_result['success']) {
                            try {
                                // Check if this is the first image for this room
                                $is_first = (int)db_fetch_value("SELECT COUNT(*) FROM room_images WHERE room_id = ?", [$room_id]) == 0;
                                
                                if (function_exists('db_insert')) {
                                    db_insert('room_images', [
                                        'room_id' => $room_id,
                                        'image_path' => $upload_result['filename'],
                                        'is_primary' => $is_first ? 1 : 0,
                                        'sort_order' => 999
                                    ]);
                                } else {
                                    // Fallback direct insert
                                    $pdo = get_db_connection();
                                    $sql = "INSERT INTO room_images (room_id, image_path, is_primary, sort_order) VALUES (?, ?, ?, ?)";
                                    $stmt = $pdo->prepare($sql);
                                    $stmt->execute([
                                        $room_id,
                                        $upload_result['filename'],
                                        $is_first ? 1 : 0,
                                        999
                                    ]);
                                }
                                
                                $uploaded++;
                                
                                // Audit log
                                if (function_exists('audit_log')) {
                                    audit_log($user_id, 'upload', 'room_images', null, null, [
                                        'room_id' => $room_id,
                                        'filename' => $upload_result['filename']
                                    ]);
                                }
                            } catch (Exception $e) {
                                $failed++;
                                error_log("Error saving image record: " . $e->getMessage());
                            }
                        } else {
                            $failed++;
                            $error_details = implode(', ', $upload_result['errors']);
                            if (function_exists('log_message')) {
                                log_message("Image upload failed: $error_details", 'ERROR');
                            } else {
                                error_log("Image upload failed: $error_details");
                            }
                        }
                    }
                    
                    if ($uploaded > 0) {
                        $message = "$uploaded image(s) uploaded successfully";
                        if ($failed > 0) {
                            $message .= ", $failed failed";
                        }
                    } else {
                        $error = 'Failed to upload images';
                    }
                } else {
                    $error = 'No images selected';
                }
                break;
                
            case 'set_primary':
                $image_id = (int)($_POST['image_id'] ?? 0);
                
                if ($image_id) {
                    try {
                        // Clear primary flag for all images of this room
                        if (function_exists('db_update')) {
                            db_update('room_images', ['is_primary' => 0], 'room_id = ?', [$room_id]);
                            
                            // Set new primary
                            db_update('room_images', ['is_primary' => 1], 'image_id = ?', [$image_id]);
                            
                            $message = 'Primary image updated';
                            
                            if (function_exists('audit_log')) {
                                audit_log($user_id, 'set_primary', 'room_images', $image_id);
                            }
                        }
                    } catch (Exception $e) {
                        error_log("Error setting primary: " . $e->getMessage());
                        $error = 'Failed to update primary image';
                    }
                }
                break;
                
            case 'delete':
                $image_id = (int)($_POST['image_id'] ?? 0);
                
                if ($image_id) {
                    try {
                        // Get image info
                        $image = db_fetch_one("SELECT * FROM room_images WHERE image_id = ? AND room_id = ?", [$image_id, $room_id]);
                        
                        if ($image) {
                            // Delete file
                            $file_path = $base_path . '/uploads/room_images/' . $image['image_path'];
                            if (file_exists($file_path)) {
                                unlink($file_path);
                            }
                            
                            // Delete from database
                            if (function_exists('db_delete')) {
                                db_delete('room_images', 'image_id = ?', [$image_id]);
                            } else {
                                $pdo = get_db_connection();
                                $pdo->prepare("DELETE FROM room_images WHERE image_id = ?")->execute([$image_id]);
                            }
                            
                            // If this was primary, set another image as primary
                            if (!empty($image['is_primary'])) {
                                $new_primary = db_fetch_one("SELECT image_id FROM room_images WHERE room_id = ? ORDER BY sort_order LIMIT 1", [$room_id]);
                                if ($new_primary && function_exists('db_update')) {
                                    db_update('room_images', ['is_primary' => 1], 'image_id = ?', [$new_primary['image_id']]);
                                }
                            }
                            
                            $message = 'Image deleted successfully';
                            
                            if (function_exists('audit_log')) {
                                audit_log($user_id, 'delete', 'room_images', $image_id);
                            }
                        }
                    } catch (Exception $e) {
                        error_log("Error deleting image: " . $e->getMessage());
                        $error = 'Failed to delete image';
                    }
                }
                break;
                
            case 'update_order':
                $orders = json_decode($_POST['order'] ?? '[]', true);
                
                if (!empty($orders)) {
                    try {
                        foreach ($orders as $index => $image_id) {
                            if (function_exists('db_update')) {
                                db_update('room_images', ['sort_order' => $index + 1], 'image_id = ?', [$image_id]);
                            } else {
                                $pdo = get_db_connection();
                                $pdo->prepare("UPDATE room_images SET sort_order = ? WHERE image_id = ?")->execute([$index + 1, $image_id]);
                            }
                        }
                        
                        $message = 'Image order updated';
                    } catch (Exception $e) {
                        error_log("Error updating order: " . $e->getMessage());
                        $error = 'Failed to update image order';
                    }
                }
                break;
        }
    }
}

// Get room images
$images = [];
try {
    $images = db_fetch_all("SELECT * FROM room_images WHERE room_id = ? ORDER BY is_primary DESC, sort_order, image_id", [$room_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching images: " . $e->getMessage());
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Room Images</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Room Images</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Room Images: <?php echo htmlspecialchars($room['room_number'] ?? ''); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                    <li class="breadcrumb-item"><a href="/HMSPOS/rooms/dashboard.php">Rooms</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Rooms</a></li>
                    <li class="breadcrumb-item"><a href="view.php?id=<?php echo $room_id; ?>">View</a></li>
                    <li class="breadcrumb-item active">Images</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if (!empty($message)): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-4">
                <!-- Upload Form -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-upload me-1"></i>
                            Upload Images
                        </h3>
                    </div>
                    
                    <form method="POST" enctype="multipart/form-data">
                        <?php if (function_exists('csrf_field')): ?>
                            <?php echo csrf_field(); ?>
                        <?php else: ?>
                            <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                        <?php endif; ?>
                        <input type="hidden" name="action" value="upload">
                        
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="images" class="form-label">Select Images</label>
                                <input type="file" class="form-control" id="images" name="images[]" 
                                       multiple accept="image/jpeg,image/png,image/gif,image/webp" required>
                                <small class="text-muted">
                                    Allowed: JPG, PNG, GIF, WEBP. Max size: <?php echo function_exists('format_bytes') ? format_bytes(defined('UPLOAD_MAX_SIZE') ? UPLOAD_MAX_SIZE : 5242880) : '5 MB'; ?>
                                </small>
                            </div>
                            
                            <div id="filePreview" class="mt-3" style="display: none;">
                                <h6>Selected Files:</h6>
                                <ul class="list-group" id="fileList"></ul>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-upload me-1"></i> Upload Images
                            </button>
                            <a href="view.php?id=<?php echo $room_id; ?>" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Instructions -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Instructions
                        </h3>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="fas fa-check-circle text-success me-2"></i>
                                <strong>Primary Image:</strong> The first image will be set as primary. You can change this later.
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-arrows-alt text-info me-2"></i>
                                <strong>Drag & Drop:</strong> You can reorder images by dragging them.
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-star text-warning me-2"></i>
                                <strong>Primary Image:</strong> The star icon indicates the main image for the room.
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-trash text-danger me-2"></i>
                                <strong>Delete:</strong> Use the trash icon to remove images.
                            </li>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="col-md-8">
                <!-- Image Gallery -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-images me-1"></i>
                            Room Images (<?php echo count($images); ?>)
                        </h3>
                    </div>
                    
                    <div class="card-body">
                        <?php if (empty($images)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-image fa-4x mb-3"></i>
                                <h5>No images uploaded yet</h5>
                                <p>Upload images using the form on the left</p>
                            </div>
                        <?php else: ?>
                            <div class="row image-gallery" id="imageGallery">
                                <?php foreach ($images as $image): ?>
                                    <div class="col-md-4 col-sm-6 mb-3 image-item" data-id="<?php echo $image['image_id'] ?? 0; ?>">
                                        <div class="card card-outline card-<?php echo !empty($image['is_primary']) ? 'success' : 'secondary'; ?>">
                                            <div class="card-body p-2">
                                                <div class="position-relative">
                                                    <img src="/HMSPOS/uploads/room_images/<?php echo urlencode($image['image_path'] ?? ''); ?>" 
                                                         class="img-fluid rounded" alt="Room Image"
                                                         style="height: 150px; width: 100%; object-fit: cover;">
                                                    
                                                    <?php if (!empty($image['is_primary'])): ?>
                                                        <span class="badge bg-success position-absolute" style="top: 5px; left: 5px;">
                                                            <i class="fas fa-star"></i> Primary
                                                        </span>
                                                    <?php endif; ?>
                                                    
                                                    <div class="image-actions position-absolute" style="top: 5px; right: 5px;">
                                                        <?php if (empty($image['is_primary'])): ?>
                                                            <form method="POST" style="display: inline;">
                                                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                                <input type="hidden" name="action" value="set_primary">
                                                                <input type="hidden" name="image_id" value="<?php echo $image['image_id'] ?? 0; ?>">
                                                                <button type="submit" class="btn btn-sm btn-warning" title="Set as Primary">
                                                                    <i class="fas fa-star"></i>
                                                                </button>
                                                            </form>
                                                        <?php endif; ?>
                                                        
                                                        <form method="POST" style="display: inline;" 
                                                              onsubmit="return confirm('Delete this image?');">
                                                            <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                            <input type="hidden" name="action" value="delete">
                                                            <input type="hidden" name="image_id" value="<?php echo $image['image_id'] ?? 0; ?>">
                                                            <button type="submit" class="btn btn-sm btn-danger" title="Delete">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </form>
                                                    </div>
                                                </div>
                                                
                                                <div class="mt-2 text-center">
                                                    <small class="text-muted">
                                                        <i class="fas fa-arrows-alt drag-handle" style="cursor: move;"></i>
                                                        Drag to reorder
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <form method="POST" id="orderForm">
                                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                <input type="hidden" name="action" value="update_order">
                                <input type="hidden" name="order" id="imageOrder" value="">
                            </form>
                            
                            <div class="text-center mt-3">
                                <button type="button" class="btn btn-info" onclick="saveOrder()">
                                    <i class="fas fa-save me-1"></i> Save Order
                                </button>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Include SortableJS -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>

<script>
$(document).ready(function() {
    // File input preview
    $('#images').on('change', function() {
        const files = this.files;
        const $preview = $('#filePreview');
        const $list = $('#fileList');
        
        $list.empty();
        
        if (files.length > 0) {
            for (let i = 0; i < files.length; i++) {
                $list.append('<li class="list-group-item">' + files[i].name + ' (' + formatFileSize(files[i].size) + ')</li>');
            }
            $preview.show();
        } else {
            $preview.hide();
        }
    });
    
    // Initialize sortable
    const gallery = document.getElementById('imageGallery');
    if (gallery) {
        new Sortable(gallery, {
            animation: 150,
            handle: '.drag-handle',
            onEnd: function() {
                // Update order numbers visually
                updateOrderIndicators();
            }
        });
    }
});

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function updateOrderIndicators() {
    $('.image-item').each(function(index) {
        $(this).find('.badge-light').text('#' + (index + 1));
    });
}

function saveOrder() {
    const order = [];
    $('.image-item').each(function() {
        order.push($(this).data('id'));
    });
    
    $('#imageOrder').val(JSON.stringify(order));
    $('#orderForm').submit();
}
</script>

<style>
.image-actions {
    opacity: 0;
    transition: opacity 0.3s ease;
}
.image-item:hover .image-actions {
    opacity: 1;
}
.drag-handle {
    cursor: move;
    color: #6c757d;
}
.drag-handle:hover {
    color: #007bff;
}
.image-item .card {
    transition: transform 0.2s ease;
}
.image-item .card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
</style>

<?php
// Include footer
$footer_path = $base_path . '/views/partials/footer.php';
if (file_exists($footer_path)) {
    require_once $footer_path;
} else {
    echo '</div></div></body></html>';
}
?>