<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guests 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
// Current file: /HMSPOS/guests/guests/index.php
// Need to go up to: /HMSPOS/
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root
$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/guests/guests/ -> /HMSPOS/
    $base_path = dirname(dirname(dirname(__DIR__)));
}

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

// Load required files
require_once $base_path . '/config/config.php';
require_once $base_path . '/config/database.php';
require_once $base_path . '/config/auth.php';

// Load helpers if they exist
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';
}
if (file_exists($base_path . '/config/constants.php')) {
    require_once $base_path . '/config/constants.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
    }
}

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

if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount, 0);
    }
}

if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

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

if (!function_exists('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

if (!function_exists('display_flash_messages')) {
    function display_flash_messages() {
        if (isset($_SESSION['flash_messages']) && !empty($_SESSION['flash_messages'])) {
            foreach ($_SESSION['flash_messages'] as $flash) {
                $type = $flash['type'] ?? 'info';
                $message = $flash['message'] ?? '';
                echo '<div class="alert alert-' . $type . ' alert-dismissible fade show" role="alert">';
                echo htmlspecialchars($message);
                echo '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
                echo '</div>';
            }
            $_SESSION['flash_messages'] = [];
        }
    }
}

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

// Set page title
$page_title = 'Guests 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
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$nationality = $_GET['nationality'] ?? '';
$sort = $_GET['sort'] ?? 'guest_id';
$order = $_GET['order'] ?? 'DESC';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = defined('ITEMS_PER_PAGE') ? ITEMS_PER_PAGE : 25;

// Build where clause
$where = "1=1";
$params = [];

if (!empty($search)) {
    $where .= " AND (first_name LIKE ? OR last_name LIKE ? OR email LIKE ? OR phone LIKE ? OR guest_code LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

if ($status === 'blacklisted') {
    $where .= " AND is_blacklisted = 1";
} elseif ($status === 'active') {
    $where .= " AND is_blacklisted = 0";
}

if (!empty($nationality)) {
    $where .= " AND nationality = ?";
    $params[] = $nationality;
}

// Validate sort column
$allowed_sort = ['guest_id', 'guest_code', 'first_name', 'last_name', 'email', 'created_at', 'is_blacklisted'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'guest_id';
}

// Get total count
$total = 0;
try {
    $count_sql = "SELECT COUNT(*) FROM guests WHERE $where";
    $total = (int)db_fetch_value($count_sql, $params) ?: 0;
} catch (Exception $e) {
    error_log("Error counting guests: " . $e->getMessage());
}

// Get guests with statistics
$guests = [];
try {
    $sql = "
        SELECT 
            g.*,
            (SELECT COUNT(*) FROM reservations WHERE guest_id = g.guest_id) as total_stays,
            (SELECT COALESCE(SUM(total_amount), 0) FROM reservations WHERE guest_id = g.guest_id) as total_spent,
            (SELECT MAX(check_in_date) FROM reservations WHERE guest_id = g.guest_id) as last_visit,
            (SELECT COUNT(*) FROM reservations WHERE guest_id = g.guest_id AND booking_status = 'checked_in') as current_stay
        FROM guests g
        WHERE $where
        ORDER BY $sort $order
    ";
    
    // Get paginated data
    $offset = ($page - 1) * $per_page;
    $data_sql = $sql . " LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
    $guests = db_fetch_all($data_sql, $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching guests: " . $e->getMessage());
}

// Calculate pagination
$total_pages = $per_page > 0 ? ceil($total / $per_page) : 1;

// Get unique nationalities for filter
$nationalities = [];
try {
    $nationalities = db_fetch_all("SELECT DISTINCT nationality FROM guests WHERE nationality IS NOT NULL AND nationality != '' ORDER BY nationality") ?: [];
} catch (Exception $e) {
    error_log("Error fetching nationalities: " . $e->getMessage());
}

// Get summary statistics
$stats = [
    'total' => $total,
    'total_all' => 0,
    'active' => 0,
    'blacklisted' => 0,
    'with_email' => 0,
    'with_phone' => 0,
    'in_house' => 0,
    'new_today' => 0
];

try {
    $stats['total_all'] = (int)db_fetch_value("SELECT COUNT(*) FROM guests") ?: 0;
    $stats['active'] = (int)db_fetch_value("SELECT COUNT(*) FROM guests WHERE is_blacklisted = 0") ?: 0;
    $stats['blacklisted'] = (int)db_fetch_value("SELECT COUNT(*) FROM guests WHERE is_blacklisted = 1") ?: 0;
    $stats['with_email'] = (int)db_fetch_value("SELECT COUNT(*) FROM guests WHERE email IS NOT NULL AND email != ''") ?: 0;
    $stats['with_phone'] = (int)db_fetch_value("SELECT COUNT(*) FROM guests WHERE phone IS NOT NULL AND phone != ''") ?: 0;
    $stats['in_house'] = (int)db_fetch_value("SELECT COUNT(DISTINCT guest_id) FROM reservations WHERE booking_status = 'checked_in'") ?: 0;
    $stats['new_today'] = (int)db_fetch_value("SELECT COUNT(*) FROM guests WHERE DATE(created_at) = CURDATE()") ?: 0;
} catch (Exception $e) {
    error_log("Error fetching stats: " . $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>Guests 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; }
        </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="#">Guests 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">Guests 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/guests/dashboard.php">Guests</a></li>
                    <li class="breadcrumb-item active">All Guests</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if (function_exists('display_flash_messages')): ?>
            <?php display_flash_messages(); ?>
        <?php endif; ?>

        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-2 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo number_format($stats['total_all']); ?></h3>
                        <p>Total Guests</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo number_format($stats['in_house']); ?></h3>
                        <p>In-House</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-hotel"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-primary">
                    <div class="inner">
                        <h3><?php echo number_format($stats['active']); ?></h3>
                        <p>Active</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo number_format($stats['blacklisted']); ?></h3>
                        <p>Blacklisted</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-ban"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo number_format($stats['new_today']); ?></h3>
                        <p>New Today</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-user-plus"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php echo number_format($stats['total']); ?></h3>
                        <p>Filtered Results</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-filter"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-body">
                        <?php if (function_exists('has_permission') && has_permission('guests.create')): ?>
                            <a href="create.php" class="btn btn-primary me-2">
                                <i class="fas fa-user-plus"></i> New Guest
                            </a>
                        <?php endif; ?>
                        <a href="../history/index.php" class="btn btn-info me-2">
                            <i class="fas fa-history"></i> Guest History
                        </a>
                        <?php if (function_exists('has_permission') && has_permission('guests.blacklist')): ?>
                            <a href="blacklist.php" class="btn btn-danger me-2">
                                <i class="fas fa-ban"></i> Blacklist
                            </a>
                        <?php endif; ?>
                        <a href="/HMSPOS/reports/guest-analytics.php" class="btn btn-success me-2">
                            <i class="fas fa-chart-pie"></i> Analytics
                        </a>
                        <button type="button" class="btn btn-secondary" onclick="exportGuests()">
                            <i class="fas fa-download"></i> Export
                        </button>
                        <button type="button" class="btn btn-warning" onclick="quickSearch()">
                            <i class="fas fa-search"></i> Quick Search
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-filter me-1"></i>
                    Filters
                </h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse">
                        <i class="fas fa-minus"></i>
                    </button>
                </div>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <input type="text" class="form-control" name="search" placeholder="Search name, email, phone, code..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">All Guests</option>
                            <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="blacklisted" <?php echo $status == 'blacklisted' ? 'selected' : ''; ?>>Blacklisted</option>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="nationality">
                            <option value="">All Nationalities</option>
                            <?php foreach ($nationalities as $nat): ?>
                                <option value="<?php echo escape_html($nat['nationality'] ?? ''); ?>" <?php echo $nationality == ($nat['nationality'] ?? '') ? 'selected' : ''; ?>>
                                    <?php echo escape_html($nat['nationality'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-search"></i> Apply
                        </button>
                    </div>
                    
                    <div class="col-md-2">
                        <a href="?" class="btn btn-secondary w-100">
                            <i class="fas fa-times"></i> Clear
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Guests Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-list me-1"></i>
                    Guests (<?php echo $total; ?> total)
                </h3>
                <div class="card-tools">
                    <div class="input-group input-group-sm" style="width: 200px;">
                        <input type="text" class="form-control" id="tableSearch" placeholder="Search in table...">
                        <button class="btn btn-primary" type="button">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($guests)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-users fa-4x mb-3"></i>
                        <h5>No guests found</h5>
                        <p>Try adjusting your filters or create a new guest</p>
                        <?php if (function_exists('has_permission') && has_permission('guests.create')): ?>
                            <a href="create.php" class="btn btn-primary">
                                <i class="fas fa-plus me-1"></i> New Guest
                            </a>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover" id="guestsTable">
                            <thead>
                                <tr>
                                    <th>
                                        <a href="?sort=guest_code&order=<?php echo $sort === 'guest_code' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&nationality=<?php echo urlencode($nationality); ?>" class="text-dark">
                                            Code
                                            <?php if ($sort === 'guest_code'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>
                                        <a href="?sort=first_name&order=<?php echo $sort === 'first_name' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&nationality=<?php echo urlencode($nationality); ?>" class="text-dark">
                                            Name
                                            <?php if ($sort === 'first_name'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>Contact</th>
                                    <th>Nationality</th>
                                    <th class="text-center">Stays</th>
                                    <th class="text-end">Total Spent</th>
                                    <th>Last Visit</th>
                                    <th>Status</th>
                                    <th width="150">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($guests as $guest): ?>
                                <tr class="<?php echo ($guest['current_stay'] ?? 0) > 0 ? 'table-success' : (!empty($guest['is_blacklisted']) ? 'table-danger' : ''); ?>">
                                    <td>
                                        <strong><?php echo escape_html($guest['guest_code'] ?? ''); ?></strong>
                                    </td>
                                    <td>
                                        <a href="view.php?id=<?php echo $guest['guest_id'] ?? 0; ?>">
                                            <?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?>
                                        </a>
                                        <?php if (($guest['current_stay'] ?? 0) > 0): ?>
                                            <br><small class="text-success"><i class="fas fa-circle"></i> In-house</small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($guest['email'])): ?>
                                            <i class="fas fa-envelope text-muted me-1"></i><?php echo escape_html($guest['email']); ?><br>
                                        <?php endif; ?>
                                        <?php if (!empty($guest['phone'])): ?>
                                            <i class="fas fa-phone text-muted me-1"></i><?php echo escape_html($guest['phone']); ?>
                                        <?php endif; ?>
                                        <?php if (empty($guest['email']) && empty($guest['phone'])): ?>
                                            <span class="text-muted">No contact</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo !empty($guest['nationality']) ? escape_html($guest['nationality']) : '-'; ?></td>
                                    <td class="text-center">
                                        <span class="badge bg-info"><?php echo $guest['total_stays'] ?? 0; ?></span>
                                    </td>
                                    <td class="text-end"><?php echo format_currency($guest['total_spent'] ?? 0); ?></td>
                                    <td>
                                        <?php echo !empty($guest['last_visit']) ? format_date($guest['last_visit']) : 'Never'; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($guest['is_blacklisted'])): ?>
                                            <span class="badge bg-danger">Blacklisted</span>
                                        <?php else: ?>
                                            <span class="badge bg-success">Active</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="view.php?id=<?php echo $guest['guest_id'] ?? 0; ?>" 
                                               class="btn btn-sm btn-info" title="View">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('guests.edit')): ?>
                                                <a href="edit.php?id=<?php echo $guest['guest_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-warning" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                            <?php endif; ?>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('guests.documents')): ?>
                                                <a href="documents.php?id=<?php echo $guest['guest_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-primary" title="Documents">
                                                    <i class="fas fa-file-alt"></i>
                                                </a>
                                            <?php endif; ?>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('guests.blacklist')): ?>
                                                <?php if (!empty($guest['is_blacklisted'])): ?>
                                                    <button type="button" class="btn btn-sm btn-success" 
                                                            onclick="removeBlacklist(<?php echo $guest['guest_id'] ?? 0; ?>, '<?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?>')"
                                                            title="Remove from Blacklist">
                                                        <i class="fas fa-check-circle"></i>
                                                    </button>
                                                <?php else: ?>
                                                    <button type="button" class="btn btn-sm btn-danger" 
                                                            onclick="addBlacklist(<?php echo $guest['guest_id'] ?? 0; ?>, '<?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?>')"
                                                            title="Add to Blacklist">
                                                        <i class="fas fa-ban"></i>
                                                    </button>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                            
                                            <?php if (function_exists('has_permission') && has_permission('reservations.create')): ?>
                                                <a href="/HMSPOS/reservations/reservations/create.php?guest_id=<?php echo $guest['guest_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-success" title="New Reservation">
                                                    <i class="fas fa-calendar-plus"></i>
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="card-footer clearfix">
                <div class="row">
                    <div class="col-sm-5">
                        <span class="text-muted">
                            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $per_page, $total); ?> of <?php echo $total; ?> guests
                        </span>
                    </div>
                    <div class="col-sm-7">
                        <ul class="pagination pagination-sm float-end">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&nationality=<?php echo urlencode($nationality); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-angle-double-left"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&nationality=<?php echo urlencode($nationality); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-chevron-left"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                            
                            <?php
                            $start = max(1, $page - 2);
                            $end = min($total_pages, $page + 2);
                            
                            for ($i = $start; $i <= $end; $i++):
                            ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&nationality=<?php echo urlencode($nationality); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&nationality=<?php echo urlencode($nationality); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-chevron-right"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $total_pages; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo $status; ?>&nationality=<?php echo urlencode($nationality); ?>&sort=<?php echo $sort; ?>&order=<?php echo $order; ?>">
                                        <i class="fas fa-angle-double-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<!-- Quick Search Modal -->
<div class="modal fade" id="quickSearchModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-info">
                <h5 class="modal-title">Quick Guest Search</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" class="form-control form-control-lg" id="quickSearchInput" 
                               placeholder="Type name, email, phone, or code..." autocomplete="off">
                        <button class="btn btn-primary" type="button" onclick="performQuickSearch()">
                            Search
                        </button>
                    </div>
                </div>
                <div id="quickSearchResults" style="max-height: 400px; overflow-y: auto;"></div>
            </div>
        </div>
    </div>
</div>

<!-- Blacklist Modals -->
<div class="modal fade" id="blacklistModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Add to Blacklist</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="blacklist.php" method="POST">
                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                <input type="hidden" name="action" value="add">
                <input type="hidden" name="guest_id" id="blacklist_guest_id">
                
                <div class="modal-body">
                    <p>Are you sure you want to add <strong id="blacklist_guest_name"></strong> to the blacklist?</p>
                    
                    <div class="mb-3">
                        <label for="blacklist_reason" class="form-label">Reason</label>
                        <textarea class="form-control" id="blacklist_reason" name="reason" rows="3" required></textarea>
                    </div>
                    
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        Blacklisted guests cannot make new reservations and will be flagged at check-in.
                    </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">Add to Blacklist</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="removeBlacklistModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-success">
                <h5 class="modal-title">Remove from Blacklist</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="blacklist.php" method="POST">
                <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                <input type="hidden" name="action" value="remove">
                <input type="hidden" name="guest_id" id="remove_blacklist_guest_id">
                
                <div class="modal-body">
                    <p>Are you sure you want to remove <strong id="remove_blacklist_guest_name"></strong> from the blacklist?</p>
                    
                    <div class="mb-3">
                        <label for="remove_reason" class="form-label">Reason for removal</label>
                        <textarea class="form-control" id="remove_reason" name="reason" rows="2"></textarea>
                    </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">Remove from Blacklist</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
let searchTimeout;

$(document).ready(function() {
    // Table search
    $('#tableSearch').on('keyup', function() {
        const value = $(this).val().toLowerCase();
        $('#guestsTable tbody tr').filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });
    
    // Quick search input
    $('#quickSearchInput').on('keyup', function(e) {
        clearTimeout(searchTimeout);
        const query = $(this).val();
        
        if (query.length < 2) {
            $('#quickSearchResults').html('<div class="text-center text-muted py-3">Type at least 2 characters</div>');
            return;
        }
        
        if (e.key === 'Enter') {
            performQuickSearch();
            return;
        }
        
        searchTimeout = setTimeout(function() {
            performQuickSearch();
        }, 300);
    });
});

function addBlacklist(guestId, guestName) {
    document.getElementById('blacklist_guest_id').value = guestId;
    document.getElementById('blacklist_guest_name').textContent = guestName;
    
    const modal = new bootstrap.Modal(document.getElementById('blacklistModal'));
    modal.show();
}

function removeBlacklist(guestId, guestName) {
    document.getElementById('remove_blacklist_guest_id').value = guestId;
    document.getElementById('remove_blacklist_guest_name').textContent = guestName;
    
    const modal = new bootstrap.Modal(document.getElementById('removeBlacklistModal'));
    modal.show();
}

function quickSearch() {
    const modal = new bootstrap.Modal(document.getElementById('quickSearchModal'));
    modal.show();
    
    setTimeout(function() {
        document.getElementById('quickSearchInput').focus();
    }, 500);
}

function performQuickSearch() {
    const query = $('#quickSearchInput').val();
    
    if (query.length < 2) {
        $('#quickSearchResults').html('<div class="text-center text-muted py-3">Type at least 2 characters</div>');
        return;
    }
    
    $('#quickSearchResults').html('<div class="text-center py-4"><div class="spinner-border text-primary"></div></div>');
    
    $.ajax({
        url: '/HMSPOS/api/search-guests.php',
        method: 'GET',
        data: { q: query },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                displayQuickSearchResults(response.data);
            } else {
                $('#quickSearchResults').html('<div class="alert alert-danger">' + (response.message || 'Search failed') + '</div>');
            }
        },
        error: function(xhr, status, error) {
            $('#quickSearchResults').html('<div class="alert alert-danger">Search failed: ' + error + '</div>');
        }
    });
}

function displayQuickSearchResults(guests) {
    if (!guests || guests.length === 0) {
        $('#quickSearchResults').html('<div class="text-center text-muted py-4">No guests found</div>');
        return;
    }
    
    let html = '<div class="list-group">';
    guests.forEach(function(guest) {
        const name = (guest.first_name || '') + ' ' + (guest.last_name || '');
        const contact = [];
        if (guest.email) contact.push(guest.email);
        if (guest.phone) contact.push(guest.phone);
        
        html += `
            <a href="view.php?id=${guest.guest_id}" class="list-group-item list-group-item-action" onclick="$('#quickSearchModal').modal('hide')">
                <div class="d-flex justify-content-between">
                    <div>
                        <strong>${escapeHtml(name)}</strong>
                        ${guest.is_blacklisted ? '<span class="badge bg-danger ms-2">Blacklisted</span>' : ''}
                        <br>
                        <small class="text-muted">${escapeHtml(guest.guest_code || '')}</small>
                    </div>
                    <div class="text-end">
                        <small class="text-muted">${escapeHtml(contact.join(' | '))}</small>
                    </div>
                </div>
            </a>
        `;
    });
    html += '</div>';
    
    $('#quickSearchResults').html(html);
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function exportGuests() {
    const params = new URLSearchParams(window.location.search);
    params.set('export', 'csv');
    window.location.href = 'export-guests.php?' + params.toString();
}
</script>

<style>
.table td {
    vertical-align: middle;
}
.btn-group .btn {
    margin: 0 2px;
}
.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; }
.text-end { text-align: right; }
.float-end { float: right; }
.w-100 { width: 100%; }
.badge.bg-info { background-color: #17a2b8; color: #fff; }
.badge.bg-success { background-color: #28a745; color: #fff; }
.badge.bg-warning { background-color: #ffc107; color: #000; }
.badge.bg-danger { background-color: #dc3545; color: #fff; }
.badge.bg-secondary { background-color: #6c757d; 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>';
}
?>