<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Check-out Management - List View - FIXED VERSION
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 2) - should go up two levels to root
$base_path = dirname(__DIR__, 2);

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

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

// Load the universal initializer
$init_file = $base_path . '/config/init.php';
if (file_exists($init_file)) {
    require_once $init_file;
} else {
    // Emergency fallback - load files directly
    require_once $base_path . '/config/config.php';
    require_once $base_path . '/config/database.php';
    require_once $base_path . '/config/auth.php';
    
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
}

// Require authentication
require_auth();

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

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

// Set page title
$page_title = 'Check-out Management';

// Get current user
$current_user = function_exists('current_user') ? current_user() : null;
$user_id = $current_user['user_id'] ?? 0;

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

// Get filter parameters
$date = $_GET['date'] ?? date('Y-m-d');
$search = $_GET['search'] ?? '';

// Get today's departures
$departures = [];
try {
    $sql = "
        SELECT 
            r.*,
            g.guest_id, g.first_name, g.last_name, g.email, g.phone,
            rt.type_name,
            rm.room_number,
            DATEDIFF(r.check_out_date, r.check_in_date) as nights,
            (r.total_amount - r.paid_amount) as balance,
            (SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
             WHERE reservation_id = r.reservation_id AND charge_type != 'payment' AND is_voided = 0) as total_charges,
            (SELECT COALESCE(SUM(amount), 0) FROM folio_charges 
             WHERE reservation_id = r.reservation_id AND charge_type = 'payment' AND is_voided = 0) as total_payments
        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.check_out_date = ?
        AND r.booking_status = 'checked_in'
    ";
    
    $params = [$date];
    
    if (!empty($search)) {
        $sql .= " AND (g.first_name LIKE ? OR g.last_name LIKE ? OR r.booking_code LIKE ?)";
        $search_term = "%$search%";
        $params[] = $search_term;
        $params[] = $search_term;
        $params[] = $search_term;
    }
    
    $sql .= " ORDER BY rm.room_number";
    
    $departures = db_fetch_all($sql, $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching departures: " . $e->getMessage());
    $departures = [];
}

// Calculate statistics
$stats = [
    'today' => count($departures),
    'total_balance' => 0,
    'total_charges' => 0,
    'total_payments' => 0
];

foreach ($departures as $res) {
    $stats['total_balance'] += $res['balance'] ?? 0;
    $stats['total_charges'] += $res['total_charges'] ?? 0;
    $stats['total_payments'] += $res['total_payments'] ?? 0;
}

// Get extended stay candidates (guests who might want to extend)
$extend_candidates = [];
try {
    $extend_candidates = db_fetch_all("
        SELECT 
            r.*,
            g.first_name, g.last_name,
            rm.room_number
        FROM reservations r
        JOIN guests g ON r.guest_id = g.guest_id
        JOIN rooms rm ON r.room_id = rm.room_id
        WHERE r.check_out_date = ?
        AND r.booking_status = 'checked_in'
        AND rm.status = 'occupied'
        AND NOT EXISTS (
            SELECT 1 FROM reservations r2 
            WHERE r2.room_id = r.room_id 
            AND r2.booking_status IN ('confirmed', 'pending')
            AND r2.check_in_date = ?
        )
        LIMIT 5
    ", [$date, date('Y-m-d', strtotime('+1 day'))]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching extend candidates: " . $e->getMessage());
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // Simple fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Check-out Management</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; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; overflow: hidden; color: #fff; }
            .small-box .inner { padding: 20px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .small-box .icon { position: absolute; top: 10px; right: 15px; font-size: 4rem; opacity: 0.3; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-success { background-color: #28a745 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-danger { background-color: #dc3545 !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="#">Check-out Management</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-out Management</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 active">Check-out</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Date Navigation -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-md-4">
                                <div class="btn-group">
                                    <a href="?date=<?php echo date('Y-m-d', strtotime($date . ' -1 day')); ?>" class="btn btn-primary">
                                        <i class="fas fa-chevron-left"></i> Previous Day
                                    </a>
                                    <a href="?date=<?php echo date('Y-m-d'); ?>" class="btn btn-info">
                                        <i class="fas fa-calendar-day"></i> Today
                                    </a>
                                    <a href="?date=<?php echo date('Y-m-d', strtotime($date . ' +1 day')); ?>" class="btn btn-primary">
                                        Next Day <i class="fas fa-chevron-right"></i>
                                    </a>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <form method="GET" class="d-flex justify-content-center">
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-calendar"></i></span>
                                        <input type="date" class="form-control" name="date" value="<?php echo htmlspecialchars($date); ?>">
                                        <button type="submit" class="btn btn-primary">Go</button>
                                    </div>
                                </form>
                            </div>
                            
                            <div class="col-md-4 text-end">
                                <h4><?php echo function_exists('format_date') ? format_date($date, 'l, F j, Y') : date('l, F j, Y', strtotime($date)); ?></h4>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['today']; ?></h3>
                        <p>Departures Today</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-sign-out-alt"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo function_exists('format_currency') ? format_currency($stats['total_charges']) : 'RWF ' . number_format($stats['total_charges']); ?></h3>
                        <p>Total Charges</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo function_exists('format_currency') ? format_currency($stats['total_payments']) : 'RWF ' . number_format($stats['total_payments']); ?></h3>
                        <p>Payments Received</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-arrow-down"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo function_exists('format_currency') ? format_currency($stats['total_balance']) : 'RWF ' . number_format($stats['total_balance']); ?></h3>
                        <p>Outstanding Balance</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Search -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <input type="hidden" name="date" value="<?php echo htmlspecialchars($date); ?>">
                            <div class="col-md-8">
                                <input type="text" class="form-control" name="search" placeholder="Search guest or booking..." 
                                       value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-search me-1"></i> Search
                                </button>
                                <?php if (!empty($search)): ?>
                                    <a href="?date=<?php echo urlencode($date); ?>" class="btn btn-secondary">
                                        <i class="fas fa-times me-1"></i> Clear
                                    </a>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Today's Departures -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sign-out-alt me-1"></i>
                            Today's Departures (<?php echo count($departures); ?>)
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($departures)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-calendar-times fa-4x mb-3"></i>
                                <h5>No departures scheduled for <?php echo function_exists('format_date') ? format_date($date) : $date; ?></h5>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Room</th>
                                            <th>Guest</th>
                                            <th>Booking #</th>
                                            <th>Check-in</th>
                                            <th>Nights</th>
                                            <th class="text-end">Charges</th>
                                            <th class="text-end">Payments</th>
                                            <th class="text-end">Balance</th>
                                            <th width="150">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($departures as $res): ?>
                                        <?php $balance = ($res['total_amount'] ?? 0) - ($res['paid_amount'] ?? 0); ?>
                                        <tr class="<?php echo $balance > 0 ? 'table-warning' : 'table-success'; ?>">
                                            <td>
                                                <span class="badge bg-info"><?php echo htmlspecialchars($res['room_number'] ?? ''); ?></span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/guests/guests/view.php?id=<?php echo $res['guest_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars(($res['first_name'] ?? '') . ' ' . ($res['last_name'] ?? '')); ?>
                                                </a>
                                                <br>
                                                <small class="text-muted"><?php echo htmlspecialchars($res['email'] ?? ''); ?></small>
                                            </td>
                                            <td>
                                                <a href="../reservations/view.php?id=<?php echo $res['reservation_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($res['booking_code'] ?? ''); ?>
                                                </a>
                                            </td>
                                            <td><?php echo function_exists('format_date') ? format_date($res['check_in_date'] ?? '') : ($res['check_in_date'] ?? ''); ?></td>
                                            <td class="text-center"><?php echo $res['nights'] ?? 1; ?></td>
                                            <td class="text-end"><?php echo function_exists('format_currency') ? format_currency($res['total_charges'] ?? 0) : 'RWF ' . number_format($res['total_charges'] ?? 0); ?></td>
                                            <td class="text-end text-success"><?php echo function_exists('format_currency') ? format_currency($res['total_payments'] ?? 0) : 'RWF ' . number_format($res['total_payments'] ?? 0); ?></td>
                                            <td class="text-end">
                                                <strong class="text-<?php echo $balance > 0 ? 'danger' : 'success'; ?>">
                                                    <?php echo function_exists('format_currency') ? format_currency($balance) : 'RWF ' . number_format($balance); ?>
                                                </strong>
                                            </td>
                                            <td>
                                                <a href="start.php?id=<?php echo $res['reservation_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning">
                                                    <i class="fas fa-sign-out-alt"></i> Check-out
                                                </a>
                                                <?php if ($balance > 0): ?>
                                                    <a href="../folio/add-charge.php?reservation_id=<?php echo $res['reservation_id'] ?? 0; ?>" 
                                                       class="btn btn-sm btn-success mt-1">
                                                        <i class="fas fa-dollar-sign"></i> Payment
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Extended Stay Suggestions -->
        <?php if (!empty($extend_candidates)): ?>
        <div class="row mt-4">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clock me-1"></i>
                            Extended Stay Opportunities
                        </h3>
                    </div>
                    <div class="card-body">
                        <p>These guests might be interested in extending their stay (room available tomorrow).</p>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Room</th>
                                        <th>Guest</th>
                                        <th>Current Check-out</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($extend_candidates as $candidate): ?>
                                    <tr>
                                        <td><span class="badge bg-info"><?php echo htmlspecialchars($candidate['room_number'] ?? ''); ?></span></td>
                                        <td><?php echo htmlspecialchars(($candidate['first_name'] ?? '') . ' ' . ($candidate['last_name'] ?? '')); ?></td>
                                        <td><?php echo function_exists('format_date') ? format_date($candidate['check_out_date'] ?? '') : ($candidate['check_out_date'] ?? ''); ?></td>
                                        <td>
                                            <a href="../reservations/edit.php?id=<?php echo $candidate['reservation_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info">
                                                <i class="fas fa-calendar-plus"></i> Extend Stay
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Check-out Checklist -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card card-secondary">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-clipboard-check me-1"></i>
                            Check-out Checklist
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-info">
                                        <i class="fas fa-file-invoice"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">1. Review Folio</span>
                                        <span class="info-box-number small">Check all charges</span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-success">
                                        <i class="fas fa-dollar-sign"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">2. Settle Balance</span>
                                        <span class="info-box-number small">Collect payment if needed</span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-warning">
                                        <i class="fas fa-key"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">3. Return Keys</span>
                                        <span class="info-box-number small">Collect room keys</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-4 { margin-top: 1.5rem; }
.text-end { text-align: right; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
.table-warning { background-color: #fff3cd; }
.table-success { background-color: #d4edda; }
</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>';
}
?>