<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guests Dashboard - FIXED PATHS
 * Developer: JOACHIM'S INNOTECH
 */

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

// Calculate the correct base path
$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')) {
    $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';
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        // Detect protocol
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        
        // Get host
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        
        // Get base path (remove public from URL if present)
        $base = '/HMSPOS';
        
        return $protocol . $host . $base . '/' . ltrim($path, '/');
    }
}

// Define time_ago function if it doesn't exist
if (!function_exists('time_ago')) {
    function time_ago($datetime) {
        if (empty($datetime)) return 'Never';
        
        $time = strtotime($datetime);
        $now = time();
        $diff = $now - $time;
        
        if ($diff < 60) {
            return 'Just now';
        } 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);
        }
    }
}

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

// Require authentication and permission
require_auth();

// Check if require_permission function exists
if (function_exists('require_permission')) {
    require_permission('dashboard.guests');
}

// Set page title
$page_title = 'Guests Dashboard';

// Get current user
$current_user = function_exists('current_user') ? current_user() : ['username' => 'Guest'];

// Helper function for database queries with error handling
function safe_db_query($sql, $params = [], $default = 0) {
    try {
        if (function_exists('db_fetch_value')) {
            return db_fetch_value($sql, $params) ?: $default;
        } elseif (function_exists('db_fetch_all')) {
            $result = db_fetch_all($sql, $params);
            return $result ?: $default;
        } else {
            // Manual query
            global $db;
            if (isset($db) && $db instanceof mysqli) {
                $stmt = $db->prepare($sql);
                if ($stmt) {
                    if (!empty($params)) {
                        $types = str_repeat('s', count($params));
                        $stmt->bind_param($types, ...$params);
                    }
                    $stmt->execute();
                    $result = $stmt->get_result();
                    $value = $result->fetch_row()[0] ?? $default;
                    $stmt->close();
                    return $value;
                }
            }
        }
    } catch (Exception $e) {
        error_log("Database query error: " . $e->getMessage());
    }
    return $default;
}

// Get guest statistics with error handling
$stats = [
    'total_guests' => safe_db_query("SELECT COUNT(*) FROM guests"),
    'active_guests' => safe_db_query("
        SELECT COUNT(DISTINCT guest_id) FROM reservations 
        WHERE booking_status IN ('confirmed', 'checked_in')
        AND check_in_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    "),
    'in_house' => safe_db_query("
        SELECT COUNT(DISTINCT guest_id) FROM reservations 
        WHERE booking_status = 'checked_in'
    "),
    'blacklisted' => safe_db_query("SELECT COUNT(*) FROM guests WHERE is_blacklisted = 1"),
    'new_this_month' => safe_db_query("
        SELECT COUNT(*) FROM guests 
        WHERE MONTH(created_at) = MONTH(CURDATE())
        AND YEAR(created_at) = YEAR(CURDATE())
    "),
    'returning' => safe_db_query("
        SELECT COUNT(*) FROM (
            SELECT guest_id FROM reservations 
            GROUP BY guest_id 
            HAVING COUNT(*) > 1
        ) as returning
    "),
    'avg_stay' => safe_db_query("
        SELECT COALESCE(AVG(nights), 0) FROM reservations 
        WHERE booking_status IN ('checked_out', 'checked_in')
        AND check_out_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ") ?: 0,
    'avg_spend' => safe_db_query("
        SELECT COALESCE(AVG(total_amount), 0) FROM reservations 
        WHERE booking_status IN ('checked_out', 'checked_in')
        AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    ") ?: 0
];

// Get recent guests
$recent_guests = [];
try {
    if (function_exists('db_fetch_all')) {
        $recent_guests = db_fetch_all("
            SELECT g.*, 
                   COUNT(r.reservation_id) as booking_count,
                   MAX(r.check_in_date) as last_visit
            FROM guests g
            LEFT JOIN reservations r ON g.guest_id = r.guest_id
            GROUP BY g.guest_id
            ORDER BY g.created_at DESC
            LIMIT 15
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error fetching recent guests: " . $e->getMessage());
}

// Get top guests by spending
$top_guests = [];
try {
    if (function_exists('db_fetch_all')) {
        $top_guests = db_fetch_all("
            SELECT 
                g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                COUNT(r.reservation_id) as booking_count,
                COALESCE(SUM(r.total_amount), 0) as total_spent,
                AVG(r.total_amount) as avg_spent,
                MAX(r.check_in_date) as last_visit
            FROM guests g
            JOIN reservations r ON g.guest_id = r.guest_id
            WHERE r.booking_status != 'cancelled'
            GROUP BY g.guest_id
            ORDER BY total_spent DESC
            LIMIT 15
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error fetching top guests: " . $e->getMessage());
}

// Get guest nationality breakdown
$nationalities = [];
try {
    if (function_exists('db_fetch_all')) {
        $nationalities = db_fetch_all("
            SELECT 
                COALESCE(nationality, 'Unknown') as nationality,
                COUNT(*) as count
            FROM guests
            GROUP BY nationality
            ORDER BY count DESC
            LIMIT 10
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error fetching nationalities: " . $e->getMessage());
}

// Get monthly guest acquisition
$monthly_acquisition = ['labels' => [], 'data' => []];
for ($i = 5; $i >= 0; $i--) {
    $month = date('Y-m', strtotime("-$i months"));
    $month_name = date('M Y', strtotime("-$i months"));
    
    $count = safe_db_query("
        SELECT COUNT(*) FROM guests 
        WHERE DATE_FORMAT(created_at, '%Y-%m') = ?
    ", [$month]);
    
    $monthly_acquisition['labels'][] = $month_name;
    $monthly_acquisition['data'][] = (int)$count;
}

// Get guest segmentation by visit frequency
$segmentation = [
    'first_time' => safe_db_query("
        SELECT COUNT(*) FROM guests g
        WHERE (SELECT COUNT(*) FROM reservations r WHERE r.guest_id = g.guest_id) = 1
    "),
    'returning' => safe_db_query("
        SELECT COUNT(*) FROM guests g
        WHERE (SELECT COUNT(*) FROM reservations r WHERE r.guest_id = g.guest_id) BETWEEN 2 AND 3
    "),
    'frequent' => safe_db_query("
        SELECT COUNT(*) FROM guests g
        WHERE (SELECT COUNT(*) FROM reservations r WHERE r.guest_id = g.guest_id) >= 4
    ")
];

// Get upcoming birthdays (next 30 days)
$birthdays = [];
try {
    if (function_exists('db_fetch_all')) {
        $birthdays = db_fetch_all("
            SELECT * FROM guests 
            WHERE date_of_birth IS NOT NULL
            AND DATE_ADD(date_of_birth, INTERVAL YEAR(CURDATE()) - YEAR(date_of_birth) YEAR) 
                BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
            ORDER BY MONTH(date_of_birth), DAY(date_of_birth)
            LIMIT 10
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error fetching birthdays: " . $e->getMessage());
}

// Get guests with pending folio balances
$guests_with_balance = [];
try {
    if (function_exists('db_fetch_all')) {
        $guests_with_balance = db_fetch_all("
            SELECT 
                g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                r.reservation_id, r.booking_code,
                r.total_amount, r.paid_amount,
                (r.total_amount - r.paid_amount) as balance,
                r.check_in_date, r.check_out_date,
                rm.room_number
            FROM guests g
            JOIN reservations r ON g.guest_id = r.guest_id
            LEFT JOIN rooms rm ON r.room_id = rm.room_id
            WHERE r.booking_status IN ('checked_in', 'confirmed')
            AND r.total_amount > r.paid_amount
            ORDER BY balance DESC
            LIMIT 15
        ") ?: [];
    }
} catch (Exception $e) {
    error_log("Error fetching guests with balance: " . $e->getMessage());
}

// Include header
$header_path = $base_path . '/views/partials/header.php';
if (file_exists($header_path)) {
    require_once $header_path;
} else {
    // 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 Dashboard</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <style>
            body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
            .content-wrapper { padding: 20px; }
            .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
            .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
            .small-box { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; position: relative; overflow: hidden; color: #fff; padding: 15px; }
            .small-box .inner { padding: 10px; }
            .small-box h3 { font-size: 2rem; font-weight: 700; margin: 0 0 10px 0; }
            .small-box p { font-size: 1rem; margin: 0; }
            .bg-info { background-color: #17a2b8 !important; }
            .bg-success { background-color: #28a745 !important; }
            .bg-warning { background-color: #ffc107 !important; color: #000; }
            .bg-danger { background-color: #dc3545 !important; }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <div class="container-fluid">
                    <a class="navbar-brand" href="#">Guests Dashboard</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 Dashboard</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('guests/dashboard.php'); ?>">Guests</a></li>
                    <li class="breadcrumb-item active">Dashboard</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Quick Actions Row -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card card-outline card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <a href="<?php echo base_url('guests/create.php'); ?>" class="btn btn-primary mr-2 mb-2">
                            <i class="fas fa-user-plus mr-1"></i> New Guest
                        </a>
                        <a href="<?php echo base_url('guests/index.php'); ?>" class="btn btn-info mr-2 mb-2">
                            <i class="fas fa-list mr-1"></i> Guest List
                        </a>
                        <a href="<?php echo base_url('guests/blacklist.php'); ?>" class="btn btn-danger mr-2 mb-2">
                            <i class="fas fa-ban mr-1"></i> Blacklist
                        </a>
                        <a href="<?php echo base_url('reports/guest-analytics.php'); ?>" class="btn btn-success mr-2 mb-2">
                            <i class="fas fa-chart-pie mr-1"></i> Analytics
                        </a>
                        <button type="button" class="btn btn-warning mb-2" onclick="searchGuest()">
                            <i class="fas fa-search mr-1"></i> Quick Search
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo number_format($stats['total_guests']); ?></h3>
                        <p>Total Guests</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-users"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 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-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo number_format($stats['new_this_month']); ?></h3>
                        <p>New This Month</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-user-plus"></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['blacklisted']); ?></h3>
                        <p>Blacklisted</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-ban"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Second Row Stats -->
        <div class="row">
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-info"><i class="fas fa-chart-line"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Returning Guests</span>
                        <span class="info-box-number"><?php echo number_format($stats['returning']); ?></span>
                        <span class="info-box-percent">
                            <?php 
                            $return_rate = $stats['total_guests'] > 0 
                                ? round(($stats['returning'] / $stats['total_guests']) * 100, 1) 
                                : 0;
                            echo $return_rate; ?>%
                        </span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-success"><i class="fas fa-clock"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Avg. Stay</span>
                        <span class="info-box-number"><?php echo round($stats['avg_stay'], 1); ?> nights</span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <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">Avg. Spend</span>
                        <span class="info-box-number"><?php echo format_currency($stats['avg_spend']); ?></span>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="info-box">
                    <span class="info-box-icon bg-danger"><i class="fas fa-birthday-cake"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Birthdays (30 days)</span>
                        <span class="info-box-number"><?php echo count($birthdays); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Charts Row -->
        <div class="row">
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-pie mr-1"></i>
                            Guest Segmentation
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="segmentationChart" style="height: 250px;"></canvas>
                        
                        <div class="mt-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span><i class="fas fa-circle text-primary mr-2"></i> First Time</span>
                                <span class="badge badge-primary"><?php echo number_format($segmentation['first_time']); ?></span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span><i class="fas fa-circle text-success mr-2"></i> Returning (2-3 visits)</span>
                                <span class="badge badge-success"><?php echo number_format($segmentation['returning']); ?></span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span><i class="fas fa-circle text-warning mr-2"></i> Frequent (4+ visits)</span>
                                <span class="badge badge-warning"><?php echo number_format($segmentation['frequent']); ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-globe mr-1"></i>
                            Top Nationalities
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($nationalities)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-globe fa-3x mb-3"></i>
                                <p>No nationality data</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Nationality</th>
                                            <th class="text-right">Count</th>
                                            <th class="text-right">%</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $total = array_sum(array_column($nationalities, 'count'));
                                        foreach ($nationalities as $nation): 
                                        ?>
                                        <tr>
                                            <td><?php echo escape_html($nation['nationality']); ?></td>
                                            <td class="text-right"><?php echo number_format($nation['count']); ?></td>
                                            <td class="text-right">
                                                <?php echo round(($nation['count'] / $total) * 100, 1); ?>%
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-line mr-1"></i>
                            New Guests (Last 6 Months)
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="acquisitionChart" style="height: 250px;"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Top Guests by Spending -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-crown mr-1"></i>
                            Top Guests by Spending
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($top_guests)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-users fa-3x mb-3"></i>
                                <p>No guest data available</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th>Bookings</th>
                                            <th class="text-right">Total Spent</th>
                                            <th class="text-right">Avg. Spend</th>
                                            <th>Last Visit</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($top_guests as $guest): ?>
                                        <tr>
                                            <td>
                                                <a href="<?php echo base_url('guests/view.php?id=' . $guest['guest_id']); ?>">
                                                    <?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?>
                                                </a>
                                                <br>
                                                <small class="text-muted"><?php echo escape_html($guest['email']); ?></small>
                                            </td>
                                            <td class="text-center"><?php echo $guest['booking_count']; ?></td>
                                            <td class="text-right"><?php echo format_currency($guest['total_spent']); ?></td>
                                            <td class="text-right"><?php echo format_currency($guest['avg_spent']); ?></td>
                                            <td>
                                                <?php echo !empty($guest['last_visit']) ? format_date($guest['last_visit']) : 'Never'; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Guests with Balance -->
            <div class="col-md-6">
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-dollar-sign mr-1"></i>
                            Guests with Outstanding Balance
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('billing/debtor/index.php'); ?>" class="btn btn-sm btn-warning">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($guests_with_balance)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                                <p>No outstanding balances</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th>Room</th>
                                            <th>Booking</th>
                                            <th class="text-right">Balance</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($guests_with_balance as $guest): ?>
                                        <tr>
                                            <td>
                                                <a href="<?php echo base_url('guests/view.php?id=' . $guest['guest_id']); ?>">
                                                    <?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php if (!empty($guest['room_number'])): ?>
                                                    <span class="badge badge-info"><?php echo $guest['room_number']; ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="<?php echo base_url('reservations/view.php?id=' . $guest['reservation_id']); ?>">
                                                    <?php echo $guest['booking_code']; ?>
                                                </a>
                                            </td>
                                            <td class="text-right">
                                                <span class="badge badge-danger"><?php echo format_currency($guest['balance']); ?></span>
                                            </td>
                                            <td>
                                                <a href="<?php echo base_url('billing/payments/add.php?reservation_id=' . $guest['reservation_id']); ?>" 
                                                   class="btn btn-sm btn-success">
                                                    <i class="fas fa-dollar-sign"></i>
                                                </a>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Recent Guests -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user-plus mr-1"></i>
                            Recent Guests
                        </h3>
                        <div class="card-tools">
                            <a href="<?php echo base_url('guests/index.php'); ?>" class="btn btn-sm btn-primary">
                                View All
                            </a>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($recent_guests)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-users fa-3x mb-3"></i>
                                <p>No guests found</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($recent_guests as $guest): ?>
                                <div class="list-group-item">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <a href="<?php echo base_url('guests/view.php?id=' . $guest['guest_id']); ?>">
                                                <strong><?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?></strong>
                                            </a>
                                            <br>
                                            <small class="text-muted">
                                                <i class="fas fa-envelope mr-1"></i> <?php echo escape_html($guest['email'] ?: 'No email'); ?>
                                            </small>
                                            <br>
                                            <small class="text-muted">
                                                <i class="fas fa-phone mr-1"></i> <?php echo escape_html($guest['phone'] ?: 'No phone'); ?>
                                            </small>
                                        </div>
                                        <div class="text-right">
                                            <span class="badge badge-info"><?php echo $guest['booking_count']; ?> bookings</span>
                                            <br>
                                            <?php if (!empty($guest['is_blacklisted'])): ?>
                                                <span class="badge badge-danger">Blacklisted</span>
                                            <?php endif; ?>
                                            <br>
                                            <small class="text-muted">
                                                <?php echo time_ago($guest['created_at']); ?>
                                            </small>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Upcoming Birthdays -->
            <div class="col-md-6">
                <div class="card card-pink">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-birthday-cake mr-1"></i>
                            Upcoming Birthdays (Next 30 Days)
                        </h3>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($birthdays)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-birthday-cake fa-3x mb-3"></i>
                                <p>No upcoming birthdays</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Guest</th>
                                            <th>Birthday</th>
                                            <th>Age</th>
                                            <th>Days Until</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php 
                                        $today = new DateTime();
                                        foreach ($birthdays as $guest):
                                            if (empty($guest['date_of_birth'])) continue;
                                            
                                            $birthday = new DateTime($guest['date_of_birth']);
                                            $next_birthday = clone $birthday;
                                            $next_birthday->setDate((int)$today->format('Y'), (int)$birthday->format('m'), (int)$birthday->format('d'));
                                            
                                            if ($next_birthday < $today) {
                                                $next_birthday->modify('+1 year');
                                            }
                                            
                                            $days_until = $today->diff($next_birthday)->days;
                                            $age = $next_birthday->diff($birthday)->y;
                                        ?>
                                        <tr>
                                            <td>
                                                <a href="<?php echo base_url('guests/view.php?id=' . $guest['guest_id']); ?>">
                                                    <?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?>
                                                </a>
                                            </td>
                                            <td><?php echo format_date($guest['date_of_birth'], 'M d'); ?></td>
                                            <td><?php echo $age; ?></td>
                                            <td>
                                                <?php if ($days_until == 0): ?>
                                                    <span class="badge badge-success">Today!</span>
                                                <?php else: ?>
                                                    <?php echo $days_until; ?> days
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-pink" onclick="sendBirthdayWish(<?php echo $guest['guest_id']; ?>)">
                                                    <i class="fas fa-gift"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Quick Search Modal -->
<div class="modal fade" id="searchGuestModal" tabindex="-1">
    <div class="modal-dialog">
        <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="form-group">
                    <input type="text" class="form-control form-control-lg" id="guestSearchInput" 
                           placeholder="Type name, email, or phone..." autocomplete="off">
                </div>
                <div id="guestSearchResults" style="max-height: 400px; overflow-y: auto;"></div>
            </div>
        </div>
    </div>
</div>

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

<script>
$(document).ready(function() {
    // Segmentation Chart
    const segCtx = document.getElementById('segmentationChart')?.getContext('2d');
    if (segCtx) {
        new Chart(segCtx, {
            type: 'doughnut',
            data: {
                labels: ['First Time', 'Returning (2-3)', 'Frequent (4+)'],
                datasets: [{
                    data: [
                        <?php echo $segmentation['first_time']; ?>,
                        <?php echo $segmentation['returning']; ?>,
                        <?php echo $segmentation['frequent']; ?>
                    ],
                    backgroundColor: ['#007bff', '#28a745', '#ffc107'],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }
    
    // Acquisition Chart
    const acqCtx = document.getElementById('acquisitionChart')?.getContext('2d');
    if (acqCtx) {
        new Chart(acqCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($monthly_acquisition['labels']); ?>,
                datasets: [{
                    label: 'New Guests',
                    data: <?php echo json_encode($monthly_acquisition['data']); ?>,
                    backgroundColor: '#17a2b8',
                    borderColor: '#138496',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }
    
    // Guest search
    let searchTimeout;
    $('#guestSearchInput').on('input', function() {
        clearTimeout(searchTimeout);
        const query = $(this).val();
        
        if (query.length < 2) {
            $('#guestSearchResults').html('<div class="text-center text-muted py-3">Type at least 2 characters</div>');
            return;
        }
        
        searchTimeout = setTimeout(function() {
            $.get('<?php echo base_url('api/search-guests.php'); ?>', { q: query }, function(response) {
                if (response && response.status === 'success') {
                    displaySearchResults(response.data || []);
                } else {
                    $('#guestSearchResults').html('<div class="alert alert-danger">Search failed</div>');
                }
            }).fail(function() {
                $('#guestSearchResults').html('<div class="alert alert-danger">Search request failed</div>');
            });
        }, 300);
    });
});

function searchGuest() {
    $('#searchGuestModal').modal('show');
    setTimeout(function() {
        $('#guestSearchInput').focus();
    }, 500);
}

function displaySearchResults(guests) {
    if (!guests || guests.length === 0) {
        $('#guestSearchResults').html('<div class="text-center text-muted py-3">No guests found</div>');
        return;
    }
    
    let html = '<div class="list-group">';
    guests.forEach(function(guest) {
        html += `
            <a href="<?php echo base_url('/guests/view.php?id='); ?>${guest.guest_id}" 
               class="list-group-item list-group-item-action" onclick="$('#searchGuestModal').modal('hide')">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <strong>${guest.first_name || ''} ${guest.last_name || ''}</strong>
                        <br>
                        <small class="text-muted">${guest.email || 'No email'}</small>
                        <br>
                        <small class="text-muted">${guest.phone || 'No phone'}</small>
                    </div>
                    ${guest.is_blacklisted ? '<span class="badge badge-danger">Blacklisted</span>' : ''}
                </div>
            </a>
        `;
    });
    html += '</div>';
    
    $('#guestSearchResults').html(html);
}

function sendBirthdayWish(guestId) {
    if (confirm('Send birthday greeting to this guest?')) {
        $.post('<?php echo base_url('api/send-birthday-wish.php'); ?>', {
            guest_id: guestId,
            csrf_token: '<?php echo function_exists('csrf_token') ? csrf_token() : ''; ?>'
        }, function(response) {
            if (response && response.status === 'success') {
                alert('Birthday wish sent successfully');
            } else {
                alert('Failed to send birthday wish');
            }
        }).fail(function() {
            alert('Failed to send birthday wish');
        });
    }
}
</script>

<style>
.card-pink {
    border-top-color: #e83e8c;
}
.card-pink .card-header {
    background-color: #e83e8c;
    color: white;
}
.btn-pink {
    background-color: #e83e8c;
    border-color: #e83e8c;
    color: white;
}
.btn-pink:hover {
    background-color: #d6327c;
    border-color: #d6327c;
    color: white;
}
.info-box {
    display: flex;
    align-items: center;
    background: #fff;
    border-radius: 0.5rem;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    margin-bottom: 20px;
    padding: 15px;
}
.info-box-icon {
    width: 70px;
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 0.5rem;
    margin-right: 15px;
    font-size: 2rem;
    color: #fff;
}
.info-box-content {
    flex: 1;
}
.info-box-text {
    font-size: 0.9rem;
    color: #6c757d;
}
.info-box-number {
    font-size: 1.5rem;
    font-weight: 600;
}
.info-box-percent {
    font-size: 0.9rem;
    color: #28a745;
}
</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>';
}
?>