<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * View Guest Folio - 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/folio/
$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/folio/ -> /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_datetime function if it doesn't exist
if (!function_exists('format_datetime')) {
    function format_datetime($datetime, $format = 'M d, H:i') {
        if (empty($datetime)) return '';
        return date($format, strtotime($datetime));
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

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

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

// Set page title
$page_title = 'Guest Folio';

// 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['reservation_id']) ? (int)$_GET['reservation_id'] : 0;

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

// Get reservation and guest information
$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,
                rt.type_name, rt.type_code,
                rm.room_number,
                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('../reservations/index.php');
    } else {
        header('Location: ../reservations/index.php');
        exit;
    }
}

// Get all folio charges
$folio_charges = [];
if (function_exists('db_fetch_all')) {
    try {
        $folio_charges = db_fetch_all("
            SELECT 
                fc.*,
                u.first_name, u.last_name,
                vu.first_name as voided_by_first, vu.last_name as voided_by_last,
                p.product_name,
                po.outlet_name
            FROM folio_charges fc
            LEFT JOIN users u ON fc.posted_by = u.user_id
            LEFT JOIN users vu ON fc.voided_by = vu.user_id
            LEFT JOIN pos_products p ON fc.product_id = p.product_id
            LEFT JOIN pos_outlets po ON fc.pos_outlet_id = po.outlet_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 totals
$totals = [
    'room_charges' => 0,
    'fnb_charges' => 0,
    'service_charges' => 0,
    'other_charges' => 0,
    'payments' => 0,
    'adjustments' => 0,
    'total_charges' => 0,
    'total_paid' => 0
];

foreach ($folio_charges as $charge) {
    if (!empty($charge['is_voided'])) {
        continue;
    }
    
    if (($charge['charge_type'] ?? '') == 'payment') {
        $totals['payments'] += $charge['amount'] ?? 0;
        $totals['total_paid'] += $charge['amount'] ?? 0;
    } elseif (($charge['charge_type'] ?? '') == 'adjustment') {
        $totals['adjustments'] += $charge['amount'] ?? 0;
        $totals['total_charges'] += $charge['amount'] ?? 0;
    } else {
        $totals['total_charges'] += $charge['amount'] ?? 0;
        
        switch ($charge['charge_type'] ?? '') {
            case 'room':
                $totals['room_charges'] += $charge['amount'] ?? 0;
                break;
            case 'fnb':
                $totals['fnb_charges'] += $charge['amount'] ?? 0;
                break;
            case 'service':
                $totals['service_charges'] += $charge['amount'] ?? 0;
                break;
            default:
                $totals['other_charges'] += $charge['amount'] ?? 0;
        }
    }
}

$balance = $totals['total_charges'] - $totals['total_paid'];

// 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>Guest Folio</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; }
            .info-box { box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2); border-radius: 0.25rem; background: #fff; display: flex; margin-bottom: 20px; min-height: 80px; }
            .info-box-icon { border-radius: 0.25rem 0 0 0.25rem; display: flex; align-items: center; justify-content: center; width: 70px; font-size: 1.875rem; text-align: center; }
            .info-box-content { padding: 10px; flex: 1; }
            .bg-info { background-color: #17a2b8 !important; color: #fff; }
            .bg-success { background-color: #28a745 !important; color: #fff; }
            .bg-light { background-color: #f8f9fa !important; }
            .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-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; }
            
            @media print {
                .main-header, .main-sidebar, .main-footer, .btn, .card-tools, .btn-group {
                    display: none !important;
                }
                .content-wrapper {
                    margin-left: 0 !important;
                    padding: 0 !important;
                }
                .card {
                    border: none !important;
                    box-shadow: none !important;
                }
            }
        </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="#">Guest Folio</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">Guest Folio</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="../reservations/view.php?id=<?php echo $reservation_id; ?>">Reservation</a></li>
                    <li class="breadcrumb-item active">Folio</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="../reservations/view.php?id=<?php echo $reservation_id; ?>" class="btn btn-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Back to Reservation
                    </a>
                    
                    <?php if (function_exists('has_permission') && has_permission('reservations.folio')): ?>
                        <a href="add-charge.php?reservation_id=<?php echo $reservation_id; ?>" class="btn btn-success">
                            <i class="fas fa-plus-circle me-1"></i> Add Charge
                        </a>
                        
                        <?php if ($balance > 0): ?>
                            <a href="add-charge.php?reservation_id=<?php echo $reservation_id; ?>&type=payment" class="btn btn-primary">
                                <i class="fas fa-dollar-sign me-1"></i> Record Payment
                            </a>
                        <?php endif; ?>
                        
                        <a href="#" onclick="printFolio()" class="btn btn-info">
                            <i class="fas fa-print me-1"></i> Print Folio
                        </a>
                        
                        <a href="move-charge.php?reservation_id=<?php echo $reservation_id; ?>" class="btn btn-warning">
                            <i class="fas fa-exchange-alt me-1"></i> Move Charges
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Folio Summary -->
            <div class="col-md-4">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Guest Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>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"><?php echo $reservation['room_number'] ?: 'Not assigned'; ?></span>
                                </td>
                            </tr>
                            <tr>
                                <th>Booking Code:</th>
                                <td><?php echo htmlspecialchars($reservation['booking_code'] ?? 'N/A'); ?></td>
                            </tr>
                            <tr>
                                <th>Check-in:</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:</th>
                                <td><?php echo isset($reservation['check_out_date']) ? date('M d, Y', strtotime($reservation['check_out_date'])) : 'N/A'; ?></td>
                            </tr>
                            <tr>
                                <th>Status:</th>
                                <td>
                                    <span class="badge bg-<?php 
                                        $status = $reservation['booking_status'] ?? '';
                                        echo $status == 'checked_in' ? 'success' : 
                                            ($status == 'confirmed' ? 'info' : 
                                            ($status == 'checked_out' ? 'secondary' : 'warning'));
                                    ?>">
                                        <?php echo ucfirst($status); ?>
                                    </span>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Financial Summary -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-calculator me-1"></i>
                            Financial Summary
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th>Room Charges:</th>
                                <td class="text-end"><?php echo format_currency($totals['room_charges']); ?></td>
                            </tr>
                            <tr>
                                <th>F&B Charges:</th>
                                <td class="text-end"><?php echo format_currency($totals['fnb_charges']); ?></td>
                            </tr>
                            <tr>
                                <th>Service Charges:</th>
                                <td class="text-end"><?php echo format_currency($totals['service_charges']); ?></td>
                            </tr>
                            <tr>
                                <th>Other Charges:</th>
                                <td class="text-end"><?php echo format_currency($totals['other_charges']); ?></td>
                            </tr>
                            <tr>
                                <th>Adjustments:</th>
                                <td class="text-end"><?php echo format_currency($totals['adjustments']); ?></td>
                            </tr>
                            <tr class="table-info">
                                <th>Total Charges:</th>
                                <td class="text-end"><strong><?php echo format_currency($totals['total_charges']); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Payments:</th>
                                <td class="text-end text-success">- <?php echo format_currency($totals['payments']); ?></td>
                            </tr>
                            <tr class="<?php echo $balance > 0 ? 'table-warning' : 'table-success'; ?>">
                                <th>Current Balance:</th>
                                <td class="text-end">
                                    <strong><?php echo format_currency($balance); ?></strong>
                                </td>
                            </tr>
                        </table>
                        
                        <?php if ($balance > 0): ?>
                            <div class="alert alert-warning mt-2">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                Outstanding balance: <?php echo format_currency($balance); ?>
                            </div>
                        <?php elseif ($balance < 0): ?>
                            <div class="alert alert-info mt-2">
                                <i class="fas fa-info-circle me-2"></i>
                                Credit balance: <?php echo format_currency(abs($balance)); ?>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-success mt-2">
                                <i class="fas fa-check-circle me-2"></i>
                                Balance paid in full
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Quick Stats -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar me-1"></i>
                            Folio Statistics
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-info elevation-1">
                                <i class="fas fa-receipt"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Total Transactions</span>
                                <span class="info-box-number"><?php echo count($folio_charges); ?></span>
                            </div>
                        </div>
                        
                        <div class="info-box bg-light">
                            <span class="info-box-icon bg-success elevation-1">
                                <i class="fas fa-clock"></i>
                            </span>
                            <div class="info-box-content">
                                <span class="info-box-text">Average per Night</span>
                                <span class="info-box-number">
                                    <?php 
                                    $nights = $reservation['nights'] ?? 1;
                                    $avg = $nights > 0 ? ($totals['total_charges'] / $nights) : 0;
                                    echo format_currency($avg);
                                    ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Folio Transactions -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list me-1"></i>
                            Folio Transactions
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-default" onclick="refreshFolio()">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($folio_charges)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-receipt fa-4x mb-3"></i>
                                <h5>No folio transactions</h5>
                                <p>Click "Add Charge" to add the first transaction</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Date/Time</th>
                                            <th>Transaction #</th>
                                            <th>Type</th>
                                            <th>Description</th>
                                            <th class="text-end">Amount</th>
                                            <th>Posted By</th>
                                            <th>Status</th>
                                            <th width="100">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($folio_charges as $charge): ?>
                                        <tr class="<?php 
                                            echo !empty($charge['is_voided']) ? 'text-muted' : 
                                                (($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>
                                                <small><?php echo htmlspecialchars($charge['transaction_code'] ?? ''); ?></small>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    $type = $charge['charge_type'] ?? '';
                                                    echo $type == 'payment' ? 'success' : 
                                                        ($type == 'room' ? 'primary' : 
                                                        ($type == 'fnb' ? 'info' : 
                                                        ($type == 'service' ? 'warning' : 
                                                        ($type == 'adjustment' ? 'secondary' : 'dark'))));
                                                ?>">
                                                    <?php echo ucfirst($type); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php echo escape_html($charge['description'] ?? ''); ?>
                                                <?php if (!empty($charge['product_name'])): ?>
                                                    <br>
                                                    <small class="text-muted"><?php echo htmlspecialchars($charge['product_name']); ?></small>
                                                <?php endif; ?>
                                                <?php if (!empty($charge['outlet_name'])): ?>
                                                    <br>
                                                    <small class="text-muted"><?php echo htmlspecialchars($charge['outlet_name']); ?></small>
                                                <?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>
                                            <td>
                                                <small><?php echo escape_html($charge['first_name'] ?? ''); ?></small>
                                            </td>
                                            <td>
                                                <?php if (!empty($charge['is_voided'])): ?>
                                                    <span class="badge bg-danger">VOID</span>
                                                    <br>
                                                    <small>by <?php echo escape_html($charge['voided_by_first'] ?? ''); ?></small>
                                                <?php else: ?>
                                                    <span class="badge bg-success">Active</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if (empty($charge['is_voided']) && ($charge['charge_type'] ?? '') != 'payment'): ?>
                                                    <button type="button" class="btn btn-sm btn-danger" 
                                                            onclick="voidCharge(<?php echo $charge['charge_id'] ?? 0; ?>)">
                                                        <i class="fas fa-ban"></i>
                                                    </button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="card-footer">
                        <div class="row">
                            <div class="col-sm-6">
                                <small class="text-muted">
                                    <i class="fas fa-info-circle me-1"></i>
                                    Showing all <?php echo count($folio_charges); ?> transactions
                                </small>
                            </div>
                            <div class="col-sm-6 text-end">
                                <button type="button" class="btn btn-sm btn-primary" onclick="exportFolio()">
                                    <i class="fas fa-download"></i> Export CSV
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Void Charge Modal -->
<div class="modal fade" id="voidModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Void Charge</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="voidForm">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php else: ?>
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                <?php endif; ?>
                <input type="hidden" name="charge_id" id="void_charge_id">
                
                <div class="modal-body">
                    <p>Are you sure you want to void this charge?</p>
                    
                    <div class="form-group mb-3">
                        <label for="void_reason">Reason for voiding</label>
                        <textarea class="form-control" id="void_reason" name="void_reason" rows="2" required></textarea>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        This action cannot be undone.
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Void Charge</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function voidCharge(chargeId) {
    $('#void_charge_id').val(chargeId);
    
    // Initialize Bootstrap 5 modal
    const voidModal = new bootstrap.Modal(document.getElementById('voidModal'));
    voidModal.show();
}

$('#voidForm').on('submit', function(e) {
    e.preventDefault();
    
    $.post('/HMSPOS/api/void-charge.php', $(this).serialize(), function(response) {
        if (response.status === 'success') {
            // Hide modal using Bootstrap 5
            const voidModal = bootstrap.Modal.getInstance(document.getElementById('voidModal'));
            voidModal.hide();
            location.reload();
        } else {
            alert('Failed to void charge: ' + response.message);
        }
    }).fail(function(xhr) {
        alert('Failed to void charge: ' + (xhr.responseJSON?.message || 'Unknown error'));
    });
});

function printFolio() {
    window.print();
}

function refreshFolio() {
    location.reload();
}

function exportFolio() {
    window.location.href = 'export-folio.php?reservation_id=<?php echo $reservation_id; ?>';
}
</script>

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