<?php
session_start();
include 'layouts/dbconn.php';
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Not logged in']);
    exit();
}
$user_id = $_SESSION['user_id'];
// Handle POST request with JSON data
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['action']) && isset($data['notifications']) && is_array($data['notifications'])) {
    $notifications = array_map('intval', $data['notifications']);
    
    if (count($notifications) > 0) {
        $notification_ids = implode(',', $notifications);
        
        if ($data['action'] === 'delete') {
            // Delete selected notifications
            $delete_notif_sql = "DELETE FROM notifications WHERE id IN ($notification_ids)";
            $delete_notif_result = $conn->query($delete_notif_sql);
            
            // Delete selected messages
            $delete_msg_sql = "DELETE FROM messages WHERE id IN ($notification_ids) AND receiver_id = $user_id";
            $delete_msg_result = $conn->query($delete_msg_sql);
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => ($delete_notif_result || $delete_msg_result),
                'deleted' => count($notifications)
            ]);
            exit();
        } 
        elseif ($data['action'] === 'mark_read') {
            // Mark selected notifications as read
            $mark_notif_sql = "UPDATE notifications SET is_read = 1 WHERE id IN ($notification_ids)";
            $mark_notif_result = $conn->query($mark_notif_sql);
            
            // Mark selected messages as read
            $mark_msg_sql = "UPDATE messages SET is_read = 1 WHERE id IN ($notification_ids) AND receiver_id = $user_id";
            $mark_msg_result = $conn->query($mark_msg_sql);
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => ($mark_notif_result || $mark_msg_result),
                'marked_read' => count($notifications)
            ]);
            exit();
        }
        elseif ($data['action'] === 'mark_all_read') {
            // Mark all notifications as read for this user
            $mark_all_notif_sql = "UPDATE notifications SET is_read = 1 WHERE file_id IN (SELECT id FROM files)";
            $mark_all_notif_result = $conn->query($mark_all_notif_sql);
            
            // Mark all messages as read for this user
            $mark_all_msg_sql = "UPDATE messages SET is_read = 1 WHERE receiver_id = $user_id";
            $mark_all_msg_result = $conn->query($mark_all_msg_sql);
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => ($mark_all_notif_result || $mark_all_msg_result),
                'all_marked_read' => true
            ]);
            exit();
        }
    }
}

// Handle GET request to fetch notifications
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Get notifications
    $notifications_sql = "SELECT n.*, f.file_number 
                        FROM notifications n 
                        LEFT JOIN files f ON n.file_id = f.id 
                        ORDER BY n.created_at DESC 
                        LIMIT 50";
    $notifications_result = $conn->query($notifications_sql);
    
    // Get unread messages
    $messages_sql = "SELECT m.*, u.username as sender_name, u.full_name as sender_full_name 
                   FROM messages m 
                   JOIN users u ON m.sender_id = u.user_id 
                   WHERE m.receiver_id = $user_id AND m.is_read = 0 
                   ORDER BY m.created_at DESC";
    $messages_result = $conn->query($messages_sql);
    
    $notifications = [];
    $unread_count = 0;
    
    // Process file notifications
    if ($notifications_result && $notifications_result->num_rows > 0) {
        while ($row = $notifications_result->fetch_assoc()) {
            $notifications[] = [
                'id' => $row['id'],
                'type' => 'file',
                'message' => $row['notif_message'],
                'file_number' => $row['file_number'],
                'is_read' => $row['is_read'] == 1,
                'created_at' => $row['created_at'],
                'url' => 'view_file.php?file_number=' . $row['file_number']
            ];
            
            if ($row['is_read'] == 0) {
                $unread_count++;
            }
        }
    }
    
    // Process message notifications
    if ($messages_result && $messages_result->num_rows > 0) {
        while ($row = $messages_result->fetch_assoc()) {
            $sender_name = !empty($row['sender_full_name']) ? $row['sender_full_name'] : $row['sender_name'];
            $message_preview = substr($row['message'], 0, 50) . (strlen($row['message']) > 50 ? '...' : '');
            
            $notifications[] = [
                'id' => $row['id'],
                'type' => 'message',
                'message' => "New message from $sender_name: $message_preview",
                'sender_id' => $row['sender_id'],
                'sender_name' => $sender_name,
                'is_read' => $row['is_read'] == 1,
                'created_at' => $row['created_at'],
                'url' => 'chat.php?user=' . $row['sender_id']
            ];
            
            $unread_count++;
        }
    }
    
    // Sort notifications by created_at
    usort($notifications, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'notifications' => $notifications,
        'unread_count' => $unread_count
    ]);
    exit();
}

// If we get here, it means the request is invalid
header('Content-Type: application/json');
echo json_encode(['success' => false, 'error' => 'Invalid request']);
exit();
?>