<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Edit Room - 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/edit.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_UPDATE')) {
    define('AUDIT_UPDATE', 'update');
}

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

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

// 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 * FROM rooms WHERE 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;
    }
}

// Get room types for dropdown
$room_types = [];
try {
    $room_types = db_fetch_all("SELECT room_type_id, type_code, type_name FROM room_types ORDER BY type_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $e->getMessage());
}

// Handle form submission
$errors = [];
$form_data = [
    'room_number' => $room['room_number'] ?? '',
    'room_type_id' => $room['room_type_id'] ?? 0,
    'floor' => $room['floor'] ?? '',
    'status' => $room['status'] ?? 'available',
    'housekeeping_status' => $room['housekeeping_status'] ?? 'clean',
    'notes' => $room['notes'] ?? '',
    'is_active' => $room['is_active'] ?? 1
];

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;
            $errors[] = 'Invalid security token. Please try again.';
        }
    }
    
    if ($csrf_valid) {
        // Get and validate input
        $form_data['room_number'] = isset($_POST['room_number']) ? strtoupper(trim($_POST['room_number'])) : '';
        $form_data['room_type_id'] = (int)($_POST['room_type_id'] ?? 0);
        $form_data['floor'] = $_POST['floor'] ?? '';
        $form_data['status'] = $_POST['status'] ?? 'available';
        $form_data['housekeeping_status'] = $_POST['housekeeping_status'] ?? 'clean';
        $form_data['notes'] = $_POST['notes'] ?? '';
        $form_data['is_active'] = isset($_POST['is_active']) ? 1 : 0;
        
        // Validate required fields
        if (empty($form_data['room_number'])) {
            $errors[] = 'Room number is required';
        }
        
        if (empty($form_data['room_type_id'])) {
            $errors[] = 'Room type is required';
        }
        
        // Check if room number exists for another room
        if (empty($errors)) {
            try {
                $exists = db_fetch_value(
                    "SELECT COUNT(*) FROM rooms WHERE room_number = ? AND room_id != ?",
                    [$form_data['room_number'], $room_id]
                ) ?: 0;
                if ($exists > 0) {
                    $errors[] = 'Room number already exists';
                }
            } catch (Exception $e) {
                error_log("Error checking room existence: " . $e->getMessage());
            }
        }
        
        // Check if room can be deactivated
        if (!$form_data['is_active'] && ($room['status'] ?? '') == 'occupied') {
            $errors[] = 'Cannot deactivate a room that is currently occupied';
        }
        
        // Update room
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $update_data = [
                    'room_number' => $form_data['room_number'],
                    'room_type_id' => $form_data['room_type_id'],
                    'floor' => $form_data['floor'] ?: null,
                    'status' => $form_data['status'],
                    'housekeeping_status' => $form_data['housekeeping_status'],
                    'notes' => $form_data['notes'] ?: null,
                    'is_active' => $form_data['is_active']
                ];
                
                if (function_exists('db_update')) {
                    db_update('rooms', $update_data, 'room_id = ?', [$room_id]);
                } else {
                    // Fallback direct update
                    $pdo = get_db_connection();
                    $sql = "UPDATE rooms SET room_number = ?, room_type_id = ?, floor = ?, 
                            status = ?, housekeeping_status = ?, notes = ?, is_active = ? WHERE room_id = ?";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([
                        $form_data['room_number'],
                        $form_data['room_type_id'],
                        $form_data['floor'] ?: null,
                        $form_data['status'],
                        $form_data['housekeeping_status'],
                        $form_data['notes'] ?: null,
                        $form_data['is_active'],
                        $room_id
                    ]);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($user_id, 'update', 'rooms', $room_id, $room, $update_data);
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'Room updated successfully');
                }
                
                // Redirect
                if (function_exists('redirect')) {
                    redirect('view.php?id=' . $room_id);
                } else {
                    header('Location: view.php?id=' . $room_id);
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to update room: ' . $e->getMessage();
                if (function_exists('log_message')) {
                    log_message("Room update failed: " . $e->getMessage(), 'ERROR');
                } else {
                    error_log("Room update failed: " . $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>Edit Room</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">
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
        <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>
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.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="#">Edit Room</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">Edit Room: <?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">Edit</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Error Messages -->
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        <strong>Please fix the following errors:</strong>
                        <ul class="mt-2 mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Edit Form -->
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit me-1"></i>
                            Edit Room
                        </h3>
                    </div>
                    
                    <form method="POST" id="editForm">
                        <?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; ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="room_number">Room Number <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="room_number" name="room_number" 
                                               value="<?php echo htmlspecialchars($form_data['room_number']); ?>" 
                                               maxlength="10" required>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="room_type_id">Room Type <span class="text-danger">*</span></label>
                                        <select class="form-select" id="room_type_id" name="room_type_id" required>
                                            <option value="">Select Room Type</option>
                                            <?php foreach ($room_types as $type): ?>
                                                <option value="<?php echo $type['room_type_id'] ?? 0; ?>" 
                                                        <?php echo $form_data['room_type_id'] == ($type['room_type_id'] ?? 0) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars(($type['type_name'] ?? '') . ' (' . ($type['type_code'] ?? '') . ')'); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="floor">Floor</label>
                                        <input type="text" class="form-control" id="floor" name="floor" 
                                               value="<?php echo htmlspecialchars($form_data['floor']); ?>" 
                                               maxlength="10">
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="status">Status</label>
                                        <select class="form-select" id="status" name="status">
                                            <option value="available" <?php echo $form_data['status'] == 'available' ? 'selected' : ''; ?>>Available</option>
                                            <option value="occupied" <?php echo $form_data['status'] == 'occupied' ? 'selected' : ''; ?>>Occupied</option>
                                            <option value="maintenance" <?php echo $form_data['status'] == 'maintenance' ? 'selected' : ''; ?>>Maintenance</option>
                                            <option value="housekeeping" <?php echo $form_data['status'] == 'housekeeping' ? 'selected' : ''; ?>>Housekeeping</option>
                                            <option value="blocked" <?php echo $form_data['status'] == 'blocked' ? 'selected' : ''; ?>>Blocked</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="mb-3">
                                        <label for="housekeeping_status">Housekeeping Status</label>
                                        <select class="form-select" id="housekeeping_status" name="housekeeping_status">
                                            <option value="clean" <?php echo $form_data['housekeeping_status'] == 'clean' ? 'selected' : ''; ?>>Clean</option>
                                            <option value="dirty" <?php echo $form_data['housekeeping_status'] == 'dirty' ? 'selected' : ''; ?>>Dirty</option>
                                            <option value="inspected" <?php echo $form_data['housekeeping_status'] == 'inspected' ? 'selected' : ''; ?>>Inspected</option>
                                            <option value="out_of_service" <?php echo $form_data['housekeeping_status'] == 'out_of_service' ? 'selected' : ''; ?>>Out of Service</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="notes">Notes</label>
                                <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo htmlspecialchars($form_data['notes']); ?></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input type="checkbox" class="form-check-input" id="is_active" name="is_active"
                                           <?php echo $form_data['is_active'] ? 'checked' : ''; ?>
                                           <?php echo ($room['status'] ?? '') == 'occupied' ? 'disabled' : ''; ?>>
                                    <label class="form-check-label" for="is_active">Active</label>
                                </div>
                                <?php if (($room['status'] ?? '') == 'occupied'): ?>
                                    <small class="text-muted">Cannot deactivate an occupied room</small>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save me-1"></i> Update Room
                            </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>

                <!-- Danger Zone -->
                <?php if (($room['status'] ?? '') != 'occupied' && function_exists('has_permission') && has_permission('rooms.delete')): ?>
                <div class="card card-danger mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-exclamation-triangle me-1"></i>
                            Danger Zone
                        </h3>
                    </div>
                    <div class="card-body">
                        <p>Once you delete a room, there is no going back. Please be certain.</p>
                        <button type="button" class="btn btn-danger" onclick="deleteRoom(<?php echo $room_id; ?>, '<?php echo htmlspecialchars(addslashes($room['room_number'] ?? '')); ?>')">
                            <i class="fas fa-trash me-1"></i> Delete Room
                        </button>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Room</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete room <strong id="deleteRoomNumber"></strong>?</p>
                <p class="text-danger"><i class="fas fa-exclamation-triangle me-1"></i> This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" action="delete.php" id="deleteForm">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="room_id" id="deleteRoomId">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete Room</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize Select2
    $('#room_type_id').select2({
        theme: 'bootstrap-5',
        width: '100%',
        placeholder: 'Select Room Type'
    });
    
    // Check room number availability
    let roomTimeout;
    $('#room_number').on('input', function() {
        clearTimeout(roomTimeout);
        const roomNumber = $(this).val();
        const originalNumber = '<?php echo addslashes($room['room_number'] ?? ''); ?>';
        
        if (roomNumber.length < 1 || roomNumber === originalNumber) return;
        
        roomTimeout = setTimeout(function() {
            $.get('/HMSPOS/api/check-room-number.php', { 
                room_number: roomNumber,
                exclude: <?php echo $room_id; ?>
            }, function(response) {
                const $room = $('#room_number');
                if (response.exists) {
                    $room.addClass('is-invalid');
                    if ($room.next('.invalid-feedback').length === 0) {
                        $room.after('<div class="invalid-feedback">Room number already exists</div>');
                    }
                } else {
                    $room.removeClass('is-invalid');
                    $room.next('.invalid-feedback').remove();
                }
            }).fail(function() {
                console.error('Failed to check room number availability');
            });
        }, 500);
    });
    
    // Warn if changing status of occupied room
    $('#status').change(function() {
        if ('<?php echo $room['status'] ?? ''; ?>' === 'occupied' && $(this).val() !== 'occupied') {
            if (!confirm('This room is currently occupied. Changing status may affect the guest record. Continue?')) {
                $(this).val('occupied');
            }
        }
    });
});

function deleteRoom(roomId, roomNumber) {
    $('#deleteRoomId').val(roomId);
    $('#deleteRoomNumber').text(roomNumber);
    
    const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}
</script>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-3 { margin-top: 1rem; }
.select2-container--bootstrap-5 { width: 100% !important; }
.form-check-input:checked { background-color: #ffc107; border-color: #ffc107; }
</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>';
}
?>