<?php
require __DIR__ . '/bootstrap.php';

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Database;
use App\Core\Response;

$user = Auth::requireUser();
$pdo = Database::connection();
$input = request_input();
$method = $_SERVER['REQUEST_METHOD'];
$action = $input['action'] ?? 'list';
$userId = (int)$user['id'];

function pyrk_member_notif_tables_ready(PDO $pdo): bool
{
    try {
        $pdo->query('SELECT read_at FROM notifications LIMIT 1');
        return true;
    } catch (Throwable) {
        return false;
    }
}

function pyrk_member_notif_column_exists(PDO $pdo, string $table, string $column): bool
{
    static $cache = [];
    $key = $table . '.' . $column;
    if (array_key_exists($key, $cache)) return $cache[$key];
    try {
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?');
        $stmt->execute([$table, $column]);
        return $cache[$key] = ((int)$stmt->fetchColumn() > 0);
    } catch (Throwable) {
        return $cache[$key] = false;
    }
}

function pyrk_member_notif_table_exists(PDO $pdo, string $table): bool
{
    static $cache = [];
    if (array_key_exists($table, $cache)) return $cache[$table];
    try {
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?');
        $stmt->execute([$table]);
        return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
    } catch (Throwable) {
        return $cache[$table] = false;
    }
}

if (!pyrk_member_notif_tables_ready($pdo)) {
    Response::error('Notification inbox is not installed yet. Please run database/migrations/032_manual_push_notifications.sql');
}

if ($method === 'GET' && $action === 'list') {
    $hasBatchId = pyrk_member_notif_column_exists($pdo, 'notifications', 'batch_id');
    $select = $hasBatchId
        ? 'SELECT id, batch_id, subject, message, status, sent_at, created_at, read_at'
        : 'SELECT id, NULL AS batch_id, subject, message, status, sent_at, created_at, read_at';

    $stmt = $pdo->prepare($select . '
        FROM notifications
        WHERE user_id = ? AND channel = "in_app"
        ORDER BY COALESCE(sent_at, created_at) DESC, id DESC
        LIMIT 120');
    $stmt->execute([$userId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($hasBatchId && $rows && pyrk_member_notif_table_exists($pdo, 'manual_notification_attachments')) {
        $batchIds = array_values(array_unique(array_filter(array_map(static fn($r) => (int)($r['batch_id'] ?? 0), $rows))));
        if ($batchIds) {
            $placeholders = implode(',', array_fill(0, count($batchIds), '?'));
            $att = $pdo->prepare("SELECT batch_id, original_name, file_path, size_bytes FROM manual_notification_attachments WHERE batch_id IN ($placeholders) ORDER BY id ASC");
            $att->execute($batchIds);
            $map = [];
            foreach ($att->fetchAll(PDO::FETCH_ASSOC) as $file) {
                $map[(int)$file['batch_id']][] = $file;
            }
            foreach ($rows as &$row) {
                $row['attachments'] = $map[(int)($row['batch_id'] ?? 0)] ?? [];
            }
            unset($row);
        }
    }

    $countStmt = $pdo->prepare('SELECT COUNT(*) FROM notifications WHERE user_id = ? AND channel = "in_app" AND read_at IS NULL');
    $countStmt->execute([$userId]);

    Response::ok([
        'notifications' => $rows,
        'unread_count' => (int)$countStmt->fetchColumn(),
    ]);
}

if ($method === 'POST' && $action === 'mark_read') {
    Csrf::validateFromRequest();
    $id = (int)($input['id'] ?? 0);
    if ($id <= 0) Response::error('Notification id is required.');

    $stmt = $pdo->prepare('UPDATE notifications SET read_at = COALESCE(read_at, NOW()) WHERE id = ? AND user_id = ? AND channel = "in_app"');
    $stmt->execute([$id, $userId]);

    Response::ok([], 'Notification marked as read.');
}

if ($method === 'POST' && $action === 'mark_unread') {
    Csrf::validateFromRequest();
    $id = (int)($input['id'] ?? 0);
    if ($id <= 0) Response::error('Notification id is required.');

    $stmt = $pdo->prepare('UPDATE notifications SET read_at = NULL WHERE id = ? AND user_id = ? AND channel = "in_app"');
    $stmt->execute([$id, $userId]);

    Response::ok([], 'Notification marked as unread.');
}

if ($method === 'POST' && $action === 'mark_all_unread') {
    Csrf::validateFromRequest();

    $stmt = $pdo->prepare('UPDATE notifications SET read_at = NULL WHERE user_id = ? AND channel = "in_app" AND read_at IS NOT NULL');
    $stmt->execute([$userId]);

    Response::ok(['updated' => $stmt->rowCount()], 'All notifications marked as unread.');
}

if ($method === 'POST' && $action === 'mark_all_read') {
    Csrf::validateFromRequest();

    $stmt = $pdo->prepare('UPDATE notifications SET read_at = COALESCE(read_at, NOW()) WHERE user_id = ? AND channel = "in_app" AND read_at IS NULL');
    $stmt->execute([$userId]);

    Response::ok(['updated' => $stmt->rowCount()], 'All notifications marked as read.');
}

Response::error('Unsupported member notification action.', 404);
