<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * View Guest History Details
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 3) . '/config/config.php';
require_once dirname(__DIR__, 3) . '/config/constants.php';
require_once dirname(__DIR__, 3) . '/config/database.php';
require_once dirname(__DIR__, 3) . '/config/helpers.php';
require_once dirname(__DIR__, 3) . '/config/auth.php';
require_once dirname(__DIR__, 3) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('guests.view');

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

// Get current user
$current_user = current_user();

// Get guest ID from URL
$guest_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$guest_id) {
    set_flash_message('danger', 'Invalid guest ID');
    redirect('index.php');
}

// Get guest information
$guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$guest_id]);

if (!$guest) {
    set_flash_message('danger', 'Guest not found');
    redirect('index.php');
}

// Get complete reservation history for this guest
$reservations = db_fetch_all("
    SELECT 
        r.*,
        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,
        u.first_name as created_by_first, u.last_name as created_by_last
    FROM reservations r
    JOIN room_types rt ON r.room_type_id = rt.room_type_id
    LEFT JOIN rooms rm ON r.room_id = rm.room_id
    LEFT JOIN users u ON r.created_by = u.user_id
    WHERE r.guest_id = ?
    ORDER BY r.check_in_date DESC
", [$guest_id]);

// Get guest activity timeline
$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
", [$guest_id]);

// Calculate statistics
$stats = [
    'total_stays' => count($reservations),
    'total_nights' => array_sum(array_column($reservations, 'nights')),
    'total_spent' => array_sum(array_column($reservations, 'total_amount')),
    'avg_spent' => count($reservations) > 0 ? array_sum(array_column($reservations, 'total_amount')) / count($reservations) : 0,
    'cancelled' => count(array_filter($reservations, function($r) { return $r['booking_status'] == 'cancelled'; })),
    'completed' => count(array_filter($reservations, function($r) { return $r['booking_status'] == 'checked_out'; })),
    'first_visit' => $reservations ? min(array_column($reservations, 'check_in_date')) : null,
    'last_visit' => $reservations ? max(array_column($reservations, 'check_in_date')) : null
];

// Get spending by year
$spending_by_year = [];
foreach ($reservations as $res) {
    $year = date('Y', strtotime($res['check_in_date']));
    if (!isset($spending_by_year[$year])) {
        $spending_by_year[$year] = 0;
    }
    $spending_by_year[$year] += $res['total_amount'];
}

// Get favorite room types
$room_type_counts = [];
foreach ($reservations as $res) {
    $type = $res['type_name'];
    $room_type_counts[$type] = ($room_type_counts[$type] ?? 0) + 1;
}
arsort($room_type_counts);

// Include header
require_once dirname(__DIR__, 3) . '/views/partials/header.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: <?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="<?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"><a href="../guests/index.php">Guests</a></li>
                    <li class="breadcrumb-item"><a href="../guests/view.php?id=<?php echo $guest_id; ?>">View</a></li>
                    <li class="breadcrumb-item"><a href="index.php?guest_id=<?php echo $guest_id; ?>">History</a></li>
                    <li class="breadcrumb-item active">Details</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Summary Cards -->
        <div class="row">
            <div class="col-lg-2 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $stats['total_stays']; ?></h3>
                        <p>Total Stays</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-calendar-check"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $stats['total_nights']; ?></h3>
                        <p>Nights</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-moon"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['total_spent']); ?></h3>
                        <p>Total Spent</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-primary">
                    <div class="inner">
                        <h3><?php echo format_currency($stats['avg_spent']); ?></h3>
                        <p>Avg. per Stay</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $stats['cancelled']; ?></h3>
                        <p>Cancellations</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-times-circle"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-2 col-6">
                <div class="small-box bg-secondary">
                    <div class="inner">
                        <h3><?php echo $stats['completed']; ?></h3>
                        <p>Completed</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Guest Information -->
        <div class="row">
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user mr-1"></i>
                            Guest Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 120px;">Guest Code:</th>
                                <td><strong><?php echo $guest['guest_code']; ?></strong></td>
                            </tr>
                            <tr>
                                <th>Name:</th>
                                <td><?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?></td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td><?php echo $guest['email'] ?: 'Not provided'; ?></td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td><?php echo $guest['phone'] ?: 'Not provided'; ?></td>
                            </tr>
                            <tr>
                                <th>Nationality:</th>
                                <td><?php echo $guest['nationality'] ?: 'Not provided'; ?></td>
                            </tr>
                            <tr>
                                <th>Member Since:</th>
                                <td><?php echo format_date($guest['created_at']); ?></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <!-- Preferences -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-heart mr-1"></i>
                            Preferences & Insights
                        </h3>
                    </div>
                    <div class="card-body">
                        <h6>Favorite Room Types</h6>
                        <?php if (empty($room_type_counts)): ?>
                            <p class="text-muted">No data available</p>
                        <?php else: ?>
                            <?php foreach (array_slice($room_type_counts, 0, 3) as $type => $count): ?>
                                <div class="d-flex justify-content-between mb-2">
                                    <span><?php echo $type; ?></span>
                                    <span class="badge badge-info"><?php echo $count; ?> stays</span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>

                        <hr>

                        <h6>Visit History</h6>
                        <p><strong>First Visit:</strong> <?php echo $stats['first_visit'] ? format_date($stats['first_visit']) : 'Never'; ?></p>
                        <p><strong>Last Visit:</strong> <?php echo $stats['last_visit'] ? format_date($stats['last_visit']) : 'Never'; ?></p>
                        <p><strong>Frequency:</strong> 
                            <?php 
                            if ($stats['total_stays'] > 0) {
                                $first = new DateTime($stats['first_visit']);
                                $last = new DateTime($stats['last_visit']);
                                $interval = $first->diff($last);
                                $months = ($interval->y * 12) + $interval->m + 1;
                                $frequency = $months > 0 ? round($stats['total_stays'] / $months, 1) : 0;
                                echo "~$frequency stays per month";
                            } else {
                                echo 'N/A';
                            }
                            ?>
                        </p>
                    </div>
                </div>
            </div>

            <!-- Spending by Year -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-chart-bar mr-1"></i>
                            Annual Spending
                        </h3>
                    </div>
                    <div class="card-body">
                        <canvas id="spendingChart" style="height: 300px;"></canvas>
                    </div>
                </div>

                <!-- Recent Activity Timeline -->
                <div class="card mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history mr-1"></i>
                            Activity Timeline
                        </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="timeline" style="padding: 1rem;">
                                <?php 
                                $last_date = '';
                                foreach ($activities as $activity):
                                    $date = format_date($activity['created_at']);
                                    if ($date != $last_date):
                                        $last_date = $date;
                                ?>
                                    <div class="time-label">
                                        <span class="bg-info"><?php echo $date; ?></span>
                                    </div>
                                <?php endif; ?>
                                    <div class="timeline-item">
                                        <span class="time">
                                            <i class="fas fa-clock"></i> <?php echo date('H:i', strtotime($activity['created_at'])); ?>
                                        </span>
                                        <div class="timeline-body">
                                            <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' : 
                                                    ($activity['activity_type'] == 'document_uploaded' ? 'fa-file-alt text-secondary' : 'fa-info-circle')))));
                                            ?> mr-2"></i>
                                            <?php echo escape_html($activity['description']); ?>
                                            <br>
                                            <small class="text-muted">by <?php echo $activity['first_name']; ?></small>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Complete Reservation History -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list mr-1"></i>
                            Complete Reservation History
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($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>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Booking #</th>
                                            <th>Dates</th>
                                            <th>Nights</th>
                                            <th>Room Type</th>
                                            <th>Room</th>
                                            <th class="text-right">Total</th>
                                            <th class="text-right">Paid</th>
                                            <th class="text-right">Balance</th>
                                            <th>Status</th>
                                            <th>Created By</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($reservations as $res): ?>
                                        <tr class="<?php 
                                            echo $res['balance'] > 0 ? 'table-warning' : '';
                                            echo $res['booking_status'] == 'cancelled' ? 'table-danger' : '';
                                        ?>">
                                            <td>
                                                <a href="<?php echo base_url('reservations/view.php?id=' . $res['reservation_id']); ?>">
                                                    <?php echo $res['booking_code']; ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php echo format_date($res['check_in_date']); ?><br>
                                                <small>to <?php echo format_date($res['check_out_date']); ?></small>
                                            </td>
                                            <td class="text-center"><?php echo $res['nights']; ?></td>
                                            <td><?php echo $res['type_name']; ?></td>
                                            <td>
                                                <?php if ($res['room_number']): ?>
                                                    Room <?php echo $res['room_number']; ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-right"><?php echo format_currency($res['total_amount']); ?></td>
                                            <td class="text-right"><?php echo format_currency($res['paid_amount']); ?></td>
                                            <td class="text-right">
                                                <?php if ($res['balance'] > 0): ?>
                                                    <span class="badge badge-warning"><?php echo format_currency($res['balance']); ?></span>
                                                <?php else: ?>
                                                    <span class="badge badge-success">Paid</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?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']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <small><?php echo $res['created_by_first'] . ' ' . $res['created_by_last']; ?></small>
                                            </td>
                                            <td>
                                                <a href="<?php echo base_url('reservations/view.php?id=' . $res['reservation_id']); ?>" 
                                                   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>

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

<script>
$(document).ready(function() {
    // Spending Chart
    const spendingCtx = document.getElementById('spendingChart').getContext('2d');
    
    new Chart(spendingCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode(array_keys($spending_by_year)); ?>,
            datasets: [{
                label: 'Annual Spending',
                data: <?php echo json_encode(array_values($spending_by_year)); ?>,
                backgroundColor: '#28a745',
                borderColor: '#218838',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '<?php echo CURRENCY_SYMBOL; ?>' + value;
                        }
                    }
                }
            }
        }
    });
});
</script>

<style>
.timeline {
    position: relative;
    padding: 0;
    list-style: none;
}
.timeline .time-label {
    position: relative;
    margin: 20px 0 10px;
}
.timeline .time-label span {
    padding: 5px 10px;
    border-radius: 3px;
    font-size: 0.85rem;
}
.timeline-item {
    position: relative;
    padding-bottom: 15px;
    padding-left: 20px;
    border-left: 2px solid #dee2e6;
    margin-left: 10px;
}
.timeline-item:last-child {
    padding-bottom: 0;
}
.timeline-item .time {
    position: absolute;
    left: -30px;
    top: 0;
    color: #6c757d;
    font-size: 0.75rem;
    white-space: nowrap;
}
.timeline-item .timeline-body {
    padding: 5px 0 0 0;
}
</style>

<?php
// Include footer
require_once dirname(__DIR__, 3) . '/views/partials/footer.php';
?>