<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_user.php';

apply_cors();
$authUser = require_user();
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];

// GET   /notifications.php            -> list (broadcast + targeted to this user), newest first, with is_read flag
// PATCH /notifications.php?id=5       -> mark one as read
// PATCH /notifications.php?action=read_all -> mark all as read

if ($method === 'GET') {
    $stmt = $pdo->prepare(
        "SELECT n.id, n.title, n.message, n.action_url, n.created_at,
                (r.id IS NOT NULL) AS is_read
         FROM notifications n
         LEFT JOIN notification_reads r ON r.notification_id = n.id AND r.user_email = :email
         WHERE n.target_user_email IS NULL OR n.target_user_email = :email2
         ORDER BY n.created_at DESC
         LIMIT 50"
    );
    $stmt->execute([':email' => $authUser['email'], ':email2' => $authUser['email']]);
    $rows = $stmt->fetchAll();
    foreach ($rows as &$row) {
        $row['is_read'] = (bool) $row['is_read'];
    }

    $unreadCount = count(array_filter($rows, fn($r) => !$r['is_read']));

    send_success(['notifications' => $rows, 'unread_count' => $unreadCount]);
}

if ($method === 'PATCH' && isset($_GET['id'])) {
    $stmt = $pdo->prepare(
        'INSERT IGNORE INTO notification_reads (notification_id, user_email) VALUES (:id, :email)'
    );
    $stmt->execute([':id' => (int) $_GET['id'], ':email' => $authUser['email']]);
    send_success(null, 'Marked as read.');
}

if ($method === 'PATCH' && ($_GET['action'] ?? '') === 'read_all') {
    $ids = $pdo->prepare(
        "SELECT id FROM notifications WHERE target_user_email IS NULL OR target_user_email = :email"
    );
    $ids->execute([':email' => $authUser['email']]);
    $insert = $pdo->prepare('INSERT IGNORE INTO notification_reads (notification_id, user_email) VALUES (:nid, :email)');
    foreach ($ids->fetchAll() as $row) {
        $insert->execute([':nid' => $row['id'], ':email' => $authUser['email']]);
    }
    send_success(null, 'All notifications marked as read.');
}

send_error('Invalid request.', 400);
