<?php

namespace adrienpayet\notifications\providers;

use adrienpayet\notifications\NotificationProvider;
use Kirby\Cms\Page;
use Kirby\Cms\User;
use Kirby\Data\Yaml;

/**
 * Provider pour les notifications de type "content".
 * Dérivé depuis les briefs validés (isValidated = true).
 */
class ContentProvider implements NotificationProvider
{
    public function getType(): string
    {
        return 'content';
    }

    public function collect(Page $project, User $user): array
    {
        $notifications = [];
        $userUuid = (string) $user->uuid();

        // Chercher les briefs validés (client-brief et extended-brief)
        $briefTemplates = ['client-brief', 'extended-brief'];

        foreach ($project->children() as $step) {
            if (!in_array($step->intendedTemplate()->name(), $briefTemplates)) {
                continue;
            }

            // Pas de notification si le brief n'est pas validé
            if ($step->isValidated()->isFalse()) {
                continue;
            }

            // Vérifier que les champs requis existent
            if ($step->validatedBy()->isEmpty()) {
                continue;
            }

            $authorUuid = $step->validatedBy()->value();

            // Ne pas notifier l'auteur de sa propre validation
            if ($authorUuid === $userUuid) {
                continue;
            }

            $readby = $step->validationReadby()->isNotEmpty()
                ? Yaml::decode($step->validationReadby()->value())
                : [];

            if (!is_array($readby)) {
                $readby = [];
            }

            $stepLabel = $step->intendedTemplate()->name() === 'client-brief'
                ? 'Brief client'
                : 'Brief étendu';

            $notification = [
                'id' => 'content-' . (string) $step->uuid(),
                'type' => 'content',
                'text' => 'Nouveau ' . strtolower($stepLabel) . ' validé',
                'author' => [
                    'uuid' => $authorUuid,
                    'name' => $step->validatedByName()->value() ?? '',
                    'email' => $step->validatedByEmail()->value() ?? '',
                    'role' => 'client',
                ],
                'date' => $step->validatedAt()->value() ?? '',
                'location' => [
                    'page' => [
                        'uri' => $step->uri(),
                        'title' => (string) $step->title(),
                        'template' => $step->intendedTemplate()->name(),
                    ],
                    'project' => [
                        'uri' => $project->uri(),
                        'title' => (string) $project->title(),
                    ]
                ],
                'readby' => $readby,
                'isRead' => in_array($userUuid, $readby),
                '_briefUri' => $step->uri(),
            ];

            // Ajouter le dialogUri si présent (validation depuis PDF)
            if ($step->validationDialogUri()->isNotEmpty()) {
                $notification['dialogUri'] = $step->validationDialogUri()->value();
            }

            $notifications[] = $notification;
        }

        return $notifications;
    }

    public function markAsRead(string $id, array $location, User $user): bool
    {
        $briefUri = $location['_briefUri'] ?? null;
        if (!$briefUri) {
            return false;
        }

        $brief = page($briefUri);
        if (!$brief) {
            return false;
        }

        $readby = $brief->validationReadby()->isNotEmpty()
            ? Yaml::decode($brief->validationReadby()->value())
            : [];

        if (!is_array($readby)) {
            $readby = [];
        }

        $userUuid = (string) $user->uuid();

        if (in_array($userUuid, $readby)) {
            return true;
        }

        $readby[] = $userUuid;

        $brief->update([
            'validationReadby' => array_unique($readby)
        ]);

        return true;
    }
}
