<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Complete Check-in Process - FIXED PATH
 * 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
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/reservations/checkin/
$base_path = dirname(__DIR__, 3);

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

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

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php',
    '/config/mailer.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// 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 format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Define csrf_token function if it doesn't exist
if (!function_exists('csrf_token')) {
    function csrf_token() {
        return $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
    }
}

// Define verify_csrf_token function if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Define begin_transaction function if it doesn't exist
if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db) {
                $db->beginTransaction();
            }
        }
    }
}

// Define commit_transaction function if it doesn't exist
if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->commit();
            }
        }
    }
}

// Define rollback_transaction function if it doesn't exist
if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_connect')) {
            $db = db_connect();
            if ($db && $db->inTransaction()) {
                $db->rollBack();
            }
        }
    }
}

// Define audit_log function if it doesn't exist
if (!function_exists('audit_log')) {
    function audit_log($user_id, $action, $table, $record_id, $old_values, $new_values) {
        // Simplified audit log - just log to error log
        error_log("AUDIT: User $user_id - $action on $table:$record_id");
    }
}

// Define log_message function if it doesn't exist
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        error_log("[$level] $message");
    }
}

// Define upload_file function if it doesn't exist
if (!function_exists('upload_file')) {
    function upload_file($file, $target_dir, $allowed_types) {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['success' => false, 'errors' => ['File upload error']];
        }
        
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, $allowed_types)) {
            return ['success' => false, 'errors' => ['File type not allowed']];
        }
        
        $new_filename = uniqid() . '_' . time() . '.' . $extension;
        $target_path = rtrim($target_dir, '/') . '/' . $new_filename;
        
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0755, true);
        }
        
        if (move_uploaded_file($file['tmp_name'], $target_path)) {
            return ['success' => true, 'filename' => $new_filename];
        }
        
        return ['success' => false, 'errors' => ['Failed to move uploaded file']];
    }
}

// Define create_notification function if it doesn't exist
if (!function_exists('create_notification')) {
    function create_notification($user_id, $type, $title, $message, $link = null) {
        if (function_exists('db_insert')) {
            try {
                db_insert('notifications', [
                    'user_id' => $user_id,
                    'type' => $type,
                    'title' => $title,
                    'message' => $message,
                    'link' => $link,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            } catch (Exception $e) {
                error_log("Failed to create notification: " . $e->getMessage());
            }
        }
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('UPLOAD_PATH_IDS')) {
    define('UPLOAD_PATH_IDS', $base_path . '/uploads/ids/');
}
if (!defined('DATETIME_FORMAT')) {
    define('DATETIME_FORMAT', 'Y-m-d H:i:s');
}
if (!defined('NOTIFICATION_SUCCESS')) {
    define('NOTIFICATION_SUCCESS', 'success');
}
if (!defined('AUDIT_CHECKIN')) {
    define('AUDIT_CHECKIN', 'checkin');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('reservations.checkin');
}

// Set page title
$page_title = 'Check-in Complete';

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

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

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    process_checkin();
    exit;
}

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

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

// Get reservation data
$reservation = [];
if (function_exists('db_fetch_one')) {
    try {
        $reservation = db_fetch_one("
            SELECT 
                r.*,
                g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                rt.type_name, rt.type_code,
                rm.room_number, rm.floor,
                DATEDIFF(r.check_out_date, r.check_in_date) as nights
            FROM reservations r
            JOIN guests g ON r.guest_id = g.guest_id
            JOIN room_types rt ON r.room_type_id = rt.room_type_id
            LEFT JOIN rooms rm ON r.room_id = rm.room_id
            WHERE r.reservation_id = ?
        ", [$reservation_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching reservation: " . $e->getMessage());
    }
}

if (empty($reservation)) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Reservation not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// 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>Check-in Complete</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; }
            .badge-lg { font-size: 1.1rem; padding: 0.5rem 1rem; }
            .me-1 { margin-right: 0.25rem; }
            .me-2 { margin-right: 0.5rem; }
            .ms-2 { margin-left: 0.5rem; }
            .mb-2 { margin-bottom: 0.5rem; }
            .mb-4 { margin-bottom: 1.5rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-4 { margin-top: 1.5rem; }
            .mt-5 { margin-top: 3rem; }
        </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="#">Check-in Complete</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">Check-in Complete</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/reservations/dashboard.php">Reservations</a></li>
                    <li class="breadcrumb-item"><a href="index.php">Check-in</a></li>
                    <li class="breadcrumb-item active">Complete</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">
                <!-- Success Message -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-check-circle me-1"></i>
                            Check-in Successful
                        </h3>
                    </div>
                    
                    <div class="card-body text-center">
                        <i class="fas fa-check-circle fa-5x text-success mb-4"></i>
                        
                        <h3>Welcome to Ruhondo Beach Resort!</h3>
                        
                        <p class="lead">
                            <?php echo escape_html(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '')); ?> has been checked in successfully.
                        </p>
                        
                        <div class="card card-outline card-success mt-4">
                            <div class="card-header">
                                <h4 class="card-title">Check-in Summary</h4>
                            </div>
                            <div class="card-body">
                                <table class="table table-bordered">
                                    <tr>
                                        <th style="width: 200px;">Booking Code:</th>
                                        <td><strong><?php echo htmlspecialchars($reservation['booking_code'] ?? 'N/A'); ?></strong></td>
                                    </tr>
                                    <tr>
                                        <th>Guest Name:</th>
                                        <td><?php echo escape_html(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '')); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Room:</th>
                                        <td>
                                            <span class="badge bg-info badge-lg">
                                                Room <?php echo htmlspecialchars($reservation['room_number'] ?? 'N/A'); ?> (Floor <?php echo htmlspecialchars($reservation['floor'] ?? 'N/A'); ?>)
                                            </span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Room Type:</th>
                                        <td><?php echo htmlspecialchars($reservation['type_name'] ?? 'N/A'); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Check-in Date:</th>
                                        <td><?php echo isset($reservation['check_in_date']) ? date('M d, Y', strtotime($reservation['check_in_date'])) : 'N/A'; ?></td>
                                    </tr>
                                    <tr>
                                        <th>Check-out Date:</th>
                                        <td><?php echo isset($reservation['check_out_date']) ? date('M d, Y', strtotime($reservation['check_out_date'])) : 'N/A'; ?></td>
                                    </tr>
                                    <tr>
                                        <th>Nights:</th>
                                        <td><?php echo $reservation['nights'] ?? 0; ?></td>
                                    </tr>
                                    <tr>
                                        <th>Checked in by:</th>
                                        <td><?php echo escape_html(($current_user['first_name'] ?? '') . ' ' . ($current_user['last_name'] ?? '')); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Time:</th>
                                        <td><?php echo date(DATETIME_FORMAT); ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="mt-4">
                            <a href="../folio/view.php?reservation_id=<?php echo $reservation_id; ?>" class="btn btn-primary btn-lg me-2">
                                <i class="fas fa-file-invoice me-1"></i> View Folio
                            </a>
                            
                            <a href="../documents/registration-card.php?id=<?php echo $reservation_id; ?>" target="_blank" class="btn btn-info btn-lg me-2">
                                <i class="fas fa-id-card me-1"></i> Print Registration Card
                            </a>
                            
                            <a href="index.php" class="btn btn-success btn-lg">
                                <i class="fas fa-sign-in-alt me-1"></i> Next Check-in
                            </a>
                        </div>

                        <!-- Quick Actions -->
                        <div class="mt-5">
                            <h5>Quick Actions</h5>
                            <div class="btn-group">
                                <button type="button" class="btn btn-outline-primary" onclick="sendWelcomeEmail()">
                                    <i class="fas fa-envelope"></i> Send Welcome Email
                                </button>
                                <button type="button" class="btn btn-outline-success" onclick="createHousekeepingTask()">
                                    <i class="fas fa-broom"></i> Schedule Cleaning
                                </button>
                                <button type="button" class="btn btn-outline-warning" onclick="addToFolio()">
                                    <i class="fas fa-plus-circle"></i> Add Charge
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
function sendWelcomeEmail() {
    if (confirm('Send welcome email to guest?')) {
        $.post('/HMSPOS/api/send-welcome-email.php', {
            reservation_id: <?php echo $reservation_id; ?>,
            csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ($_SESSION['csrf_token'] ?? ''); ?>'
        }, function(response) {
            if (response.status === 'success') {
                alert('Welcome email sent successfully');
            } else {
                alert('Failed to send email: ' + (response.message || 'Unknown error'));
            }
        }).fail(function(xhr) {
            alert('Failed to send email: ' + (xhr.responseJSON?.message || 'Network error'));
        });
    }
}

function createHousekeepingTask() {
    if (confirm('Create a housekeeping task for this room?')) {
        window.location.href = '/HMSPOS/housekeeping/tasks/create.php?room_id=<?php echo $reservation['room_id'] ?? 0; ?>';
    }
}

function addToFolio() {
    window.location.href = '/HMSPOS/reservations/folio/add-charge.php?reservation_id=<?php echo $reservation_id; ?>';
}

// Auto-print registration card if requested
<?php if (isset($_GET['print']) && $_GET['print'] == 1): ?>
$(document).ready(function() {
    window.open('../documents/registration-card.php?id=<?php echo $reservation_id; ?>', '_blank');
});
<?php endif; ?>
</script>

<style>
.badge-lg {
    font-size: 1.1rem;
    padding: 0.5rem 1rem;
}
</style>

<?php
/**
 * Process check-in form submission
 */
function process_checkin() {
    global $current_user, $user_id;
    
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        if (function_exists('set_flash_message')) {
            set_flash_message('danger', 'Invalid security token');
        }
        if (function_exists('redirect')) {
            redirect('index.php');
        } else {
            header('Location: index.php');
            exit;
        }
    }
    
    $reservation_id = isset($_POST['reservation_id']) ? (int)$_POST['reservation_id'] : 0;
    $room_id = isset($_POST['room_id']) ? (int)$_POST['room_id'] : 0;
    $id_type = isset($_POST['id_type']) ? sanitize_input($_POST['id_type']) : '';
    $id_number = isset($_POST['id_number']) ? sanitize_input($_POST['id_number']) : '';
    $id_expiry = isset($_POST['id_expiry']) ? sanitize_input($_POST['id_expiry']) : '';
    $address = isset($_POST['address']) ? sanitize_input($_POST['address']) : '';
    $city = isset($_POST['city']) ? sanitize_input($_POST['city']) : '';
    $country = isset($_POST['country']) ? sanitize_input($_POST['country']) : '';
    $print_registration = isset($_POST['print_registration']);
    
    if (!$reservation_id) {
        if (function_exists('set_flash_message')) {
            set_flash_message('danger', 'Invalid reservation ID');
        }
        if (function_exists('redirect')) {
            redirect('index.php');
        } else {
            header('Location: index.php');
            exit;
        }
    }
    
    // Get reservation
    $reservation = null;
    if (function_exists('db_fetch_one')) {
        $reservation = db_fetch_one("SELECT * FROM reservations WHERE reservation_id = ?", [$reservation_id]);
    }
    
    if (!$reservation) {
        if (function_exists('set_flash_message')) {
            set_flash_message('danger', 'Reservation not found');
        }
        if (function_exists('redirect')) {
            redirect('index.php');
        } else {
            header('Location: index.php');
            exit;
        }
    }
    
    // Determine room to use
    if ($room_id) {
        // Use selected room
    } elseif (!empty($reservation['room_id'])) {
        $room_id = $reservation['room_id'];
    } else {
        if (function_exists('set_flash_message')) {
            set_flash_message('danger', 'No room assigned');
        }
        if (function_exists('redirect')) {
            redirect('start.php?id=' . $reservation_id);
        } else {
            header('Location: start.php?id=' . $reservation_id);
            exit;
        }
    }
    
    try {
        if (function_exists('begin_transaction')) {
            begin_transaction();
        }
        
        // Update guest information
        $guest_update = [];
        if ($id_type) $guest_update['id_type'] = $id_type;
        if ($id_number) $guest_update['id_number'] = $id_number;
        if ($id_expiry) $guest_update['id_expiry'] = $id_expiry;
        if ($address) $guest_update['address'] = $address;
        if ($city) $guest_update['city'] = $city;
        if ($country) $guest_update['country'] = $country;
        
        if (!empty($guest_update) && function_exists('db_update')) {
            db_update('guests', $guest_update, 'guest_id = ?', [$reservation['guest_id']]);
        }
        
        // Handle ID document upload
        if (isset($_FILES['id_document']) && $_FILES['id_document']['error'] === UPLOAD_ERR_OK) {
            if (function_exists('upload_file')) {
                $upload_result = upload_file(
                    $_FILES['id_document'],
                    defined('UPLOAD_PATH_IDS') ? UPLOAD_PATH_IDS : (dirname(__DIR__, 3) . '/uploads/ids/'),
                    ['jpg', 'jpeg', 'png', 'pdf']
                );
                
                if ($upload_result['success'] && function_exists('db_insert')) {
                    db_insert('guest_documents', [
                        'guest_id' => $reservation['guest_id'],
                        'document_type' => 'id',
                        'document_number' => $id_number,
                        'document_path' => $upload_result['filename'],
                        'uploaded_by' => $user_id,
                        'uploaded_at' => date('Y-m-d H:i:s')
                    ]);
                }
            }
        }
        
        // Update reservation status
        if (function_exists('db_update')) {
            db_update('reservations', [
                'booking_status' => 'checked_in',
                'room_id' => $room_id,
                'updated_at' => date('Y-m-d H:i:s')
            ], 'reservation_id = ?', [$reservation_id]);
        }
        
        // Update room status
        if (function_exists('db_update')) {
            db_update('rooms', [
                'status' => 'occupied',
                'housekeeping_status' => 'clean'
            ], 'room_id = ?', [$room_id]);
        }
        
        // Create guest activity record
        if (function_exists('db_insert')) {
            db_insert('guest_activity', [
                'guest_id' => $reservation['guest_id'],
                'activity_type' => 'checkin',
                'description' => "Guest checked in to room " . get_room_number($room_id),
                'reference_id' => $reservation_id,
                'reference_type' => 'reservation',
                'created_by' => $user_id,
                'created_at' => date('Y-m-d H:i:s')
            ]);
        }
        
        // Create notification
        if (function_exists('create_notification')) {
            create_notification(
                $reservation['guest_id'],
                defined('NOTIFICATION_SUCCESS') ? NOTIFICATION_SUCCESS : 'success',
                'Welcome to Ruhondo Beach Resort',
                'You have been checked in successfully. Enjoy your stay!',
                '../folio/view.php?reservation_id=' . $reservation_id
            );
        }
        
        // Audit log
        if (function_exists('audit_log')) {
            audit_log($user_id, defined('AUDIT_CHECKIN') ? AUDIT_CHECKIN : 'checkin', 'reservations', $reservation_id, 
                     ['booking_status' => $reservation['booking_status']], 
                     ['booking_status' => 'checked_in', 'room_id' => $room_id]);
        }
        
        if (function_exists('commit_transaction')) {
            commit_transaction();
        }
        
        // Redirect to completion page
        $redirect_url = 'complete.php?id=' . $reservation_id;
        if ($print_registration) {
            $redirect_url .= '&print=1';
        }
        
        if (function_exists('set_flash_message')) {
            set_flash_message('success', 'Check-in completed successfully');
        }
        
        if (function_exists('redirect')) {
            redirect($redirect_url);
        } else {
            header('Location: ' . $redirect_url);
            exit;
        }
        
    } catch (Exception $e) {
        if (function_exists('rollback_transaction')) {
            rollback_transaction();
        }
        if (function_exists('set_flash_message')) {
            set_flash_message('danger', 'Failed to complete check-in: ' . $e->getMessage());
        }
        if (function_exists('log_message')) {
            log_message("Check-in failed: " . $e->getMessage(), 'ERROR');
        }
        if (function_exists('redirect')) {
            redirect('start.php?id=' . $reservation_id);
        } else {
            header('Location: start.php?id=' . $reservation_id);
            exit;
        }
    }
}

/**
 * Get room number by ID
 */
function get_room_number($room_id) {
    if (function_exists('db_fetch_value')) {
        return db_fetch_value("SELECT room_number FROM rooms WHERE room_id = ?", [$room_id]) ?: 'Unknown';
    }
    return 'Unknown';
}

// 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>';
}
?>