<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guest History - 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/history/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/history/ -> /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('has_permission')) {
    function has_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define booking statuses if not defined
if (!defined('BOOKING_STATUSES')) {
    define('BOOKING_STATUSES', serialize([
        'pending' => 'Pending',
        'confirmed' => 'Confirmed',
        'checked_in' => 'Checked In',
        'checked_out' => 'Checked Out',
        'cancelled' => 'Cancelled',
        'no_show' => 'No Show'
    ]));
}

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

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

// 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'] ?? '';
$guest_id = isset($_GET['guest_id']) ? (int)$_GET['guest_id'] : null;
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$status = $_GET['status'] ?? '';
$sort = $_GET['sort'] ?? 'check_in_date';
$order = $_GET['order'] ?? 'DESC';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = defined('ITEMS_PER_PAGE') ? ITEMS_PER_PAGE * 2 : 50; // Show more items per page for history

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

if ($guest_id) {
    $where .= " AND r.guest_id = ?";
    $params[] = $guest_id;
}

if (!empty($search)) {
    $where .= " 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;
}

if (!empty($date_from)) {
    $where .= " AND r.check_in_date >= ?";
    $params[] = $date_from;
}

if (!empty($date_to)) {
    $where .= " AND r.check_out_date <= ?";
    $params[] = $date_to;
}

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

// Validate sort column
$allowed_sort = ['check_in_date', 'check_out_date', 'created_at', 'total_amount', 'booking_status'];
if (!in_array($sort, $allowed_sort)) {
    $sort = 'check_in_date';
}

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

// Get reservation history with guest details
$history = [];
try {
    $sql = "
        SELECT 
            r.*,
            g.guest_id, g.first_name, g.last_name, g.email, g.phone,
            g.nationality,
            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
        LEFT JOIN guests g ON r.guest_id = g.guest_id
        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 $where
        ORDER BY $sort $order
    ";
    
    // Get paginated data
    $offset = ($page - 1) * $per_page;
    $data_sql = $sql . " LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
    $history = db_fetch_all($data_sql, $params) ?: [];
} catch (Exception $e) {
    error_log("Error fetching history: " . $e->getMessage());
}

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

// Get summary statistics
$stats = [
    'total_reservations' => $total,
    'total_revenue' => 0,
    'avg_nights' => 0,
    'cancelled' => 0,
    'unique_guests' => 0
];

try {
    $stats['total_revenue'] = (float)db_fetch_value("SELECT COALESCE(SUM(total_amount), 0) FROM reservations r WHERE $where", $params) ?: 0;
    $stats['avg_nights'] = (float)db_fetch_value("SELECT COALESCE(AVG(DATEDIFF(check_out_date, check_in_date)), 0) FROM reservations r WHERE $where", $params) ?: 0;
    $stats['cancelled'] = (int)db_fetch_value("SELECT COUNT(*) FROM reservations r WHERE $where AND booking_status = 'cancelled'", $params) ?: 0;
    $stats['unique_guests'] = (int)db_fetch_value("SELECT COUNT(DISTINCT guest_id) FROM reservations r WHERE $where", $params) ?: 0;
} catch (Exception $e) {
    error_log("Error calculating stats: " . $e->getMessage());
}

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

// Get status options
$statuses = [
    'pending' => 'Pending',
    'confirmed' => 'Confirmed',
    'checked_in' => 'Checked In',
    'checked_out' => 'Checked Out',
    'cancelled' => 'Cancelled',
    'no_show' => 'No Show'
];

// 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 History</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 History</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 History</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">History</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Selected Guest Info -->
        <?php if ($selected_guest): ?>
        <div class="row mb-3">
            <div class="col-12">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user me-1"></i>
                            Viewing History for: <?php echo escape_html(($selected_guest['first_name'] ?? '') . ' ' . ($selected_guest['last_name'] ?? '')); ?>
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/guests/guests/view.php?id=<?php echo $guest_id; ?>" class="btn btn-sm btn-primary">
                                <i class="fas fa-external-link-alt"></i> View Guest Profile
                            </a>
                            <a href="?" class="btn btn-sm btn-secondary">
                                <i class="fas fa-times"></i> Clear Filter
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo number_format($stats['total_reservations']); ?></h3>
                        <p>Total Reservations</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-alt"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['total_revenue']); ?></h3>
                        <p>Total Revenue</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo round($stats['avg_nights'], 1); ?></h3>
                        <p>Avg. Nights/Stay</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-moon"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo number_format($stats['unique_guests']); ?></h3>
                        <p>Unique Guests</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-users"></i>
                    </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-2">
                        <input type="text" class="form-control" name="search" placeholder="Search guest or booking..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <input type="date" class="form-control" name="date_from" placeholder="From" 
                               value="<?php echo $date_from; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <input type="date" class="form-control" name="date_to" placeholder="To" 
                               value="<?php echo $date_to; ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">All Status</option>
                            <?php foreach ($statuses as $value => $label): ?>
                                <option value="<?php echo $value; ?>" <?php echo $status == $value ? 'selected' : ''; ?>>
                                    <?php echo $label; ?>
                                </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>
                    
                    <div class="col-12 text-end">
                        <button type="button" class="btn btn-success" onclick="exportHistory()">
                            <i class="fas fa-download"></i> Export
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- History Table -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">
                    <i class="fas fa-history me-1"></i>
                    Reservation History (<?php echo $total; ?> records)
                </h3>
            </div>
            
            <div class="card-body p-0">
                <?php if (empty($history)): ?>
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-history fa-4x mb-3"></i>
                        <h5>No reservation history found</h5>
                        <p>Try adjusting your filters</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Guest</th>
                                    <th>Booking #</th>
                                    <th>
                                        <a href="?sort=check_in_date&order=<?php echo $sort === 'check_in_date' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&guest_id=<?php echo $guest_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>" class="text-dark">
                                            Check-in
                                            <?php if ($sort === 'check_in_date'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>Check-out</th>
                                    <th>Nights</th>
                                    <th>Room Type</th>
                                    <th>Room</th>
                                    <th class="text-end">
                                        <a href="?sort=total_amount&order=<?php echo $sort === 'total_amount' && $order === 'ASC' ? 'DESC' : 'ASC'; ?>&search=<?php echo urlencode($search); ?>&guest_id=<?php echo $guest_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>" class="text-dark">
                                            Amount
                                            <?php if ($sort === 'total_amount'): ?>
                                                <i class="fas fa-sort-<?php echo $order === 'ASC' ? 'up' : 'down'; ?>"></i>
                                            <?php endif; ?>
                                        </a>
                                    </th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($history as $record): ?>
                                <tr>
                                    <td>
                                        <a href="/HMSPOS/guests/guests/view.php?id=<?php echo $record['guest_id'] ?? 0; ?>">
                                            <?php echo escape_html(($record['first_name'] ?? '') . ' ' . ($record['last_name'] ?? '')); ?>
                                        </a>
                                        <br>
                                        <small class="text-muted"><?php echo $record['nationality'] ?? ''; ?></small>
                                    </td>
                                    <td>
                                        <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $record['reservation_id'] ?? 0; ?>">
                                            <?php echo escape_html($record['booking_code'] ?? ''); ?>
                                        </a>
                                    </td>
                                    <td><?php echo !empty($record['check_in_date']) ? format_date($record['check_in_date']) : ''; ?></td>
                                    <td><?php echo !empty($record['check_out_date']) ? format_date($record['check_out_date']) : ''; ?></td>
                                    <td class="text-center"><?php echo $record['nights'] ?? 1; ?></td>
                                    <td><?php echo escape_html($record['type_name'] ?? ''); ?></td>
                                    <td>
                                        <?php if (!empty($record['room_number'])): ?>
                                            Room <?php echo $record['room_number']; ?>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end"><?php echo format_currency($record['total_amount'] ?? 0); ?></td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo ($record['booking_status'] ?? '') == 'confirmed' ? 'success' : 
                                                (($record['booking_status'] ?? '') == 'checked_in' ? 'info' : 
                                                (($record['booking_status'] ?? '') == 'checked_out' ? 'secondary' : 
                                                (($record['booking_status'] ?? '') == 'cancelled' ? 'danger' : 'warning')));
                                        ?>">
                                            <?php echo $statuses[$record['booking_status'] ?? ''] ?? ucfirst($record['booking_status'] ?? 'unknown'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <a href="/HMSPOS/reservations/reservations/view.php?id=<?php echo $record['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>

            <!-- 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; ?> records
                        </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); ?>&guest_id=<?php echo $guest_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>&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); ?>&guest_id=<?php echo $guest_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>&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); ?>&guest_id=<?php echo $guest_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>&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); ?>&guest_id=<?php echo $guest_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>&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); ?>&guest_id=<?php echo $guest_id; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&status=<?php echo $status; ?>&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>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.3.0/dist/chart.umd.min.js"></script>

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

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