<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Notifications';

if (!$auth->isLoggedIn()) {
    header('Location: ../login.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        die(json_encode(['success' => false, 'message' => 'Invalid CSRF token']));
    }
    
    header('Content-Type: application/json');
    $action = $_POST['action'];
    
    if ($action === 'mark_read') {
        $notif_id = (int)$_POST['notif_id'];
        $sql = "UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ? AND user_id = ?";
        if ($db->execute($sql, [$notif_id, $current_user['id']])) {
            echo json_encode(['success' => true, 'message' => 'Marked as read']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update']);
        }
        exit;
    }
    
    if ($action === 'mark_all_read') {
        $sql = "UPDATE notifications SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0";
        if ($db->execute($sql, [$current_user['id']])) {
            echo json_encode(['success' => true, 'message' => 'All notifications marked as read']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update']);
        }
        exit;
    }
    
    if ($action === 'delete') {
        $notif_id = (int)$_POST['notif_id'];
        $sql = "DELETE FROM notifications WHERE id = ? AND user_id = ?";
        if ($db->execute($sql, [$notif_id, $current_user['id']])) {
            echo json_encode(['success' => true, 'message' => 'Notification deleted']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete']);
        }
        exit;
    }
    
    if ($action === 'delete_all_read') {
        $sql = "DELETE FROM notifications WHERE user_id = ? AND is_read = 1";
        if ($db->execute($sql, [$current_user['id']])) {
            echo json_encode(['success' => true, 'message' => 'All read notifications deleted']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to delete']);
        }
        exit;
    }
}

// Get filter
$filter = $_GET['filter'] ?? 'all';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query
$where = ["user_id = ?"];
$params = [$current_user['id']];

if ($filter === 'unread') {
    $where[] = "is_read = 0";
} elseif ($filter === 'read') {
    $where[] = "is_read = 1";
}

$where_sql = 'WHERE ' . implode(' AND ', $where);

$count_sql = "SELECT COUNT(*) as total FROM notifications $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

$sql = "SELECT * FROM notifications
        $where_sql
        ORDER BY created_at DESC
        LIMIT $limit OFFSET $offset";

$notifications = $db->fetchAll($sql, $params);

// Get counts
$unread_count = $db->fetchOne("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0", [$current_user['id']])['count'];
$read_count = $db->fetchOne("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 1", [$current_user['id']])['count'];

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Notifications</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Notifications</li>
        </ol>
    </nav>
</div>

<div class="card">
    <div class="card-header">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <ul class="nav nav-tabs card-header-tabs">
                    <li class="nav-item">
                        <a class="nav-link <?php echo $filter === 'all' ? 'active' : ''; ?>" href="?filter=all">
                            All <span class="badge bg-secondary"><?php echo number_format($total); ?></span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?php echo $filter === 'unread' ? 'active' : ''; ?>" href="?filter=unread">
                            Unread <span class="badge bg-primary"><?php echo number_format($unread_count); ?></span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link <?php echo $filter === 'read' ? 'active' : ''; ?>" href="?filter=read">
                            Read <span class="badge bg-success"><?php echo number_format($read_count); ?></span>
                        </a>
                    </li>
                </ul>
            </div>
            
            <div>
                <button type="button" class="btn btn-sm btn-outline-primary" id="markAllRead">
                    <i class="fas fa-check-double"></i> Mark All Read
                </button>
                <button type="button" class="btn btn-sm btn-outline-danger" id="deleteAllRead">
                    <i class="fas fa-trash"></i> Delete All Read
                </button>
            </div>
        </div>
    </div>
    
    <div class="card-body p-0">
        <?php if (empty($notifications)): ?>
        <div class="text-center py-5">
            <i class="fas fa-bell-slash fa-4x text-muted mb-3 d-block"></i>
            <h5 class="text-muted">No notifications</h5>
            <p class="text-muted">You're all caught up!</p>
        </div>
        <?php else: ?>
        <div class="list-group list-group-flush">
            <?php foreach ($notifications as $notif): ?>
            <div class="list-group-item list-group-item-action <?php echo !$notif['is_read'] ? 'bg-light' : ''; ?>" 
                 style="cursor: pointer;">
                <div class="d-flex w-100 justify-content-between align-items-start">
                    <div class="flex-grow-1" onclick="handleNotificationClick(<?php echo $notif['id']; ?>, '<?php echo htmlspecialchars($notif['link'] ?? '', ENT_QUOTES); ?>')">
                        <div class="d-flex align-items-center mb-2">
                            <?php if (!$notif['is_read']): ?>
                            <span class="badge bg-primary me-2">New</span>
                            <?php endif; ?>
                            
                            <?php
                            $type_icons = [
                                'info' => 'info-circle text-info',
                                'success' => 'check-circle text-success',
                                'warning' => 'exclamation-triangle text-warning',
                                'error' => 'exclamation-circle text-danger',
                                'payment' => 'credit-card text-success',
                                'application' => 'file-alt text-primary',
                                'property' => 'building text-info',
                                'user' => 'user text-secondary'
                            ];
                            $icon = $type_icons[$notif['type']] ?? 'bell text-secondary';
                            ?>
                            <i class="fas fa-<?php echo $icon; ?> me-2"></i>
                            
                            <h6 class="mb-0"><?php echo htmlspecialchars($notif['title']); ?></h6>
                        </div>
                        
                        <p class="mb-1 text-muted"><?php echo htmlspecialchars($notif['message']); ?></p>
                        
                        <small class="text-muted">
                            <i class="far fa-clock"></i>
                            <?php 
                            $timestamp = strtotime($notif['created_at']);
                            $diff = time() - $timestamp;
                            
                            if ($diff < 60) {
                                echo 'Just now';
                            } elseif ($diff < 3600) {
                                echo floor($diff / 60) . ' minutes ago';
                            } elseif ($diff < 86400) {
                                echo floor($diff / 3600) . ' hours ago';
                            } elseif ($diff < 604800) {
                                echo floor($diff / 86400) . ' days ago';
                            } else {
                                echo date('M d, Y H:i', $timestamp);
                            }
                            ?>
                        </small>
                    </div>
                    
                    <div class="ms-3">
                        <div class="btn-group btn-group-sm">
                            <?php if (!$notif['is_read']): ?>
                            <button type="button" class="btn btn-outline-success mark-read" 
                                    data-id="<?php echo $notif['id']; ?>"
                                    data-bs-toggle="tooltip" title="Mark as read"
                                    onclick="event.stopPropagation()">
                                <i class="fas fa-check"></i>
                            </button>
                            <?php endif; ?>
                            
                            <button type="button" class="btn btn-outline-danger delete-notif" 
                                    data-id="<?php echo $notif['id']; ?>"
                                    data-bs-toggle="tooltip" title="Delete"
                                    onclick="event.stopPropagation()">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="card-footer">
            <nav>
                <ul class="pagination justify-content-center mb-0">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">Previous</a>
                    </li>
                    
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">Next</a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<script>
    const csrfToken = '<?php echo Security::generateCSRFToken(); ?>';
    
    // Handle notification click
    function handleNotificationClick(notifId, link) {
        // Mark as read
        $.post('notifications.php', {
            action: 'mark_read',
            notif_id: notifId,
            csrf_token: csrfToken
        }, function(response) {
            if (response.success && link) {
                window.location.href = link;
            } else if (response.success) {
                location.reload();
            }
        }, 'json');
    }
    
    // Mark as read
    $('.mark-read').click(function() {
        const notifId = $(this).data('id');
        
        $.post('notifications.php', {
            action: 'mark_read',
            notif_id: notifId,
            csrf_token: csrfToken
        }, function(response) {
            if (response.success) {
                location.reload();
            }
        }, 'json');
    });
    
    // Delete notification
    $('.delete-notif').click(function() {
        const notifId = $(this).data('id');
        
        Swal.fire({
            title: 'Delete Notification?',
            text: 'This action cannot be undone',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('notifications.php', {
                    action: 'delete',
                    notif_id: notifId,
                    csrf_token: csrfToken
                }, function(response) {
                    if (response.success) {
                        location.reload();
                    }
                }, 'json');
            }
        });
    });
    
    // Mark all as read
    $('#markAllRead').click(function() {
        $.post('notifications.php', {
            action: 'mark_all_read',
            csrf_token: csrfToken
        }, function(response) {
            if (response.success) {
                Swal.fire('Success', response.message, 'success').then(() => location.reload());
            }
        }, 'json');
    });
    
    // Delete all read
    $('#deleteAllRead').click(function() {
        Swal.fire({
            title: 'Delete All Read Notifications?',
            text: 'This will permanently delete all read notifications',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete them!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('notifications.php', {
                    action: 'delete_all_read',
                    csrf_token: csrfToken
                }, function(response) {
                    if (response.success) {
                        Swal.fire('Success', response.message, 'success').then(() => location.reload());
                    }
                }, 'json');
            }
        });
    });
    
    // Initialize tooltips
    $('[data-bs-toggle="tooltip"]').tooltip();
</script>

<?php include 'includes/footer.php'; ?>