<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * View Guest Details - 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/view.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('time_ago')) {
    function time_ago($datetime) {
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) {
            return $diff . ' seconds ago';
        } elseif ($diff < 3600) {
            $mins = floor($diff / 60);
            return $mins . ' minute' . ($mins > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 86400) {
            $hours = floor($diff / 3600);
            return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
        } elseif ($diff < 2592000) {
            $days = floor($diff / 86400);
            return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
        } else {
            return date('M d, Y', $time);
        }
    }
}

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

if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = [
            'type' => $type,
            'message' => $message,
            'time' => time()
        ];
    }
}

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 . '">';
    }
}

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

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

// 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 guest ID from URL
$guest_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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

// Get guest data
$guest = null;
try {
    $guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$guest_id]);
} catch (Exception $e) {
    error_log("Error fetching guest: " . $e->getMessage());
}

if (!$guest) {
    set_flash_message('danger', 'Guest not found');
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get guest statistics
$stats = [
    'total_stays' => 0,
    'total_nights' => 0,
    'total_spent' => 0,
    'average_spent' => 0,
    'last_visit' => null,
    'cancellations' => 0
];

try {
    $stats['total_stays'] = (int)db_fetch_value("SELECT COUNT(*) FROM reservations WHERE guest_id = ?", [$guest_id]) ?: 0;
    $stats['total_nights'] = (int)db_fetch_value("
        SELECT COALESCE(SUM(DATEDIFF(check_out_date, check_in_date)), 0) 
        FROM reservations WHERE guest_id = ? AND booking_status != 'cancelled'
    ", [$guest_id]) ?: 0;
    $stats['total_spent'] = (float)db_fetch_value("
        SELECT COALESCE(SUM(total_amount), 0) 
        FROM reservations WHERE guest_id = ? AND booking_status != 'cancelled'
    ", [$guest_id]) ?: 0;
    $stats['average_spent'] = $stats['total_stays'] > 0 ? $stats['total_spent'] / $stats['total_stays'] : 0;
    $stats['last_visit'] = db_fetch_value("
        SELECT MAX(check_in_date) 
        FROM reservations WHERE guest_id = ?
    ", [$guest_id]);
    $stats['cancellations'] = (int)db_fetch_value("
        SELECT COUNT(*) FROM reservations 
        WHERE guest_id = ? AND booking_status = 'cancelled'
    ", [$guest_id]) ?: 0;
} catch (Exception $e) {
    error_log("Error fetching guest stats: " . $e->getMessage());
}

// Get current active reservation
$current_reservation = null;
try {
    $current_reservation = db_fetch_one("
        SELECT r.*, rt.type_name, rm.room_number
        FROM reservations r
        LEFT 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.guest_id = ? AND r.booking_status = 'checked_in'
        ORDER BY r.check_in_date DESC
        LIMIT 1
    ", [$guest_id]);
} catch (Exception $e) {
    error_log("Error fetching current reservation: " . $e->getMessage());
}

// Get recent reservations
$recent_reservations = [];
try {
    $recent_reservations = db_fetch_all("
        SELECT r.*, rt.type_name, rm.room_number,
               DATEDIFF(r.check_out_date, r.check_in_date) as nights
        FROM reservations r
        LEFT 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.guest_id = ?
        ORDER BY r.check_in_date DESC
        LIMIT 10
    ", [$guest_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching recent reservations: " . $e->getMessage());
}

// Get guest documents
$documents = [];
try {
    $documents = db_fetch_all("
        SELECT d.*, u.first_name, u.last_name
        FROM guest_documents d
        LEFT JOIN users u ON d.uploaded_by = u.user_id
        WHERE d.guest_id = ?
        ORDER BY d.uploaded_at DESC
    ", [$guest_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching documents: " . $e->getMessage());
}

// Get guest activity
$activities = [];
try {
    $activities = db_fetch_all("
        SELECT a.*, u.first_name, u.last_name
        FROM guest_activity a
        LEFT JOIN users u ON a.created_by = u.user_id
        WHERE a.guest_id = ?
        ORDER BY a.created_at DESC
        LIMIT 20
    ", [$guest_id]) ?: [];
} catch (Exception $e) {
    error_log("Error fetching activities: " . $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>Guest Details</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Guest Details</a>
                    <div class="navbar-nav ms-auto">
                        <span class="nav-item nav-link text-white">
                            <i class="fas fa-user"></i> 
                            <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                        </span>
                        <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                            <i class="fas fa-sign-out-alt"></i> Logout
                        </a>
                    </div>
                </div>
            </nav>
            <div class="content-wrapper">
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Guest: <?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?></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"><a href="index.php">Guests</a></li>
                    <li class="breadcrumb-item active">View</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Action Buttons -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="btn-group">
                    <a href="index.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Back to List
                    </a>
                    
                    <?php if (function_exists('has_permission') && has_permission('guests.edit')): ?>
                        <a href="edit.php?id=<?php echo $guest_id; ?>" class="btn btn-warning">
                            <i class="fas fa-edit me-1"></i> Edit Guest
                        </a>
                    <?php endif; ?>
                    
                    <?php if (function_exists('has_permission') && has_permission('guests.blacklist')): ?>
                        <?php if (!empty($guest['is_blacklisted'])): ?>
                            <a href="blacklist.php?action=remove&id=<?php echo $guest_id; ?>" class="btn btn-success">
                                <i class="fas fa-check-circle"></i> Remove from Blacklist
                            </a>
                        <?php else: ?>
                            <button type="button" class="btn btn-danger" onclick="addToBlacklist()">
                                <i class="fas fa-ban"></i> Add to Blacklist
                            </button>
                        <?php endif; ?>
                    <?php endif; ?>
                    
                    <?php if (function_exists('has_permission') && has_permission('guests.documents')): ?>
                        <a href="documents.php?id=<?php echo $guest_id; ?>" class="btn btn-info">
                            <i class="fas fa-file-alt me-1"></i> Documents
                        </a>
                    <?php endif; ?>
                    
                    <?php if (function_exists('has_permission') && has_permission('reservations.create')): ?>
                        <a href="/HMSPOS/reservations/reservations/create.php?guest_id=<?php echo $guest_id; ?>" class="btn btn-success">
                            <i class="fas fa-plus-circle me-1"></i> New Reservation
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Blacklist Alert -->
        <?php if (!empty($guest['is_blacklisted'])): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>Blacklisted Guest</strong> - This guest is on the blacklist.
                <?php if (!empty($guest['blacklist_reason'])): ?>
                    Reason: <?php echo escape_html($guest['blacklist_reason']); ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <!-- Current Stay Alert -->
        <?php if ($current_reservation): ?>
            <div class="alert alert-success">
                <i class="fas fa-info-circle me-2"></i>
                <strong>Currently In-House</strong> - 
                Room <?php echo $current_reservation['room_number'] ?? 'N/A'; ?>, 
                Check-out: <?php echo !empty($current_reservation['check_out_date']) ? format_date($current_reservation['check_out_date']) : 'N/A'; ?>
                <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $current_reservation['reservation_id'] ?? 0; ?>" class="btn btn-sm btn-success ms-2">
                    View Current Stay
                </a>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Guest Information -->
            <div class="col-md-4">
                <div class="card card-primary card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user me-1"></i>
                            Personal Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 120px;">Guest Code:</th>
                                <td><strong><?php echo escape_html($guest['guest_code'] ?? ''); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Full Name:</th>
                                <td><?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_name'] ?? '')); ?></td>
                            </tr>
                            <tr>
                                <th>Date of Birth:</th>
                                <td><?php echo !empty($guest['date_of_birth']) ? format_date($guest['date_of_birth']) : 'Not provided'; ?></td>
                            </tr>
                            <tr>
                                <th>Nationality:</th>
                                <td><?php echo !empty($guest['nationality']) ? escape_html($guest['nationality']) : 'Not provided'; ?></td>
                            </tr>
                            <tr>
                                <th>Member Since:</th>
                                <td><?php echo !empty($guest['created_at']) ? format_date($guest['created_at']) : 'N/A'; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Contact Information -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-address-card me-1"></i>
                            Contact Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 120px;">Email:</th>
                                <td>
                                    <?php if (!empty($guest['email'])): ?>
                                        <a href="mailto:<?php echo $guest['email']; ?>"><?php echo $guest['email']; ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td>
                                    <?php if (!empty($guest['phone'])): ?>
                                        <a href="tel:<?php echo $guest['phone']; ?>"><?php echo $guest['phone']; ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Address:</th>
                                <td>
                                    <?php 
                                    $address = array_filter([
                                        $guest['address'] ?? '',
                                        $guest['city'] ?? '',
                                        $guest['postal_code'] ?? '',
                                        $guest['country'] ?? ''
                                    ]);
                                    echo $address ? implode('<br>', array_map('escape_html', $address)) : 'Not provided';
                                    ?>
                                </td>
                            </tr>
                        </table>
                        
                        <div class="btn-group mt-2">
                            <button type="button" class="btn btn-sm btn-info" onclick="sendEmail()">
                                <i class="fas fa-envelope"></i> Email
                            </button>
                            <button type="button" class="btn btn-sm btn-primary" onclick="sendSMS()">
                                <i class="fas fa-sms"></i> SMS
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Identification -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-id-card me-1"></i>
                            Identification
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 120px;">ID Type:</th>
                                <td>
                                    <?php 
                                    $id_types = [
                                        'passport' => 'Passport',
                                        'national_id' => 'National ID',
                                        'drivers_license' => 'Driver\'s License',
                                        'other' => 'Other'
                                    ];
                                    echo !empty($guest['id_type']) ? ($id_types[$guest['id_type']] ?? ucfirst($guest['id_type'])) : 'Not provided';
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <th>ID Number:</th>
                                <td><?php echo !empty($guest['id_number']) ? escape_html($guest['id_number']) : 'Not provided'; ?></td>
                            </tr>
                            <tr>
                                <th>Expiry Date:</th>
                                <td>
                                    <?php if (!empty($guest['id_expiry'])): ?>
                                        <?php echo format_date($guest['id_expiry']); ?>
                                        <?php if (strtotime($guest['id_expiry']) < time()): ?>
                                            <span class="badge bg-danger">Expired</span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        Not provided
                                    <?php endif; ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Statistics and Current Stay -->
            <div class="col-md-4">
                <!-- Statistics -->
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar me-1"></i>
                            Guest Statistics
                        </h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-info">
                                        <i class="fas fa-bed"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Total Stays</span>
                                        <span class="info-box-number"><?php echo $stats['total_stays']; ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-success">
                                        <i class="fas fa-moon"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Nights</span>
                                        <span class="info-box-number"><?php echo $stats['total_nights']; ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-warning">
                                        <i class="fas fa-dollar-sign"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Total Spent</span>
                                        <span class="info-box-number"><?php echo format_currency($stats['total_spent']); ?></span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="info-box bg-light">
                                    <span class="info-box-icon bg-danger">
                                        <i class="fas fa-times-circle"></i>
                                    </span>
                                    <div class="info-box-content">
                                        <span class="info-box-text">Cancellations</span>
                                        <span class="info-box-number"><?php echo $stats['cancellations']; ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <table class="table table-sm">
                            <tr>
                                <th>Average per Stay:</th>
                                <td class="text-end"><?php echo format_currency($stats['average_spent']); ?></td>
                            </tr>
                            <tr>
                                <th>Last Visit:</th>
                                <td class="text-end"><?php echo !empty($stats['last_visit']) ? format_date($stats['last_visit']) : 'Never'; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Documents Summary -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-file-alt me-1"></i>
                            Documents (<?php echo count($documents); ?>)
                        </h3>
                        <div class="card-tools">
                            <a href="documents.php?id=<?php echo $guest_id; ?>" class="btn btn-sm btn-primary">
                                Manage
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($documents)): ?>
                            <div class="text-center text-muted py-3">
                                <p>No documents uploaded</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach (array_slice($documents, 0, 5) as $doc): ?>
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <i class="fas fa-<?php 
                                                echo ($doc['document_type'] ?? '') == 'id' ? 'id-card' : 
                                                    (($doc['document_type'] ?? '') == 'passport' ? 'passport' : 'file');
                                            ?> me-2"></i>
                                            <strong><?php echo ucfirst($doc['document_type'] ?? 'Document'); ?></strong>
                                            <?php if (!empty($doc['document_number'])): ?>
                                                <br>
                                                <small>#<?php echo escape_html($doc['document_number']); ?></small>
                                            <?php endif; ?>
                                        </div>
                                        <small class="text-muted">
                                            <?php echo !empty($doc['uploaded_at']) ? time_ago($doc['uploaded_at']) : ''; ?>
                                        </small>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Recent Activity -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history me-1"></i>
                            Recent Activity
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($activities)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-history fa-3x mb-3"></i>
                                <p>No activity recorded</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($activities as $activity): ?>
                                <div class="list-group-item">
                                    <div class="d-flex w-100 justify-content-between">
                                        <h6 class="mb-1">
                                            <i class="fas <?php 
                                                echo ($activity['activity_type'] ?? '') == 'created' ? 'fa-plus-circle text-success' : 
                                                    (($activity['activity_type'] ?? '') == 'updated' ? 'fa-edit text-info' : 
                                                    (($activity['activity_type'] ?? '') == 'checkin' ? 'fa-sign-in-alt text-primary' : 
                                                    (($activity['activity_type'] ?? '') == 'checkout' ? 'fa-sign-out-alt text-warning' : 
                                                    (($activity['activity_type'] ?? '') == 'blacklist' ? 'fa-ban text-danger' : 'fa-info-circle'))));
                                            ?> me-2"></i>
                                            <?php echo escape_html($activity['description'] ?? ''); ?>
                                        </h6>
                                        <small class="text-muted"><?php echo time_ago($activity['created_at'] ?? date('Y-m-d H:i:s')); ?></small>
                                    </div>
                                    <small class="text-muted">by <?php echo escape_html(($activity['first_name'] ?? '') . ' ' . ($activity['last_name'] ?? '')); ?></small>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Reservations -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-calendar-alt me-1"></i>
                            Reservation History
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/guests/history/index.php?guest_id=<?php echo $guest_id; ?>" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($recent_reservations)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-calendar-times fa-3x mb-3"></i>
                                <p>No reservation history</p>
                                <a href="/HMSPOS/reservations/reservations/create.php?guest_id=<?php echo $guest_id; ?>" class="btn btn-primary">
                                    Create First Reservation
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Booking #</th>
                                            <th>Dates</th>
                                            <th>Room Type</th>
                                            <th>Room</th>
                                            <th>Nights</th>
                                            <th class="text-end">Total</th>
                                            <th>Status</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_reservations as $res): ?>
                                        <tr>
                                            <td>
                                                <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $res['reservation_id'] ?? 0; ?>">
                                                    <?php echo escape_html($res['booking_code'] ?? ''); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php echo !empty($res['check_in_date']) ? format_date($res['check_in_date']) : ''; ?><br>
                                                <small>to <?php echo !empty($res['check_out_date']) ? format_date($res['check_out_date']) : ''; ?></small>
                                            </td>
                                            <td><?php echo escape_html($res['type_name'] ?? ''); ?></td>
                                            <td>
                                                <?php if (!empty($res['room_number'])): ?>
                                                    Room <?php echo $res['room_number']; ?>
                                                <?php else: ?>
                                                    <span class="text-muted">Not assigned</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center"><?php echo $res['nights'] ?? 1; ?></td>
                                            <td class="text-end"><?php echo format_currency($res['total_amount'] ?? 0); ?></td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    echo ($res['booking_status'] ?? '') == 'confirmed' ? 'success' : 
                                                        (($res['booking_status'] ?? '') == 'checked_in' ? 'info' : 
                                                        (($res['booking_status'] ?? '') == 'checked_out' ? 'secondary' : 
                                                        (($res['booking_status'] ?? '') == 'cancelled' ? 'danger' : 'warning')));
                                                ?>">
                                                    <?php echo ucfirst($res['booking_status'] ?? 'pending'); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $res['reservation_id'] ?? 0; ?>" 
                                                   class="btn btn-sm btn-info">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Blacklist Modal -->
<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" value="<?php echo $guest_id; ?>">
                
                <div class="modal-body">
                    <p>Are you sure you want to add <strong><?php echo escape_html(($guest['first_name'] ?? '') . ' ' . ($guest['last_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>

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

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

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

<style>
.info-box {
    min-height: 70px;
    margin-bottom: 10px;
}
.info-box .info-box-icon {
    width: 50px;
    height: 50px;
    line-height: 50px;
    font-size: 1.5rem;
}
.info-box .info-box-content {
    margin-left: 60px;
}
.me-1 { margin-right: 0.25rem; }
.me-2 { margin-right: 0.5rem; }
.ms-2 { margin-left: 0.5rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 1rem; }
.mt-2 { margin-top: 0.5rem; }
.mt-3 { margin-top: 1rem; }
.text-end { text-align: right; }
.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-info { background-color: #17a2b8; 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>';
}
?>