<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userRole = $_SESSION['user_role'] ?? '';
$company_id = $_SESSION['company_id'] ?? 0;

if (!$company_id || ($userRole !== 'owner' && $userRole !== 'manager') || !isModuleEnabled('notifications')) {
    echo json_encode(['success' => true, 'data' => []]);
    exit;
}

// Support both JSON POST requests and query params
$data = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $_GET['action'] ?? $data['action'] ?? 'list';

switch ($action) {
    case 'list':
        try {
            $notifications = fetchAll("SELECT id, type, title, message, target_url, created_at FROM system_notifications WHERE company_id = ? AND is_read = 0 ORDER BY created_at DESC", [$company_id]);
            echo json_encode(['success' => true, 'data' => $notifications]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    case 'mark_read':
        try {
            $id = $data['id'] ?? $_GET['id'] ?? null;
            if ($id) {
                query("UPDATE system_notifications SET is_read = 1 WHERE id = ? AND company_id = ?", [$id, $company_id]);
                echo json_encode(['success' => true, 'message' => 'Notification marked as read']);
            } else {
                query("UPDATE system_notifications SET is_read = 1 WHERE company_id = ? AND is_read = 0", [$company_id]);
                echo json_encode(['success' => true, 'message' => 'All notifications marked as read']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
