<?php
/**
 * API de Notificações - MontaLoja
 */
require_once __DIR__ . '/../includes/config.php';

header('Content-Type: application/json');

// Verificar autenticação
if (!isset($_SESSION['user_id']) || !isset($_SESSION['store_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Não autorizado']);
    exit;
}

$storeId = $_SESSION['store_id'];
$pdo = getDB();

// GET - Listar notificações
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $limit = min((int)($_GET['limit'] ?? 20), 50);
    $offset = (int)($_GET['offset'] ?? 0);
    $unreadOnly = isset($_GET['unread']);
    
    $where = "store_id = ?";
    $params = [$storeId];
    
    if ($unreadOnly) {
        $where .= " AND is_read = 0";
    }
    
    $stmt = $pdo->prepare("
        SELECT * FROM notifications 
        WHERE $where 
        ORDER BY created_at DESC 
        LIMIT ? OFFSET ?
    ");
    $params[] = $limit;
    $params[] = $offset;
    $stmt->execute($params);
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Contar total não lidas
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE store_id = ? AND is_read = 0");
    $countStmt->execute([$storeId]);
    $unreadCount = $countStmt->fetchColumn();
    
    echo json_encode([
        'success' => true,
        'notifications' => $notifications,
        'unread_count' => (int)$unreadCount
    ]);
    exit;
}

// POST - Ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $action = $data['action'] ?? '';
    
    switch ($action) {
        case 'mark_read':
            $id = (int)($data['id'] ?? 0);
            if ($id) {
                $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE id = ? AND store_id = ?");
                $stmt->execute([$id, $storeId]);
            }
            echo json_encode(['success' => true]);
            break;
            
        case 'mark_all_read':
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1, read_at = NOW() WHERE store_id = ? AND is_read = 0");
            $stmt->execute([$storeId]);
            echo json_encode(['success' => true, 'updated' => $stmt->rowCount()]);
            break;
            
        case 'delete':
            $id = (int)($data['id'] ?? 0);
            if ($id) {
                $stmt = $pdo->prepare("DELETE FROM notifications WHERE id = ? AND store_id = ?");
                $stmt->execute([$id, $storeId]);
            }
            echo json_encode(['success' => true]);
            break;
            
        case 'clear_all':
            $stmt = $pdo->prepare("DELETE FROM notifications WHERE store_id = ?");
            $stmt->execute([$storeId]);
            echo json_encode(['success' => true, 'deleted' => $stmt->rowCount()]);
            break;
            
        default:
            http_response_code(400);
            echo json_encode(['error' => 'Ação inválida']);
    }
    exit;
}

http_response_code(405);
echo json_encode(['error' => 'Método não permitido']);
