<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Notifications Page
 * Developer: JOACHIM'S INNOTECH
 */

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

// Require authentication
require_auth();

// Set page title
$page_title = 'Notifications';

// Get current user
$user_id = current_user_id();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'mark_read':
                $notification_id = $_POST['notification_id'] ?? 0;
                if ($notification_id) {
                    db_update('notifications', ['is_read' => 1], 'notification_id = ? AND user_id = ?', [$notification_id, $user_id]);
                    $message = 'Notification marked as read';
                }
                break;
                
            case 'mark_all_read':
                db_update('notifications', ['is_read' => 1], 'user_id = ? AND is_read = 0', [$user_id]);
                $message = 'All notifications marked as read';
                break;
                
            case 'delete':
                $notification_id = $_POST['notification_id'] ?? 0;
                if ($notification_id) {
                    db_delete('notifications', 'notification_id = ? AND user_id = ?', [$notification_id, $user_id]);
                    $message = 'Notification deleted';
                }
                break;
                
            case 'delete_all':
                db_delete('notifications', 'user_id = ?', [$user_id]);
                $message = 'All notifications deleted';
                break;
        }
    }
}

// Get filter parameters
$filter_type = $_GET['type'] ?? 'all';
$filter_read = $_GET['read'] ?? 'all';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$per_page = ITEMS_PER_PAGE;

// Build where clause
$where = "user_id = ?";
$params = [$user_id];

if ($filter_type !== 'all') {
    $where .= " AND type = ?";
    $params[] = $filter_type;
}

if ($filter_read === 'unread') {
    $where .= " AND is_read = 0";
} elseif ($filter_read === 'read') {
    $where .= " AND is_read = 1";
}

// Get notifications with pagination
$notifications = db_paginate(
    'notifications',
    '*',
    $where,
    $params,
    'created_at DESC',
    $page,
    $per_page
);

// Get notification stats
$stats = [
    'total' => db_count('notifications', 'user_id = ?', [$user_id]),
    'unread' => db_count('notifications', 'user_id = ? AND is_read = 0', [$user_id]),
    'read' => db_count('notifications', 'user_id = ? AND is_read = 1', [$user_id])
];

// Get notification types breakdown
$types = db_fetch_all(
    "SELECT type, COUNT(*) as count FROM notifications WHERE user_id = ? GROUP BY type",
    [$user_id]
);

// Include header
require_once dirname(__DIR__) . '/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">Notifications</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 active">Notifications</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; ?>

        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Filter</h3>
                    </div>
                    <div class="card-body p-0">
                        <ul class="nav nav-pills flex-column">
                            <li class="nav-item">
                                <a href="?type=all&read=all" class="nav-link <?php echo $filter_type == 'all' && $filter_read == 'all' ? 'active' : ''; ?>">
                                    <i class="fas fa-inbox mr-2"></i>
                                    All
                                    <span class="badge bg-primary float-right"><?php echo $stats['total']; ?></span>
                                </a>
                            </li>
                            <li class="nav-item">
                                <a href="?type=all&read=unread" class="nav-link <?php echo $filter_read == 'unread' ? 'active' : ''; ?>">
                                    <i class="fas fa-envelope mr-2"></i>
                                    Unread
                                    <span class="badge bg-warning float-right"><?php echo $stats['unread']; ?></span>
                                </a>
                            </li>
                            <li class="nav-item">
                                <a href="?type=all&read=read" class="nav-link <?php echo $filter_read == 'read' ? 'active' : ''; ?>">
                                    <i class="fas fa-envelope-open mr-2"></i>
                                    Read
                                    <span class="badge bg-secondary float-right"><?php echo $stats['read']; ?></span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>

                <!-- Types Card -->
                <?php if (!empty($types)): ?>
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Types</h3>
                    </div>
                    <div class="card-body p-0">
                        <ul class="nav nav-pills flex-column">
                            <?php foreach ($types as $type): ?>
                            <li class="nav-item">
                                <a href="?type=<?php echo $type['type']; ?>&read=<?php echo $filter_read; ?>" 
                                   class="nav-link <?php echo $filter_type == $type['type'] ? 'active' : ''; ?>">
                                    <i class="fas fa-<?php 
                                        echo $type['type'] == 'success' ? 'check-circle text-success' : 
                                            ($type['type'] == 'warning' ? 'exclamation-triangle text-warning' : 
                                            ($type['type'] == 'danger' ? 'times-circle text-danger' : 
                                            ($type['type'] == 'info' ? 'info-circle text-info' : 'bell'))); 
                                    ?> mr-2"></i>
                                    <?php echo ucfirst($type['type']); ?>
                                    <span class="badge bg-secondary float-right"><?php echo $type['count']; ?></span>
                                </a>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Actions -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Actions</h3>
                    </div>
                    <div class="card-body">
                        <?php if ($stats['unread'] > 0): ?>
                        <form method="POST" class="mb-2">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="action" value="mark_all_read">
                            <button type="submit" class="btn btn-primary btn-block">
                                <i class="fas fa-check-double mr-2"></i>
                                Mark All as Read
                            </button>
                        </form>
                        <?php endif; ?>
                        
                        <?php if ($stats['total'] > 0): ?>
                        <form method="POST" onsubmit="return confirm('Delete all notifications? This cannot be undone.');">
                            <?php echo csrf_field(); ?>
                            <input type="hidden" name="action" value="delete_all">
                            <button type="submit" class="btn btn-danger btn-block">
                                <i class="fas fa-trash mr-2"></i>
                                Delete All
                            </button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Settings -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Settings</h3>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label>Email Notifications</label>
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="emailNotifications" 
                                       <?php echo get_user_setting($user_id, 'email_notifications', true) ? 'checked' : ''; ?>>
                                <label class="custom-control-label" for="emailNotifications">Receive email notifications</label>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Sound</label>
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="soundNotifications"
                                       <?php echo get_user_setting($user_id, 'sound_notifications', true) ? 'checked' : ''; ?>>
                                <label class="custom-control-label" for="soundNotifications">Play sound for new notifications</label>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Desktop Notifications</label>
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="desktopNotifications"
                                       <?php echo get_user_setting($user_id, 'desktop_notifications', false) ? 'checked' : ''; ?>>
                                <label class="custom-control-label" for="desktopNotifications">Show desktop notifications</label>
                            </div>
                        </div>
                        
                        <button class="btn btn-sm btn-primary" onclick="saveSettings()">
                            <i class="fas fa-save mr-1"></i> Save Settings
                        </button>
                    </div>
                </div>
            </div>

            <!-- Notifications List -->
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Notification History</h3>
                        <div class="card-tools">
                            <span class="badge badge-info"><?php echo $notifications['total']; ?> Total</span>
                        </div>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($notifications['data'])): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-bell-slash fa-4x mb-3"></i>
                                <h5>No notifications found</h5>
                                <p>You're all caught up!</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($notifications['data'] as $notification): ?>
                                <div class="list-group-item list-group-item-action <?php echo !$notification['is_read'] ? 'list-group-item-info' : ''; ?>">
                                    <div class="row align-items-center">
                                        <div class="col-auto">
                                            <i class="fas fa-<?php 
                                                echo $notification['type'] == 'success' ? 'check-circle text-success' : 
                                                    ($notification['type'] == 'warning' ? 'exclamation-triangle text-warning' : 
                                                    ($notification['type'] == 'danger' ? 'times-circle text-danger' : 
                                                    ($notification['type'] == 'info' ? 'info-circle text-info' : 'bell text-secondary'))); 
                                            ?> fa-2x"></i>
                                        </div>
                                        <div class="col">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <h5 class="mb-1"><?php echo escape_html($notification['title']); ?></h5>
                                                <small class="text-muted">
                                                    <i class="far fa-clock mr-1"></i>
                                                    <?php echo time_ago($notification['created_at']); ?>
                                                </small>
                                            </div>
                                            <p class="mb-1"><?php echo escape_html($notification['message']); ?></p>
                                            
                                            <?php if ($notification['link']): ?>
                                                <a href="<?php echo base_url($notification['link']); ?>" class="btn btn-sm btn-primary mt-2">
                                                    <i class="fas fa-external-link-alt mr-1"></i> View Details
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                        <div class="col-auto">
                                            <div class="btn-group-vertical">
                                                <?php if (!$notification['is_read']): ?>
                                                <form method="POST" style="display: inline;">
                                                    <?php echo csrf_field(); ?>
                                                    <input type="hidden" name="action" value="mark_read">
                                                    <input type="hidden" name="notification_id" value="<?php echo $notification['notification_id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-success" title="Mark as read">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                </form>
                                                <?php endif; ?>
                                                
                                                <form method="POST" style="display: inline;" onsubmit="return confirm('Delete this notification?');">
                                                    <?php echo csrf_field(); ?>
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="notification_id" value="<?php echo $notification['notification_id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger" title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Pagination -->
                    <?php if ($notifications['total_pages'] > 1): ?>
                    <div class="card-footer clearfix">
                        <ul class="pagination pagination-sm m-0 float-right">
                            <?php if ($notifications['has_previous']): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $notifications['previous_page']; ?>&type=<?php echo $filter_type; ?>&read=<?php echo $filter_read; ?>">
                                    <i class="fas fa-chevron-left"></i>
                                </a>
                            </li>
                            <?php endif; ?>
                            
                            <?php
                            $start = max(1, $notifications['current_page'] - 2);
                            $end = min($notifications['total_pages'], $notifications['current_page'] + 2);
                            
                            for ($i = $start; $i <= $end; $i++):
                            ?>
                            <li class="page-item <?php echo $i == $notifications['current_page'] ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&type=<?php echo $filter_type; ?>&read=<?php echo $filter_read; ?>">
                                    <?php echo $i; ?>
                                </a>
                            </li>
                            <?php endfor; ?>
                            
                            <?php if ($notifications['has_next']): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?php echo $notifications['next_page']; ?>&type=<?php echo $filter_type; ?>&read=<?php echo $filter_read; ?>">
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                            <?php endif; ?>
                        </ul>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
// Save notification settings
function saveSettings() {
    const settings = {
        email_notifications: $('#emailNotifications').is(':checked'),
        sound_notifications: $('#soundNotifications').is(':checked'),
        desktop_notifications: $('#desktopNotifications').is(':checked')
    };
    
    $.ajax({
        url: '<?php echo base_url('api/user-settings.php'); ?>',
        method: 'POST',
        data: {
            settings: settings,
            csrf_token: '<?php echo csrf_token(); ?>'
        },
        success: function(response) {
            if (response.status === 'success') {
                App.showToast('Settings saved successfully', 'success');
                
                // Request desktop notification permission if enabled
                if (settings.desktop_notifications && 'Notification' in window) {
                    Notification.requestPermission();
                }
            } else {
                App.showToast('Failed to save settings', 'error');
            }
        },
        error: function() {
            App.showToast('Failed to save settings', 'error');
        }
    });
}

// Check for desktop notifications permission
if ('Notification' in window && Notification.permission === 'default') {
    // Show gentle reminder
    setTimeout(function() {
        if (confirm('Would you like to enable desktop notifications for important alerts?')) {
            Notification.requestPermission();
        }
    }, 3000);
}

// Listen for new notifications (via Pusher or polling)
<?php if (isset($realtime) && $realtime): ?>
// You can implement real-time notifications here using WebSockets/Pusher
<?php endif; ?>
</script>

<?php
// Helper function to get user settings
function get_user_setting($user_id, $key, $default = false) {
    static $settings = null;
    
    if ($settings === null) {
        $settings = db_fetch_one(
            "SELECT settings FROM user_settings WHERE user_id = ?",
            [$user_id]
        );
        $settings = $settings ? json_decode($settings['settings'], true) : [];
    }
    
    return $settings[$key] ?? $default;
}

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