<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Check-in Management - List View - FINAL 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
$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/checkin/ -> /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.checkin');
// }

// Set page title
$page_title = 'Check-in 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 arrivals
$arrivals = [];
try {
    $sql = "
        SELECT 
            r.*,
            g.guest_id, g.first_name, g.last_name, g.email, g.phone,
            rt.type_name, rt.type_code,
            rm.room_number,
            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
        WHERE r.check_in_date = ?
        AND r.booking_status IN ('confirmed', 'pending')
    ";
    
    $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 r.booking_status, r.booking_code";
    
    $arrivals = db_fetch_all($sql, $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching arrivals: " . $e->getMessage());
    $arrivals = [];
}

// Get upcoming arrivals (next 7 days)
$upcoming = [];
try {
    $upcoming = db_fetch_all("
        SELECT 
            r.*,
            g.first_name, g.last_name,
            rt.type_name
        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
        WHERE r.check_in_date BETWEEN ? AND ?
        AND r.booking_status IN ('confirmed', 'pending')
        ORDER BY r.check_in_date
        LIMIT 20
    ", [date('Y-m-d'), date('Y-m-d', strtotime('+7 days'))]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching upcoming: " . $e->getMessage());
    $upcoming = [];
}

// Get statistics
$stats = [
    'today' => count($arrivals),
    'confirmed' => 0,
    'pending' => 0,
    'checked_in' => 0
];

try {
    $stats['confirmed'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM reservations 
        WHERE check_in_date = ? AND booking_status = 'confirmed'
    ", [$date]) ?: 0;
    
    $stats['pending'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM reservations 
        WHERE check_in_date = ? AND booking_status = 'pending'
    ", [$date]) ?: 0;
    
    $stats['checked_in'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM reservations 
        WHERE check_in_date = ? AND booking_status = 'checked_in'
    ", [$date]) ?: 0;
} catch (Exception $e) {
    error_log("Error fetching stats: " . $e->getMessage());
}

// Get room types for quick check-in modal
$room_types = [];
try {
    $room_types = db_fetch_all("SELECT * FROM room_types ORDER BY type_name") ?: [];
} catch (Exception $e) {
    error_log("Error fetching room types: " . $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-in 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-primary { background-color: #007bff !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-in 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-in 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-in</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>Total Arrivals</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-check"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['confirmed']; ?></h3>
                        <p>Confirmed</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo $stats['pending']; ?></h3>
                        <p>Pending</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clock"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-primary">
                    <div class="inner">
                        <h3><?php echo $stats['checked_in']; ?></h3>
                        <p>Already Checked In</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-sign-in-alt"></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 Arrivals -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-sign-in-alt me-1"></i>
                            Today's Arrivals (<?php echo count($arrivals); ?>)
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-primary" onclick="quickCheckin()">
                                <i class="fas fa-bolt"></i> Quick Walk-in
                            </button>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($arrivals)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-calendar-check fa-4x mb-3"></i>
                                <h5>No arrivals scheduled for <?php echo function_exists('format_date') ? format_date($date) : $date; ?></h5>
                                <p>Click "Quick Walk-in" to create a new check-in</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Booking #</th>
                                            <th>Guest</th>
                                            <th>Room Type</th>
                                            <th>Assigned Room</th>
                                            <th>Nights</th>
                                            <th>Guests</th>
                                            <th class="text-end">Balance</th>
                                            <th>Status</th>
                                            <th width="150">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($arrivals as $res): ?>
                                        <?php $balance = ($res['total_amount'] ?? 0) - ($res['paid_amount'] ?? 0); ?>
                                        <tr class="<?php echo $balance > 0 ? 'table-warning' : ''; ?>">
                                            <td>
                                                <a href="../reservations/view.php?id=<?php echo $res['reservation_id'] ?? 0; ?>">
                                                    <strong><?php echo htmlspecialchars($res['booking_code'] ?? ''); ?></strong>
                                                </a>
                                            </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><?php echo htmlspecialchars($res['type_name'] ?? ''); ?></td>
                                            <td>
                                                <?php if (!empty($res['room_number'])): ?>
                                                    <span class="badge bg-info">Room <?php echo htmlspecialchars($res['room_number']); ?></span>
                                                <?php else: ?>
                                                    <span class="badge bg-warning">Not assigned</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center"><?php echo $res['nights'] ?? 1; ?></td>
                                            <td class="text-center">
                                                <i class="fas fa-user"></i> <?php echo $res['adults'] ?? 2; ?>
                                                <?php if (($res['children'] ?? 0) > 0): ?>
                                                    <br><i class="fas fa-child"></i> <?php echo $res['children']; ?>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end">
                                                <?php if ($balance > 0): ?>
                                                    <span class="badge bg-warning"><?php echo function_exists('format_currency') ? format_currency($balance) : 'RWF ' . number_format($balance); ?></span>
                                                <?php else: ?>
                                                    <span class="badge bg-success">Paid</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?php echo ($res['booking_status'] ?? '') == 'confirmed' ? 'success' : 'warning'; ?>">
                                                    <?php echo ucfirst($res['booking_status'] ?? 'pending'); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="start.php?id=<?php echo $res['reservation_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success">
                                                    <i class="fas fa-sign-in-alt"></i> Check-in
                                                </a>
                                                <?php if (empty($res['room_number'])): ?>
                                                    <a href="../reservations/assign-room.php?id=<?php echo $res['reservation_id'] ?? 0; ?>" 
                                                       class="btn btn-sm btn-info">
                                                        <i class="fas fa-door-open"></i> Assign
                                                    </a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Upcoming Arrivals -->
        <?php if (!empty($upcoming)): ?>
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-calendar-alt me-1"></i>
                            Upcoming Arrivals (Next 7 Days)
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Guest</th>
                                        <th>Booking #</th>
                                        <th>Room Type</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($upcoming as $res): ?>
                                    <tr>
                                        <td><?php echo function_exists('format_date') ? format_date($res['check_in_date'] ?? '') : ($res['check_in_date'] ?? ''); ?></td>
                                        <td><?php echo htmlspecialchars(($res['first_name'] ?? '') . ' ' . ($res['last_name'] ?? '')); ?></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 htmlspecialchars($res['type_name'] ?? ''); ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo ($res['booking_status'] ?? '') == 'confirmed' ? 'success' : 'warning'; ?>">
                                                <?php echo ucfirst($res['booking_status'] ?? 'pending'); ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</section>

<!-- Quick Check-in Modal -->
<div class="modal fade" id="quickCheckinModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-success">
                <h5 class="modal-title">Quick Walk-in Check-in</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="start.php" method="POST">
                <?php if (function_exists('csrf_field')): ?>
                    <?php echo csrf_field(); ?>
                <?php else: ?>
                    <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                <?php endif; ?>
                <input type="hidden" name="walkin" value="1">
                
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6 class="mb-3">Guest Information</h6>
                            <div class="mb-3">
                                <label>First Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="first_name" required>
                            </div>
                            
                            <div class="mb-3">
                                <label>Last Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="last_name" required>
                            </div>
                            
                            <div class="mb-3">
                                <label>Email</label>
                                <input type="email" class="form-control" name="email">
                            </div>
                            
                            <div class="mb-3">
                                <label>Phone</label>
                                <input type="tel" class="form-control" name="phone">
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <h6 class="mb-3">Reservation Details</h6>
                            <div class="mb-3">
                                <label>Room Type <span class="text-danger">*</span></label>
                                <select class="form-control" name="room_type_id" required>
                                    <option value="">Select Room Type</option>
                                    <?php foreach ($room_types as $type): ?>
                                        <option value="<?php echo $type['room_type_id'] ?? 0; ?>">
                                            <?php echo htmlspecialchars($type['type_name'] ?? ''); ?> - 
                                            <?php echo function_exists('format_currency') ? format_currency($type['base_price'] ?? 0) : 'RWF ' . number_format($type['base_price'] ?? 0); ?>/night
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label>Nights <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="nights" value="1" min="1" required>
                            </div>
                            
                            <div class="mb-3">
                                <label>Adults <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="adults" value="2" min="1" required>
                            </div>
                            
                            <div class="mb-3">
                                <label>Children</label>
                                <input type="number" class="form-control" name="children" value="0" min="0">
                            </div>
                        </div>
                    </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-success">Process Check-in</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function quickCheckin() {
    const modal = new bootstrap.Modal(document.getElementById('quickCheckinModal'));
    modal.show();
}
</script>

<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; }
.table-warning { background-color: #fff3cd; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-primary { background-color: #007bff; color: #fff; }
</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>';
}
?>