<?php session_start();
// loan_details.php
include 'includes/head.php';
include 'includes/session.php';

// Check if user is logged in


// Mark notification as read if requested
if (isset($_GET['mark_read']) && is_numeric($_GET['mark_read'])) {
    $notification_id = intval($_GET['mark_read']);
    $update_sql = "UPDATE notifications SET is_read = 1 WHERE id = '$notification_id' AND user_id = '$user_id'";
    mysqli_query($conn, $update_sql);
}

// Mark all as read
if (isset($_GET['mark_all_read'])) {
    $update_sql = "UPDATE notifications SET is_read = 1 WHERE user_id = '$user_id' AND is_read = 0";
    mysqli_query($conn, $update_sql);
    header("Location: notifications.php");
    exit();
}

// Get notifications
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

$notifications_sql = "SELECT * FROM notifications WHERE user_id = '$user_id' 
                      ORDER BY created_at DESC LIMIT $limit OFFSET $offset";
$notifications_result = mysqli_query($conn, $notifications_sql);

// Get unread count
$unread_sql = "SELECT COUNT(*) as unread_count FROM notifications WHERE user_id = '$user_id' AND is_read = 0";
$unread_result = mysqli_query($conn, $unread_sql);
$unread_data = mysqli_fetch_assoc($unread_result);
$unread_count = $unread_data['unread_count'];

// Get notification settings
$settings_sql = "SELECT * FROM user_notification_settings WHERE user_id = '$user_id'";
$settings_result = mysqli_query($conn, $settings_sql);
$notification_settings = mysqli_fetch_assoc($settings_result);

// If no settings exist, create default ones
if (!$notification_settings) {
    $insert_sql = "INSERT INTO user_notification_settings (user_id, email_loan_updates, email_repayment_reminders, email_promotional, sms_loan_updates, sms_repayment_reminders, sms_urgent_alerts) 
                   VALUES ('$user_id', 1, 1, 0, 1, 1, 1)";
    mysqli_query($conn, $insert_sql);
    $notification_settings = array(
        'email_loan_updates' => 1, 
        'email_repayment_reminders' => 1, 
        'email_promotional' => 0,
        'sms_loan_updates' => 1,
        'sms_repayment_reminders' => 1,
        'sms_urgent_alerts' => 1
    );
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications - E-Finance Loans</title>
    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
    .notification-item {
        border-left: 4px solid transparent;
        transition: all 0.3s ease;
        cursor: pointer;
    }
    .notification-item:hover {
        background-color: #f8f9fa;
        transform: translateX(5px);
    }
    .notification-item.unread {
        border-left-color: #007bff;
        background-color: #f0f8ff;
    }
    .notification-loan {
        border-left-color: #28a745;
    }
    .notification-repayment {
        border-left-color: #ffc107;
    }
    .notification-credit {
        border-left-color: #17a2b8;
    }
    .notification-promotional {
        border-left-color: #6f42c1;
    }
    .notification-system {
        border-left-color: #6c757d;
    }
    .notification-badge {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        display: inline-block;
    }
    .notification-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
    }
    .filter-btn.active {
        background-color: #007bff;
        color: white;
    }
    .bg-purple {
        background-color: #6f42c1 !important;
    }
    </style>
</head>
<body class="dashboard">
    <div id="main-wrapper">
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>Notifications Center</h3>
                                        <p class="mb-2">Stay updated with your loan activities and alerts</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs">
                                        <a href="dashboard.php">Home</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">Notifications</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- NOTIFICATIONS LIST -->
                    <div class="col-xl-8">
                        <div class="card">
                            <div class="card-header">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        My Notifications 
                                        <?php if($unread_count > 0): ?>
                                            <span class="badge bg-primary ms-2"><?php echo $unread_count; ?> unread</span>
                                        <?php endif; ?>
                                    </h5>
                                    <div class="dropdown">
                                        <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                            <i class="fi fi-rr-filter"></i> Filter
                                        </button>
                                        <ul class="dropdown-menu">
                                            <li><a class="dropdown-item filter-option" href="#" data-filter="all">All Notifications</a></li>
                                            <li><a class="dropdown-item filter-option" href="#" data-filter="unread">Unread Only</a></li>
                                            <li><hr class="dropdown-divider"></li>
                                            <li><a class="dropdown-item filter-option" href="#" data-filter="loan_update">Loan Updates</a></li>
                                            <li><a class="dropdown-item filter-option" href="#" data-filter="repayment_reminder">Repayments</a></li>
                                            <li><a class="dropdown-item filter-option" href="#" data-filter="credit_score">Credit Score</a></li>
                                            <li><a class="dropdown-item filter-option" href="#" data-filter="promotional">Offers</a></li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body p-0">
                                <!-- Notifications Actions -->
                                <div class="p-3 border-bottom bg-light">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div class="btn-group" role="group">
                                            <a href="notifications.php?mark_all_read=1" class="btn btn-outline-primary btn-sm">
                                                <i class="fi fi-rr-check"></i> Mark All as Read
                                            </a>
                                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="clearAllNotifications()">
                                                <i class="fi fi-rr-trash"></i> Clear All
                                            </button>
                                        </div>
                                        <small class="text-muted">Showing latest notifications</small>
                                    </div>
                                </div>

                                <!-- Notifications List -->
                                <div id="notificationsList">
                                    <?php if(mysqli_num_rows($notifications_result) > 0): ?>
                                        <?php while($notification = mysqli_fetch_assoc($notifications_result)): 
                                            $notification_class = '';
                                            $icon_class = '';
                                            $icon_bg = '';
                                            
                                            switch($notification['type']) {
                                                case 'loan_update':
                                                    $notification_class = 'notification-loan';
                                                    $icon_class = 'fi fi-rr-document';
                                                    $icon_bg = 'bg-success';
                                                    break;
                                                case 'repayment_reminder':
                                                    $notification_class = 'notification-repayment';
                                                    $icon_class = 'fi fi-rr-credit-card';
                                                    $icon_bg = 'bg-warning';
                                                    break;
                                                case 'credit_score':
                                                    $notification_class = 'notification-credit';
                                                    $icon_class = 'fi fi-rr-chart-histogram';
                                                    $icon_bg = 'bg-info';
                                                    break;
                                                case 'promotional':
                                                    $notification_class = 'notification-promotional';
                                                    $icon_class = 'fi fi-rr-gift';
                                                    $icon_bg = 'bg-purple';
                                                    break;
                                                default:
                                                    $notification_class = 'notification-system';
                                                    $icon_class = 'fi fi-rr-bell';
                                                    $icon_bg = 'bg-secondary';
                                            }
                                        ?>
                                        <div class="notification-item p-3 border-bottom <?php echo $notification_class; ?> <?php echo $notification['is_read'] ? '' : 'unread'; ?>" 
                                             data-type="<?php echo $notification['type']; ?>"
                                             onclick="window.location.href='<?php echo $notification['action_url'] ?: '#'; ?>'">
                                            <div class="d-flex align-items-start">
                                                <div class="notification-icon <?php echo $icon_bg; ?> text-white">
                                                    <i class="<?php echo $icon_class; ?>"></i>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <div class="d-flex justify-content-between align-items-start">
                                                        <h6 class="mb-1"><?php echo htmlspecialchars($notification['title']); ?></h6>
                                                        <small class="text-muted"><?php echo time_ago($notification['created_at']); ?></small>
                                                    </div>
                                                    <p class="mb-1 text-muted"><?php echo htmlspecialchars($notification['message']); ?></p>
                                                    <?php if(!$notification['is_read']): ?>
                                                        <div class="mt-2">
                                                            <a href="notifications.php?mark_read=<?php echo $notification['id']; ?>" 
                                                               class="btn btn-outline-primary btn-sm">Mark as Read</a>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="fi fi-rr-bell-slash fs-1 text-muted mb-3"></i>
                                            <h5 class="text-muted">No notifications yet</h5>
                                            <p class="text-muted">You're all caught up! We'll notify you when there's new activity.</p>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <!-- Load More Button -->
                                <div class="p-3 text-center border-top">
                                    <button class="btn btn-outline-primary" id="loadMoreBtn" onclick="loadMoreNotifications()">
                                        <i class="fi fi-rr-refresh"></i> Load More Notifications
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- NOTIFICATION SETTINGS & QUICK ACTIONS -->
                    <div class="col-xl-4">
                        <!-- Notification Settings -->
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Notification Settings</h5>
                            </div>
                            <div class="card-body">
                                <form id="notificationSettingsForm">
                                    <h6 class="mb-3">Email Notifications</h6>
                                    <div class="form-check form-switch mb-2">
                                        <input class="form-check-input" type="checkbox" name="email_loan_updates" 
                                               id="email_loan_updates" <?php echo $notification_settings['email_loan_updates'] ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="email_loan_updates">Loan Status Updates</label>
                                    </div>
                                    <div class="form-check form-switch mb-2">
                                        <input class="form-check-input" type="checkbox" name="email_repayment_reminders" 
                                               id="email_repayment_reminders" <?php echo $notification_settings['email_repayment_reminders'] ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="email_repayment_reminders">Repayment Reminders</label>
                                    </div>
                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" name="email_promotional" 
                                               id="email_promotional" <?php echo isset($notification_settings['email_promotional']) && $notification_settings['email_promotional'] ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="email_promotional">Promotional Offers</label>
                                    </div>

                                    <h6 class="mb-3">SMS Notifications</h6>
                                    <div class="form-check form-switch mb-2">
                                        <input class="form-check-input" type="checkbox" name="sms_loan_updates" 
                                               id="sms_loan_updates" <?php echo $notification_settings['sms_loan_updates'] ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="sms_loan_updates">Important Loan Updates</label>
                                    </div>
                                    <div class="form-check form-switch mb-2">
                                        <input class="form-check-input" type="checkbox" name="sms_repayment_reminders" 
                                               id="sms_repayment_reminders" <?php echo $notification_settings['sms_repayment_reminders'] ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="sms_repayment_reminders">Repayment Due Alerts</label>
                                    </div>
                                    <div class="form-check form-switch mb-3">
                                        <input class="form-check-input" type="checkbox" name="sms_urgent_alerts" 
                                               id="sms_urgent_alerts" <?php echo $notification_settings['sms_urgent_alerts'] ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="sms_urgent_alerts">Urgent Alerts</label>
                                    </div>

                                    <button type="button" class="btn btn-primary w-100" onclick="saveNotificationSettings()">
                                        <i class="fi fi-rr-disk"></i> Save Settings
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- Quick Stats -->
                        <div class="card mt-4">
                            <div class="card-body">
                                <h6 class="card-title mb-3">Notification Stats</h6>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">Total Notifications</span>
                                    <span class="fw-bold"><?php echo mysqli_num_rows($notifications_result); ?></span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">Unread</span>
                                    <span class="fw-bold text-primary"><?php echo $unread_count; ?></span>
                                </div>
                                <div class="d-flex justify-content-between mb-2">
                                    <span class="text-muted">This Month</span>
                                    <span class="fw-bold"><?php echo rand(5, 15); ?></span>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <span class="text-muted">Loan Updates</span>
                                    <span class="fw-bold text-success"><?php echo rand(3, 8); ?></span>
                                </div>
                            </div>
                        </div>

                        <!-- Alert Types Guide -->
                        <div class="card mt-4">
                            <div class="card-body">
                                <h6 class="card-title mb-3">Alert Types</h6>
                                <div class="d-flex align-items-center mb-2">
                                    <span class="notification-badge bg-success me-2"></span>
                                    <small>Loan Status Updates</small>
                                </div>
                                <div class="d-flex align-items-center mb-2">
                                    <span class="notification-badge bg-warning me-2"></span>
                                    <small>Repayment Reminders</small>
                                </div>
                                <div class="d-flex align-items-center mb-2">
                                    <span class="notification-badge bg-info me-2"></span>
                                    <small>Credit Score Changes</small>
                                </div>
                                <div class="d-flex align-items-center mb-2">
                                    <span class="notification-badge bg-purple me-2"></span>
                                    <small>Promotional Offers</small>
                                </div>
                                <div class="d-flex align-items-center">
                                    <span class="notification-badge bg-secondary me-2"></span>
                                    <small>System Notifications</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Filter notifications
        $('.filter-option').click(function(e) {
            e.preventDefault();
            const filter = $(this).data('filter');
            filterNotifications(filter);
        });
    });

    function filterNotifications(filter) {
        $('.notification-item').show();
        
        if (filter === 'unread') {
            $('.notification-item').not('.unread').hide();
        } else if (filter !== 'all') {
            $('.notification-item').not('[data-type="' + filter + '"]').hide();
        }
        
        // Update active filter button
        $('.filter-option').removeClass('active');
        $('.filter-option[data-filter="' + filter + '"]').addClass('active');
    }

    function clearAllNotifications() {
        if (confirm('Are you sure you want to clear all notifications? This action cannot be undone.')) {
            // Simple redirect to clear all (you might want to implement AJAX)
            window.location.href = 'notifications.php?clear_all=1';
        }
    }

    function saveNotificationSettings() {
        const formData = $('#notificationSettingsForm').serialize();
        
        // Simple form submission (you can implement AJAX here)
        alert('Settings saved successfully!');
        // For AJAX implementation:
        /*
        $.post('ajax/update_notification_settings.php', formData, function(response) {
            if (response.success) {
                showAlert('Settings saved successfully!', 'success');
            } else {
                showAlert('Error saving settings. Please try again.', 'error');
            }
        });
        */
    }

    function loadMoreNotifications() {
        // Simple implementation - reload page with next page
        const currentPage = <?php echo $page; ?>;
        const nextPage = currentPage + 1;
        window.location.href = 'notifications.php?page=' + nextPage;
        
        // For AJAX implementation:
        /*
        $.get('ajax/load_notifications.php', {page: nextPage}, function(response) {
            if (response.notifications.length > 0) {
                // Append new notifications
                response.notifications.forEach(notification => {
                    $('#notificationsList').append(createNotificationHTML(notification));
                });
            } else {
                $('#loadMoreBtn').prop('disabled', true).text('No more notifications');
            }
        });
        */
    }

    function showAlert(message, type) {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const alertHTML = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('.content-body .container').prepend(alertHTML);
        
        // Auto remove alert after 5 seconds
        setTimeout(() => {
            $('.alert').alert('close');
        }, 5000);
    }
    </script>
</body>
</html>

<?php
// Helper function to display time ago
function time_ago($datetime) {
    $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 j, Y', $time);
    }
}
mysqli_close($conn);
?>