<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = ['success' => false, 'message' => '', 'notifications' => [], 'total_pages' => 1, 'page' => 1];

if (!isLoggedIn()) {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

$user = getCurrentUser();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['message'] = "Security check failed (CSRF). Please try again.";
        echo json_encode($response);
        exit();
    }

    $action = $_POST['action'] ?? '';
    
    if ($action === 'read_all') {
        try {
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = TRUE WHERE user_id = ? AND channels_sent LIKE '%in_app%'");
            $stmt->execute([$user['id']]);
            $response['success'] = true;
            $response['message'] = "All notifications marked as read.";
        } catch (PDOException $e) {
            $response['message'] = "Failed to update notifications.";
        }
    } elseif ($action === 'delete') {
        $notifId = (int)($_POST['id'] ?? 0);
        try {
            $stmt = $pdo->prepare("DELETE FROM notifications WHERE id = ? AND user_id = ?");
            $stmt->execute([$notifId, $user['id']]);
            $response['success'] = true;
            $response['message'] = "Notification deleted successfully.";
        } catch (PDOException $e) {
            $response['message'] = "Failed to delete notification.";
        }
    }
} else {
    // GET requests return notification logs
    try {
        $limit = isset($_GET['limit']) ? min(50, max(1, (int)$_GET['limit'])) : 10;
        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $offset = ($page - 1) * $limit;

        $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND channels_sent LIKE '%in_app%'");
        $stmt_count->execute([$user['id']]);
        $total_records = (int)$stmt_count->fetchColumn();
        $total_pages = ceil($total_records / $limit);

        $stmt = $pdo->prepare("
            SELECT * FROM notifications 
            WHERE user_id = ? AND channels_sent LIKE '%in_app%' 
            ORDER BY created_at DESC 
            LIMIT ? OFFSET ?
        ");
        $stmt->bindValue(1, $user['id'], PDO::PARAM_INT);
        $stmt->bindValue(2, $limit, PDO::PARAM_INT);
        $stmt->bindValue(3, $offset, PDO::PARAM_INT);
        $stmt->execute();
        
        $response['notifications'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $response['total_pages'] = max(1, $total_pages);
        $response['page'] = $page;
        $response['success'] = true;
    } catch (PDOException $e) {
        $response['message'] = "Database error: " . $e->getMessage();
    }
}

echo json_encode($response);
