<?php
/**
 * Notifications API
 * Handles notification operations (fetch, mark as read, delete)
 */

header('Content-Type: application/json');
require_once '../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userId = getCurrentUserId();
$method = $_SERVER['REQUEST_METHOD'];

try {
    $db = getDB();
    
    switch ($method) {
        case 'GET':
            // Fetch notifications
            $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
            $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
            $unreadOnly = isset($_GET['unread_only']) && $_GET['unread_only'] === 'true';
            
            $sql = "SELECT * FROM notifications WHERE user_id = ?";
            $params = [$userId];
            
            if ($unreadOnly) {
                $sql .= " AND is_read = 0";
            }
            
            $sql .= " ORDER BY created_at DESC LIMIT ? OFFSET ?";
            $params[] = $limit;
            $params[] = $offset;
            
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            $notifications = $stmt->fetchAll();
            
            // Get unread count
            $stmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
            $stmt->execute([$userId]);
            $unreadCount = $stmt->fetchColumn();
            
            echo json_encode([
                'success' => true,
                'notifications' => $notifications,
                'unread_count' => $unreadCount,
                'total' => count($notifications)
            ]);
            break;
            
        case 'POST':
            // Mark notification as read
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['notification_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Notification ID required']);
                exit;
            }
            
            $notificationId = (int)$data['notification_id'];
            
            // Verify notification belongs to user
            $stmt = $db->prepare("SELECT id FROM notifications WHERE id = ? AND user_id = ?");
            $stmt->execute([$notificationId, $userId]);
            
            if (!$stmt->fetch()) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Notification not found']);
                exit;
            }
            
            // Mark as read
            $stmt = $db->prepare("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ?");
            $stmt->execute([$notificationId]);
            
            echo json_encode(['success' => true, 'message' => 'Notification marked as read']);
            break;
            
        case 'PUT':
            // Mark all notifications as read
            $stmt = $db->prepare("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE user_id = ? AND is_read = 0");
            $stmt->execute([$userId]);
            $affected = $stmt->rowCount();
            
            echo json_encode([
                'success' => true,
                'message' => 'All notifications marked as read',
                'count' => $affected
            ]);
            break;
            
        case 'DELETE':
            // Delete notification
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['notification_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Notification ID required']);
                exit;
            }
            
            $notificationId = (int)$data['notification_id'];
            
            // Verify notification belongs to user
            $stmt = $db->prepare("SELECT id FROM notifications WHERE id = ? AND user_id = ?");
            $stmt->execute([$notificationId, $userId]);
            
            if (!$stmt->fetch()) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Notification not found']);
                exit;
            }
            
            // Delete notification
            $stmt = $db->prepare("DELETE FROM notifications WHERE id = ?");
            $stmt->execute([$notificationId]);
            
            echo json_encode(['success' => true, 'message' => 'Notification deleted']);
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
            break;
    }
    
} catch (Exception $e) {
    error_log("Notifications API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
