<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * View Reservation Details - 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/
$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/ -> /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'
];

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 has_permission function if it doesn't exist
if (!function_exists('has_permission')) {
    function has_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 format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0);
    }
}

// Define time_ago function if it doesn't exist
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        if (empty($datetime)) return '';
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) return $diff . ' seconds ago';
        if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
        if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
        return date('M d, Y', $time);
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        $_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, '/');
    }
}

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

// Set page title
$page_title = 'Reservation Details';

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

// 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 with all details
$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,
                g.address, g.city, g.country, g.id_type, g.id_number,
                g.nationality,
                rt.type_name, rt.type_code, rt.base_price,
                rt.max_adults, rt.max_children, rt.max_occupancy,
                rm.room_number, rm.floor,
                rp.plan_name, rp.plan_code,
                u.first_name as created_by_first, u.last_name as created_by_last,
                DATEDIFF(r.check_out_date, r.check_in_date) as nights,
                (r.total_amount - r.paid_amount) as balance
            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
            LEFT JOIN rate_plans rp ON r.rate_plan_id = rp.rate_plan_id
            LEFT JOIN users u ON r.created_by = u.user_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;
    }
}

// Get folio charges
$folio_charges = [];
if (function_exists('db_fetch_all')) {
    try {
        $folio_charges = db_fetch_all("
            SELECT fc.*, u.first_name, u.last_name
            FROM folio_charges fc
            LEFT JOIN users u ON fc.posted_by = u.user_id
            WHERE fc.reservation_id = ?
            ORDER BY fc.posted_at DESC
        ", [$reservation_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching folio charges: " . $e->getMessage());
    }
}

// Calculate folio summary
$folio_summary = [
    'room_charges' => 0,
    'fnb_charges' => 0,
    'service_charges' => 0,
    'total_charges' => 0,
    'payments' => 0,
    'balance' => 0
];

foreach ($folio_charges as $charge) {
    if (($charge['charge_type'] ?? '') == 'payment') {
        $folio_summary['payments'] += $charge['amount'] ?? 0;
    } else {
        $folio_summary['total_charges'] += $charge['amount'] ?? 0;
        
        switch ($charge['charge_type'] ?? '') {
            case 'room':
                $folio_summary['room_charges'] += $charge['amount'] ?? 0;
                break;
            case 'fnb':
                $folio_summary['fnb_charges'] += $charge['amount'] ?? 0;
                break;
            case 'service':
                $folio_summary['service_charges'] += $charge['amount'] ?? 0;
                break;
        }
    }
}

$folio_summary['balance'] = $folio_summary['total_charges'] - $folio_summary['payments'];

// Get recent guest history
$guest_history = [];
if (function_exists('db_fetch_all')) {
    try {
        $guest_history = db_fetch_all("
            SELECT r.*, rt.type_name
            FROM reservations r
            JOIN room_types rt ON r.room_type_id = rt.room_type_id
            WHERE r.guest_id = ? AND r.reservation_id != ?
            ORDER BY r.check_in_date DESC
            LIMIT 5
        ", [$reservation['guest_id'] ?? 0, $reservation_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching guest history: " . $e->getMessage());
    }
}

// Get booking sources
$sources = [];
if (defined('BOOKING_SOURCES')) {
    $sources = @unserialize(BOOKING_SOURCES) ?: [];
} else {
    $sources = [
        'direct' => 'Direct',
        'website' => 'Website',
        'phone' => 'Phone',
        'email' => 'Email',
        'walk_in' => 'Walk-in',
        'agent' => 'Travel Agent',
        'ota' => 'OTA'
    ];
}

// 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>Reservation Details</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: 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-3 { margin-bottom: 1rem; }
            .mt-2 { margin-top: 0.5rem; }
            .mt-3 { margin-top: 1rem; }
            .mt-4 { margin-top: 1.5rem; }
            .text-end { text-align: right; }
            .table-sm td, .table-sm th { padding: 0.5rem; }
            .btn-group .btn { margin-right: 5px; }
        </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="#">Reservation Details</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">Reservation: <?php echo htmlspecialchars($reservation['booking_code'] ?? 'N/A'); ?></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">Reservations</a></li>
                    <li class="breadcrumb-item active">View</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Action Buttons -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="btn-group">
                    <a href="index.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Back to List
                    </a>
                    
                    <?php if (function_exists('has_permission') && has_permission('reservations.edit') && !in_array($reservation['booking_status'] ?? '', ['checked_out', 'cancelled'])): ?>
                        <a href="edit.php?id=<?php echo $reservation_id; ?>" class="btn btn-warning">
                            <i class="fas fa-edit me-1"></i> Edit
                        </a>
                    <?php endif; ?>
                    
                    <?php if (($reservation['booking_status'] ?? '') == 'confirmed' && ($reservation['check_in_date'] ?? '') <= date('Y-m-d')): ?>
                        <a href="../checkin/start.php?id=<?php echo $reservation_id; ?>" class="btn btn-success">
                            <i class="fas fa-sign-in-alt me-1"></i> Check-in
                        </a>
                    <?php endif; ?>
                    
                    <?php if (($reservation['booking_status'] ?? '') == 'checked_in'): ?>
                        <a href="../checkout/start.php?id=<?php echo $reservation_id; ?>" class="btn btn-warning">
                            <i class="fas fa-sign-out-alt me-1"></i> Check-out
                        </a>
                    <?php endif; ?>
                    
                    <?php if (function_exists('has_permission') && has_permission('reservations.cancel') && !in_array($reservation['booking_status'] ?? '', ['checked_out', 'cancelled', 'no_show'])): ?>
                        <a href="cancel.php?id=<?php echo $reservation_id; ?>" class="btn btn-danger">
                            <i class="fas fa-times-circle me-1"></i> Cancel
                        </a>
                    <?php endif; ?>
                    
                    <a href="../documents/registration-card.php?id=<?php echo $reservation_id; ?>" class="btn btn-info" target="_blank">
                        <i class="fas fa-id-card me-1"></i> Registration Card
                    </a>
                    
                    <a href="../folio/view.php?reservation_id=<?php echo $reservation_id; ?>" class="btn btn-primary">
                        <i class="fas fa-file-invoice me-1"></i> View Folio
                    </a>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Reservation Info -->
            <div class="col-md-4">
                <div class="card card-primary card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Reservation Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 120px;">Booking Code:</th>
                                <td><strong><?php echo htmlspecialchars($reservation['booking_code'] ?? 'N/A'); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Status:</th>
                                <td>
                                    <span class="badge bg-<?php 
                                        $status = $reservation['booking_status'] ?? 'unknown';
                                        echo $status == 'confirmed' ? 'success' : 
                                            ($status == 'checked_in' ? 'info' : 
                                            ($status == 'pending' ? 'warning' : 
                                            ($status == 'cancelled' ? 'danger' : 'secondary')));
                                    ?> badge-lg">
                                        <?php echo ucfirst($status); ?>
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <th>Payment Status:</th>
                                <td>
                                    <span class="badge bg-<?php 
                                        $payment = $reservation['payment_status'] ?? 'unpaid';
                                        echo $payment == 'paid' ? 'success' : 
                                            ($payment == 'partial' ? 'warning' : 'danger');
                                    ?>">
                                        <?php echo ucfirst($payment); ?>
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <th>Check-in:</th>
                                <td>
                                    <strong><?php echo isset($reservation['check_in_date']) ? date('M d, Y', strtotime($reservation['check_in_date'])) : 'N/A'; ?></strong>
                                    <?php if (($reservation['check_in_date'] ?? '') == date('Y-m-d')): ?>
                                        <span class="badge bg-success">Today</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Check-out:</th>
                                <td>
                                    <strong><?php echo isset($reservation['check_out_date']) ? date('M d, Y', strtotime($reservation['check_out_date'])) : 'N/A'; ?></strong>
                                    <?php if (($reservation['check_out_date'] ?? '') == date('Y-m-d')): ?>
                                        <span class="badge bg-warning">Today</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Nights:</th>
                                <td><?php echo $reservation['nights'] ?? 0; ?></td>
                            </tr>
                            <tr>
                                <th>Guests:</th>
                                <td>
                                    <i class="fas fa-user"></i> <?php echo $reservation['adults'] ?? 0; ?> Adults
                                    <?php if (!empty($reservation['children']) && $reservation['children'] > 0): ?>
                                        <br><i class="fas fa-child"></i> <?php echo $reservation['children']; ?> Children
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Booking Source:</th>
                                <td>
                                    <span class="badge bg-secondary">
                                        <?php 
                                        $source = $reservation['booking_source'] ?? 'unknown';
                                        echo $sources[$source] ?? ucfirst($source);
                                        ?>
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <th>Created By:</th>
                                <td>
                                    <?php echo htmlspecialchars(($reservation['created_by_first'] ?? '') . ' ' . ($reservation['created_by_last'] ?? '')); ?>
                                    <br>
                                    <small class="text-muted"><?php echo isset($reservation['created_at']) ? time_ago($reservation['created_at']) : 'N/A'; ?></small>
                                </td>
                            </tr>
                        </table>
                        
                        <?php if (!empty($reservation['special_requests'])): ?>
                            <hr>
                            <h6>Special Requests:</h6>
                            <p class="text-muted"><?php echo nl2br(htmlspecialchars($reservation['special_requests'])); ?></p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Room Information -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-bed me-1"></i>
                            Room Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Room Type:</th>
                                <td>
                                    <a href="/HMSPOS/rooms/room-types/view.php?id=<?php echo $reservation['room_type_id'] ?? 0; ?>">
                                        <?php echo htmlspecialchars($reservation['type_name'] ?? 'N/A'); ?> (<?php echo htmlspecialchars($reservation['type_code'] ?? ''); ?>)
                                    </a>
                                </td>
                            </tr>
                            <tr>
                                <th>Rate Plan:</th>
                                <td>
                                    <?php if (!empty($reservation['rate_plan_id'])): ?>
                                        <?php echo htmlspecialchars($reservation['plan_name'] ?? ''); ?> (<?php echo htmlspecialchars($reservation['plan_code'] ?? ''); ?>)
                                    <?php else: ?>
                                        <span class="text-muted">Standard Rate</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Assigned Room:</th>
                                <td>
                                    <?php if (!empty($reservation['room_id'])): ?>
                                        <a href="/HMSPOS/rooms/rooms/view.php?id=<?php echo $reservation['room_id']; ?>">
                                            <span class="badge bg-info badge-lg">Room <?php echo htmlspecialchars($reservation['room_number'] ?? ''); ?></span>
                                        </a>
                                        <?php if (!empty($reservation['floor'])): ?>
                                            <br><small>Floor <?php echo htmlspecialchars($reservation['floor']); ?></small>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="badge bg-warning">Not assigned</span>
                                        <?php if (function_exists('has_permission') && has_permission('reservations.edit') && ($reservation['booking_status'] ?? '') == 'confirmed'): ?>
                                            <a href="assign-room.php?id=<?php echo $reservation_id; ?>" class="btn btn-sm btn-primary ms-2">
                                                Assign Now
                                            </a>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </table>
                        
                        <?php if (!empty($reservation['room_id']) && function_exists('has_permission') && has_permission('rooms.view')): ?>
                            <a href="/HMSPOS/rooms/rooms/view.php?id=<?php echo $reservation['room_id']; ?>" class="btn btn-sm btn-info">
                                <i class="fas fa-door-open"></i> View Room
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Guest Information -->
            <div class="col-md-4">
                <div class="card card-success card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user me-1"></i>
                            Guest Information
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/guests/view.php?id=<?php echo $reservation['guest_id'] ?? 0; ?>" class="btn btn-sm btn-success">
                                <i class="fas fa-external-link-alt"></i> Full Profile
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 100px;">Name:</th>
                                <td>
                                    <strong><?php echo htmlspecialchars(($reservation['first_name'] ?? '') . ' ' . ($reservation['last_name'] ?? '')); ?></strong>
                                </td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td>
                                    <?php if (!empty($reservation['email'])): ?>
                                        <a href="mailto:<?php echo htmlspecialchars($reservation['email']); ?>"><?php echo htmlspecialchars($reservation['email']); ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td>
                                    <?php if (!empty($reservation['phone'])): ?>
                                        <a href="tel:<?php echo htmlspecialchars($reservation['phone']); ?>"><?php echo htmlspecialchars($reservation['phone']); ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Address:</th>
                                <td>
                                    <?php 
                                    $address_parts = array_filter([
                                        $reservation['address'] ?? '',
                                        $reservation['city'] ?? '',
                                        $reservation['country'] ?? ''
                                    ]);
                                    echo $address_parts ? implode(', ', array_map('htmlspecialchars', $address_parts)) : '<span class="text-muted">Not provided</span>';
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <th>ID Type:</th>
                                <td>
                                    <?php if (!empty($reservation['id_type'])): ?>
                                        <?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($reservation['id_type']))); ?>: 
                                        <?php echo htmlspecialchars($reservation['id_number'] ?? ''); ?>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Nationality:</th>
                                <td><?php echo htmlspecialchars($reservation['nationality'] ?? 'Not provided'); ?></td>
                            </tr>
                        </table>
                        
                        <hr>
                        
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-info" onclick="sendEmail()">
                                <i class="fas fa-envelope"></i> Send Email
                            </button>
                            <button type="button" class="btn btn-sm btn-primary" onclick="sendSMS()">
                                <i class="fas fa-sms"></i> Send SMS
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Guest History -->
                <?php if (!empty($guest_history)): ?>
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history me-1"></i>
                            Guest History
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <div class="list-group list-group-flush">
                            <?php foreach ($guest_history as $history): ?>
                            <div class="list-group-item">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <a href="view.php?id=<?php echo $history['reservation_id'] ?? 0; ?>">
                                            <strong><?php echo htmlspecialchars($history['booking_code'] ?? ''); ?></strong>
                                        </a>
                                        <br>
                                        <small><?php echo isset($history['check_in_date']) ? date('M d, Y', strtotime($history['check_in_date'])) : 'N/A'; ?> - <?php echo isset($history['check_out_date']) ? date('M d, Y', strtotime($history['check_out_date'])) : 'N/A'; ?></small>
                                    </div>
                                    <span class="badge bg-<?php 
                                        $hist_status = $history['booking_status'] ?? '';
                                        echo $hist_status == 'checked_out' ? 'success' : 
                                            ($hist_status == 'cancelled' ? 'danger' : 'info');
                                    ?>">
                                        <?php echo ucfirst($hist_status); ?>
                                    </span>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Financial Summary -->
            <div class="col-md-4">
                <div class="card card-warning card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-dollar-sign me-1"></i>
                            Financial Summary
                        </h3>
                        <div class="card-tools">
                            <a href="../folio/view.php?reservation_id=<?php echo $reservation_id; ?>" class="btn btn-sm btn-warning">
                                <i class="fas fa-file-invoice"></i> Full Folio
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Room Charges:</th>
                                <td class="text-end"><?php echo format_currency($folio_summary['room_charges']); ?></td>
                            </tr>
                            <tr>
                                <th>F&B Charges:</th>
                                <td class="text-end"><?php echo format_currency($folio_summary['fnb_charges']); ?></td>
                            </tr>
                            <tr>
                                <th>Service Charges:</th>
                                <td class="text-end"><?php echo format_currency($folio_summary['service_charges']); ?></td>
                            </tr>
                            <tr>
                                <th>Total Charges:</th>
                                <td class="text-end"><strong><?php echo format_currency($folio_summary['total_charges']); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Payments:</th>
                                <td class="text-end text-success">- <?php echo format_currency($folio_summary['payments']); ?></td>
                            </tr>
                            <tr class="table-<?php echo $folio_summary['balance'] > 0 ? 'danger' : 'success'; ?>">
                                <th>Current Balance:</th>
                                <td class="text-end">
                                    <strong><?php echo format_currency($folio_summary['balance']); ?></strong>
                                </td>
                            </tr>
                        </table>
                        
                        <?php if ($folio_summary['balance'] > 0): ?>
                            <div class="alert alert-warning mt-2 mb-0">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                Outstanding balance: <?php echo format_currency($folio_summary['balance']); ?>
                                <a href="../billing/payments/add.php?reservation_id=<?php echo $reservation_id; ?>" class="btn btn-sm btn-success ms-2">
                                    <i class="fas fa-dollar-sign"></i> Record Payment
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Recent Folio Transactions -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list me-1"></i>
                            Recent Folio Transactions
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($folio_charges)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-receipt fa-3x mb-3"></i>
                                <p>No folio transactions</p>
                                <a href="../folio/add-charge.php?reservation_id=<?php echo $reservation_id; ?>" class="btn btn-sm btn-primary">
                                    Add Charge
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Description</th>
                                            <th class="text-end">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach (array_slice($folio_charges, 0, 5) as $charge): ?>
                                        <tr class="<?php echo ($charge['charge_type'] ?? '') == 'payment' ? 'table-success' : ''; ?>">
                                            <td><?php echo isset($charge['posted_at']) ? date('M d, H:i', strtotime($charge['posted_at'])) : 'N/A'; ?></td>
                                            <td>
                                                <?php echo htmlspecialchars($charge['description'] ?? ''); ?>
                                                <?php if (!empty($charge['is_voided'])): ?>
                                                    <span class="badge bg-danger">VOID</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end">
                                                <?php if (($charge['charge_type'] ?? '') == 'payment'): ?>
                                                    <span class="text-success">-<?php echo format_currency($charge['amount'] ?? 0); ?></span>
                                                <?php else: ?>
                                                    <span><?php echo format_currency($charge['amount'] ?? 0); ?></span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            <?php if (count($folio_charges) > 5): ?>
                                <div class="text-center p-2">
                                    <a href="../folio/view.php?reservation_id=<?php echo $reservation_id; ?>">View all <?php echo count($folio_charges); ?> transactions</a>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
function sendEmail() {
    const email = '<?php echo addslashes($reservation['email'] ?? ''); ?>';
    if (email) {
        window.location.href = 'mailto:' + email;
    } else {
        alert('No email address available');
    }
}

function sendSMS() {
    const phone = '<?php echo addslashes($reservation['phone'] ?? ''); ?>';
    if (phone) {
        window.location.href = 'sms:' + phone;
    } else {
        alert('No phone number available');
    }
}
</script>

<style>
.badge-lg {
    font-size: 1rem;
    padding: 0.5rem 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>';
}
?>