<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Change Room Status - 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/status.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_STATUS_CHANGE')) {
    define('AUDIT_STATUS_CHANGE', 'status_change');
}

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

// Set page title
$page_title = 'Change Room Status';

// 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, 
               CONCAT(g.first_name, ' ', g.last_name) as guest_name,
               res.reservation_id
        FROM rooms r
        JOIN room_types rt ON r.room_type_id = rt.room_type_id
        LEFT JOIN reservations res ON r.room_id = res.room_id AND res.booking_status = 'checked_in'
        LEFT JOIN guests g ON res.guest_id = g.guest_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 status update
$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) {
        $new_status = $_POST['status'] ?? '';
        $new_hk_status = $_POST['housekeeping_status'] ?? '';
        $reason = $_POST['reason'] ?? '';
        
        // Validate status
        $allowed_statuses = ['available', 'occupied', 'maintenance', 'housekeeping', 'blocked'];
        $allowed_hk = ['clean', 'dirty', 'inspected', 'out_of_service'];
        
        if (!in_array($new_status, $allowed_statuses)) {
            $error = 'Invalid room status';
        } elseif (!in_array($new_hk_status, $allowed_hk)) {
            $error = 'Invalid housekeeping status';
        } else {
            // Check if trying to mark occupied room as something else
            if (($room['status'] ?? '') == 'occupied' && $new_status != 'occupied' && !empty($room['guest_name'])) {
                if (!isset($_POST['confirm_guest']) || $_POST['confirm_guest'] != '1') {
                    $error = 'Room is currently occupied. Please confirm guest check-out first.';
                }
            }
            
            if (empty($error)) {
                try {
                    if (function_exists('begin_transaction')) {
                        begin_transaction();
                    }
                    
                    $old_values = [
                        'status' => $room['status'] ?? '',
                        'housekeeping_status' => $room['housekeeping_status'] ?? ''
                    ];
                    
                    $update_data = [
                        'status' => $new_status,
                        'housekeeping_status' => $new_hk_status
                    ];
                    
                    if (function_exists('db_update')) {
                        db_update('rooms', $update_data, 'room_id = ?', [$room_id]);
                    } else {
                        // Fallback direct update
                        $pdo = get_db_connection();
                        $pdo->prepare("UPDATE rooms SET status = ?, housekeeping_status = ? WHERE room_id = ?")
                            ->execute([$new_status, $new_hk_status, $room_id]);
                    }
                    
                    // Create housekeeping task if needed
                    if ($new_hk_status == 'dirty' && ($room['housekeeping_status'] ?? '') != 'dirty') {
                        $task_code = 'HK-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                        
                        $task_data = [
                            'task_code' => $task_code,
                            'room_id' => $room_id,
                            'task_type' => 'cleaning',
                            'priority' => $new_status == 'occupied' ? 'medium' : 'low',
                            'status' => 'pending',
                            'notes' => 'Auto-created from status change' . ($reason ? ": $reason" : ''),
                            'created_by' => $user_id,
                            'created_at' => date('Y-m-d H:i:s')
                        ];
                        
                        if (function_exists('db_insert')) {
                            db_insert('hk_tasks', $task_data);
                        }
                    }
                    
                    // Create maintenance task if needed
                    if ($new_status == 'maintenance' && ($room['status'] ?? '') != 'maintenance') {
                        $ticket_code = 'MT-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
                        
                        $ticket_data = [
                            'ticket_code' => $ticket_code,
                            'room_id' => $room_id,
                            'reported_by' => $user_id,
                            'issue_type' => 'Status Change',
                            'description' => $reason ?: 'Room marked for maintenance',
                            'priority' => 'medium',
                            'status' => 'open',
                            'created_at' => date('Y-m-d H:i:s')
                        ];
                        
                        if (function_exists('db_insert')) {
                            db_insert('maintenance_tickets', $ticket_data);
                        }
                    }
                    
                    // Audit log
                    if (function_exists('audit_log')) {
                        audit_log($user_id, 'status_change', 'rooms', $room_id, $old_values, $update_data);
                    }
                    
                    if (function_exists('commit_transaction')) {
                        commit_transaction();
                    }
                    
                    if (function_exists('set_flash_message')) {
                        set_flash_message('success', 'Room status 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();
                    }
                    $error = 'Failed to update status: ' . $e->getMessage();
                    if (function_exists('log_message')) {
                        log_message("Status update failed: " . $e->getMessage(), 'ERROR');
                    } else {
                        error_log("Status 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>Change Room Status</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="#">Change Room Status</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">Change Status: 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">Change Status</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <!-- Error Messages -->
                <?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; ?>

                <!-- Current Status Card -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Current Status
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-sm-6">
                                <strong>Room Status:</strong><br>
                                <span class="badge bg-<?php 
                                    echo ($room['status'] ?? '') == 'available' ? 'success' : 
                                        (($room['status'] ?? '') == 'occupied' ? 'danger' : 
                                        (($room['status'] ?? '') == 'maintenance' ? 'warning' : 
                                        (($room['status'] ?? '') == 'housekeeping' ? 'info' : 'secondary')));
                                ?> badge-lg">
                                    <?php echo ucfirst($room['status'] ?? 'unknown'); ?>
                                </span>
                            </div>
                            <div class="col-sm-6">
                                <strong>Housekeeping Status:</strong><br>
                                <span class="badge bg-<?php 
                                    echo ($room['housekeeping_status'] ?? '') == 'clean' ? 'success' : 
                                        (($room['housekeeping_status'] ?? '') == 'dirty' ? 'warning' : 
                                        (($room['housekeeping_status'] ?? '') == 'inspected' ? 'info' : 'secondary'));
                                ?> badge-lg">
                                    <?php echo ucfirst($room['housekeeping_status'] ?? 'unknown'); ?>
                                </span>
                            </div>
                        </div>
                        
                        <?php if (!empty($room['guest_name'])): ?>
                            <hr>
                            <div class="alert alert-warning mb-0">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <strong>Occupied by:</strong> <?php echo htmlspecialchars($room['guest_name']); ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Status Change Form -->
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sync-alt me-1"></i>
                            Update Status
                        </h3>
                    </div>
                    
                    <form method="POST" id="statusForm">
                        <?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="mb-3">
                                <label for="status" class="form-label">Room Status</label>
                                <select class="form-select" id="status" name="status">
                                    <option value="available" <?php echo ($room['status'] ?? '') == 'available' ? 'selected' : ''; ?>>Available</option>
                                    <option value="occupied" <?php echo ($room['status'] ?? '') == 'occupied' ? 'selected' : ''; ?> 
                                            <?php echo empty($room['guest_name']) ? 'disabled' : ''; ?>>Occupied</option>
                                    <option value="maintenance" <?php echo ($room['status'] ?? '') == 'maintenance' ? 'selected' : ''; ?>>Maintenance</option>
                                    <option value="housekeeping" <?php echo ($room['status'] ?? '') == 'housekeeping' ? 'selected' : ''; ?>>Housekeeping</option>
                                    <option value="blocked" <?php echo ($room['status'] ?? '') == 'blocked' ? 'selected' : ''; ?>>Blocked</option>
                                </select>
                                <?php if (empty($room['guest_name'])): ?>
                                    <small class="text-muted">Occupied option disabled - no guest currently</small>
                                <?php endif; ?>
                            </div>
                            
                            <div class="mb-3">
                                <label for="housekeeping_status" class="form-label">Housekeeping Status</label>
                                <select class="form-select" id="housekeeping_status" name="housekeeping_status">
                                    <option value="clean" <?php echo ($room['housekeeping_status'] ?? '') == 'clean' ? 'selected' : ''; ?>>Clean</option>
                                    <option value="dirty" <?php echo ($room['housekeeping_status'] ?? '') == 'dirty' ? 'selected' : ''; ?>>Dirty</option>
                                    <option value="inspected" <?php echo ($room['housekeeping_status'] ?? '') == 'inspected' ? 'selected' : ''; ?>>Inspected</option>
                                    <option value="out_of_service" <?php echo ($room['housekeeping_status'] ?? '') == 'out_of_service' ? 'selected' : ''; ?>>Out of Service</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="reason" class="form-label">Reason / Notes</label>
                                <textarea class="form-control" id="reason" name="reason" rows="3" 
                                          placeholder="Optional: provide reason for status change"></textarea>
                            </div>
                            
                            <?php if (($room['status'] ?? '') == 'occupied' && !empty($room['guest_name'])): ?>
                                <div class="mb-3">
                                    <div class="form-check">
                                        <input type="checkbox" class="form-check-input" id="confirm_guest" name="confirm_guest" value="1">
                                        <label class="form-check-label" for="confirm_guest">
                                            I confirm that the guest has checked out or this change is authorized
                                        </label>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-save me-1"></i> Update Status
                            </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>

                <!-- Status Guide -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-question-circle me-1"></i>
                            Status Guide
                        </h3>
                    </div>
                    <div class="card-body">
                        <dl class="row mb-0">
                            <dt class="col-sm-4"><span class="badge bg-success">Available</span></dt>
                            <dd class="col-sm-8">Room is ready for check-in</dd>
                            
                            <dt class="col-sm-4"><span class="badge bg-danger">Occupied</span></dt>
                            <dd class="col-sm-8">Guest currently in room</dd>
                            
                            <dt class="col-sm-4"><span class="badge bg-warning">Maintenance</span></dt>
                            <dd class="col-sm-8">Room needs repairs, not available</dd>
                            
                            <dt class="col-sm-4"><span class="badge bg-info">Housekeeping</span></dt>
                            <dd class="col-sm-8">Being cleaned, will be available soon</dd>
                            
                            <dt class="col-sm-4"><span class="badge bg-secondary">Blocked</span></dt>
                            <dd class="col-sm-8">Temporarily unavailable (e.g., VIP hold)</dd>
                        </dl>
                        
                        <hr>
                        
                        <dl class="row mb-0">
                            <dt class="col-sm-4"><span class="badge bg-success">Clean</span></dt>
                            <dd class="col-sm-8">Room has been cleaned and inspected</dd>
                            
                            <dt class="col-sm-4"><span class="badge bg-warning">Dirty</span></dt>
                            <dd class="col-sm-8">Needs cleaning</dd>
                            
                            <dt class="col-sm-4"><span class="badge bg-info">Inspected</span></dt>
                            <dd class="col-sm-8">Cleaned and verified by supervisor</dd>
                            
                            <dt class="col-sm-4"><span class="badge bg-secondary">Out of Service</span></dt>
                            <dd class="col-sm-8">Long-term unavailable</dd>
                        </dl>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(document).ready(function() {
    // Warn if changing status from occupied
    $('#status').change(function() {
        if ('<?php echo $room['status'] ?? ''; ?>' === 'occupied' && $(this).val() !== 'occupied') {
            if (!confirm('This room is currently occupied. Are you sure you want to change the status?')) {
                $(this).val('occupied');
            }
        }
    });
    
    // Auto-create task based on status
    $('#status, #housekeeping_status').change(function() {
        const status = $('#status').val();
        const hkStatus = $('#housekeeping_status').val();
        
        if (status === 'maintenance') {
            if (!$('#reason').val()) {
                $('#reason').val('Room marked for maintenance');
            }
        }
    });
    
    // Form validation
    $('#statusForm').on('submit', function(e) {
        const status = $('#status').val();
        
        if ('<?php echo $room['status'] ?? ''; ?>' === 'occupied' && status !== 'occupied') {
            if (!$('#confirm_guest').is(':checked')) {
                e.preventDefault();
                alert('Please confirm that the guest has checked out or this change is authorized.');
            }
        }
    });
});
</script>

<style>
.badge-lg {
    font-size: 1.1rem;
    padding: 0.5rem 1rem;
}
dl dt {
    margin-bottom: 0.5rem;
}
dl dd {
    margin-bottom: 0.5rem;
}
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 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>';
}
?>