<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Guest Blacklist Management
 * 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_once dirname(__DIR__, 3) . '/config/mailer.php';

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

// Set page title
$page_title = 'Blacklist Management';

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

// Handle actions
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        $guest_id = (int)($_POST['guest_id'] ?? 0);
        $reason = sanitize_input($_POST['reason'] ?? '');
        
        if (!$guest_id) {
            $error = 'Invalid guest ID';
        } else {
            // Get guest info
            $guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$guest_id]);
            
            if (!$guest) {
                $error = 'Guest not found';
            } else {
                try {
                    begin_transaction();
                    
                    if ($action === 'add') {
                        if (empty($reason)) {
                            $error = 'Reason is required for blacklisting';
                        } else {
                            // Update guest
                            db_update('guests', [
                                'is_blacklisted' => 1,
                                'blacklist_reason' => $reason
                            ], 'guest_id = ?', [$guest_id]);
                            
                            // Create activity record
                            db_insert('guest_activity', [
                                'guest_id' => $guest_id,
                                'activity_type' => 'blacklist',
                                'description' => "Guest added to blacklist. Reason: $reason",
                                'created_by' => $current_user['user_id']
                            ]);
                            
                            // Cancel any pending reservations
                            db_update('reservations', [
                                'booking_status' => 'cancelled',
                                'cancel_reason' => 'Guest blacklisted'
                            ], 'guest_id = ? AND booking_status IN ("pending", "confirmed")', [$guest_id]);
                            
                            // Send notifications to managers
                            $managers = db_fetch_all("
                                SELECT email FROM users 
                                WHERE role_id IN (1, 2, 3) AND is_active = 1
                            ");
                            
                            foreach ($managers as $manager) {
                                // In production, you might want to queue these emails
                                send_blacklist_alert($guest, $reason, $current_user['first_name'] . ' ' . $current_user['last_name']);
                            }
                            
                            $message = 'Guest added to blacklist successfully';
                            
                            // Audit log
                            audit_log($current_user['user_id'], AUDIT_BLACKLIST, 'guests', $guest_id, 
                                     ['is_blacklisted' => 0], 
                                     ['is_blacklisted' => 1, 'reason' => $reason]);
                        }
                    } elseif ($action === 'remove') {
                        // Update guest
                        db_update('guests', [
                            'is_blacklisted' => 0,
                            'blacklist_reason' => null
                        ], 'guest_id = ?', [$guest_id]);
                        
                        // Create activity record
                        db_insert('guest_activity', [
                            'guest_id' => $guest_id,
                            'activity_type' => 'blacklist_removed',
                            'description' => "Guest removed from blacklist" . ($reason ? ". Reason: $reason" : ''),
                            'created_by' => $current_user['user_id']
                        ]);
                        
                        $message = 'Guest removed from blacklist successfully';
                        
                        // Audit log
                        audit_log($current_user['user_id'], 'blacklist_remove', 'guests', $guest_id,
                                 ['is_blacklisted' => 1],
                                 ['is_blacklisted' => 0, 'reason' => $reason]);
                    }
                    
                    commit_transaction();
                    
                } catch (Exception $e) {
                    rollback_transaction();
                    $error = 'Failed to update blacklist: ' . $e->getMessage();
                    log_message("Blacklist update failed: " . $e->getMessage(), 'ERROR');
                }
            }
        }
    }
}

// Handle GET requests for simple actions
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action'])) {
    $action = $_GET['action'];
    $guest_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    
    if ($action === 'remove' && $guest_id) {
        // Show confirmation page for removal
        $guest = db_fetch_one("SELECT * FROM guests WHERE guest_id = ?", [$guest_id]);
        if ($guest) {
            // Display confirmation page
            ?>
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Remove from Blacklist</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">
            </head>
            <body>
                <div class="container mt-5">
                    <div class="row justify-content-center">
                        <div class="col-md-6">
                            <div class="card card-success">
                                <div class="card-header">
                                    <h3 class="card-title">Remove from Blacklist</h3>
                                </div>
                                <div class="card-body">
                                    <p>Are you sure you want to remove <strong><?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?></strong> from the blacklist?</p>
                                    
                                    <form action="blacklist.php" method="POST">
                                        <?php echo csrf_field(); ?>
                                        <input type="hidden" name="action" value="remove">
                                        <input type="hidden" name="guest_id" value="<?php echo $guest_id; ?>">
                                        
                                        <div class="form-group">
                                            <label for="reason">Reason for removal (optional)</label>
                                            <textarea class="form-control" id="reason" name="reason" rows="2"></textarea>
                                        </div>
                                        
                                        <div class="mt-3">
                                            <button type="submit" class="btn btn-success">Confirm Removal</button>
                                            <a href="view.php?id=<?php echo $guest_id; ?>" class="btn btn-secondary">Cancel</a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </body>
            </html>
            <?php
            exit;
        }
    }
}

// Get blacklisted guests
$blacklisted = db_fetch_all("
    SELECT g.*, 
           COUNT(r.reservation_id) as total_stays,
           MAX(r.check_in_date) as last_visit
    FROM guests g
    LEFT JOIN reservations r ON g.guest_id = r.guest_id
    WHERE g.is_blacklisted = 1
    GROUP BY g.guest_id
    ORDER BY g.updated_at DESC
");

// Get blacklist history/audit
$history = 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.activity_type IN ('blacklist', 'blacklist_removed')
    ORDER BY a.created_at DESC
    LIMIT 50
");

// 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">Blacklist Management</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="index.php">Guests</a></li>
                    <li class="breadcrumb-item active">Blacklist</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo $error; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>

        <!-- Stats Card -->
        <div class="row">
            <div class="col-md-3">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo count($blacklisted); ?></h3>
                        <p>Blacklisted Guests</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-ban"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Blacklisted Guests -->
        <div class="row">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-ban mr-1"></i>
                            Blacklisted Guests
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($blacklisted)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-check-circle fa-4x mb-3 text-success"></i>
                                <h5>No blacklisted guests</h5>
                                <p>The blacklist is currently empty</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Guest Code</th>
                                            <th>Name</th>
                                            <th>Contact</th>
                                            <th>Reason</th>
                                            <th>Date Added</th>
                                            <th>Previous Stays</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($blacklisted as $guest): ?>
                                        <tr>
                                            <td><?php echo $guest['guest_code']; ?></td>
                                            <td>
                                                <a href="view.php?id=<?php echo $guest['guest_id']; ?>">
                                                    <?php echo escape_html($guest['first_name'] . ' ' . $guest['last_name']); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php if ($guest['email']): ?>
                                                    <i class="fas fa-envelope text-muted"></i> <?php echo $guest['email']; ?><br>
                                                <?php endif; ?>
                                                <?php if ($guest['phone']): ?>
                                                    <i class="fas fa-phone text-muted"></i> <?php echo $guest['phone']; ?>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge badge-danger"><?php echo escape_html($guest['blacklist_reason'] ?: 'No reason provided'); ?></span>
                                            </td>
                                            <td>
                                                <?php echo format_date($guest['updated_at']); ?>
                                                <br>
                                                <small class="text-muted"><?php echo time_ago($guest['updated_at']); ?></small>
                                            </td>
                                            <td class="text-center">
                                                <span class="badge badge-info"><?php echo $guest['total_stays']; ?></span>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <a href="view.php?id=<?php echo $guest['guest_id']; ?>" 
                                                       class="btn btn-sm btn-info" title="View">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    
                                                    <a href="?action=remove&id=<?php echo $guest['guest_id']; ?>" 
                                                       class="btn btn-sm btn-success" title="Remove from Blacklist">
                                                        <i class="fas fa-check-circle"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Blacklist History -->
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history mr-1"></i>
                            Blacklist History
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($history)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-history fa-3x mb-3"></i>
                                <p>No blacklist history</p>
                            </div>
                        <?php else: ?>
                            <div class="timeline" style="padding: 1rem;">
                                <?php foreach ($history as $entry): ?>
                                <div class="timeline-item">
                                    <span class="time">
                                        <i class="fas fa-clock"></i> <?php echo time_ago($entry['created_at']); ?>
                                    </span>
                                    <div class="timeline-body">
                                        <i class="fas <?php echo $entry['activity_type'] == 'blacklist' ? 'fa-ban text-danger' : 'fa-check-circle text-success'; ?> mr-2"></i>
                                        <strong><?php echo ucfirst(str_replace('_', ' ', $entry['activity_type'])); ?></strong>
                                        <br>
                                        <?php echo escape_html($entry['description']); ?>
                                        <br>
                                        <small class="text-muted">by <?php echo $entry['first_name']; ?></small>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Information Card -->
                <div class="card card-info mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle mr-1"></i>
                            About Blacklisting
                        </h3>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            <li class="mb-2">
                                <i class="fas fa-ban text-danger mr-2"></i>
                                <strong>Blacklisted guests</strong> cannot make new reservations.
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-bell text-warning mr-2"></i>
                                Staff are alerted when a blacklisted guest attempts to check in.
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-clock text-info mr-2"></i>
                                Existing reservations for blacklisted guests are automatically cancelled.
                            </li>
                            <li class="mb-2">
                                <i class="fas fa-envelope text-primary mr-2"></i>
                                Notifications are sent to management when a guest is blacklisted.
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
.timeline {
    position: relative;
    padding: 0;
    list-style: none;
}
.timeline-item {
    position: relative;
    padding-bottom: 15px;
    padding-left: 20px;
    border-left: 2px solid #dee2e6;
}
.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
/**
 * Send blacklist alert email
 */
function send_blacklist_alert($guest, $reason, $added_by) {
    $subject = "Blacklist Alert: {$guest['first_name']} {$guest['last_name']}";
    
    $body = "
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; }
            .header { background: #dc3545; color: white; padding: 20px; }
            .content { padding: 20px; }
            .details { background: #f8d7da; padding: 15px; border-radius: 5px; }
        </style>
    </head>
    <body>
        <div class='header'>
            <h2>Guest Blacklist Alert</h2>
        </div>
        <div class='content'>
            <p>A guest has been added to the blacklist:</p>
            
            <div class='details'>
                <p><strong>Guest:</strong> {$guest['first_name']} {$guest['last_name']}</p>
                <p><strong>Guest Code:</strong> {$guest['guest_code']}</p>
                <p><strong>Email:</strong> {$guest['email']}</p>
                <p><strong>Phone:</strong> {$guest['phone']}</p>
                <p><strong>Reason:</strong> $reason</p>
                <p><strong>Added by:</strong> $added_by</p>
                <p><strong>Date:</strong> " . date('Y-m-d H:i:s') . "</p>
            </div>
            
            <p>All pending reservations for this guest have been cancelled.</p>
            <p>Please ensure all departments are aware of this blacklisting.</p>
        </div>
    </body>
    </html>
    ";
    
    $alt_body = "Guest Blacklist Alert\n\n";
    $alt_body .= "Guest: {$guest['first_name']} {$guest['last_name']}\n";
    $alt_body .= "Guest Code: {$guest['guest_code']}\n";
    $alt_body .= "Email: {$guest['email']}\n";
    $alt_body .= "Phone: {$guest['phone']}\n";
    $alt_body .= "Reason: $reason\n";
    $alt_body .= "Added by: $added_by\n";
    $alt_body .= "Date: " . date('Y-m-d H:i:s') . "\n\n";
    $alt_body .= "All pending reservations for this guest have been cancelled.\n";
    
    // In production, you would send to multiple recipients
    // For now, just log it
    log_message("Blacklist alert for guest {$guest['guest_id']}: $reason", 'INFO');
    
    return true;
}

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