<?php
namespace App\Support;

use App\Models\{ItemRequest, ApprovalStepTemplate, User};
use App\Notifications\ApprovalEventNotification;

class ApprovalNotifier
{
    public static function urlFor(ItemRequest $req): string
    {
        return route('approvals.show', $req->id);
    }

    public static function notifyCurrentApprovers(ItemRequest $req, string $event, string $actorName)
    {
        $step = ApprovalStepTemplate::where('flow_template_id', $req->flow_template_id)
            ->where('step_no', $req->current_step_no)->first();

        if (!$step) return;

        $targets = collect();

        if ($step->relationLoaded('approvers') ? $step->approvers->isNotEmpty() : $step->approvers()->exists()) {
            foreach ($step->approvers as $ap) {
                if ($ap->approver_user_id && $ap->user) {
                    $targets->push($ap->user);
                }
                if ($ap->approver_role_id) {
                    $users = User::where('role_id', $ap->approver_role_id)->get();
                    if ($users->isNotEmpty()) $targets = $targets->merge($users);
                }
            }
        } else {
            // fallback to legacy single-column approach
            if ($step->approver_user_id && $user = User::find($step->approver_user_id)) {
                $targets->push($user);
            }
            if ($step->approver_role_id) {
                $roleUsers = User::where('role_id', $step->approver_role_id)->get();
                $targets = $targets->merge($roleUsers);
            }
        }

        if ($targets->isEmpty()) return;

        $payload = [
            'request_id' => $req->id,
            'number'     => $req->number ?? $req->id,
            'status'     => $req->status,
            'actor'      => $actorName,
            'title'      => "Approval requested for #".($req->number ?? $req->id),
            'url'        => self::urlFor($req),
            'vendor'     => $req->vendor_name ?: '—',
            'requester'  => optional($req->requester)->name ?: optional($req->requester)->email ?: '—',
            'remarks'    => $req->remarks ?: '—',
            'posting'    => optional($req->posting_date)->format('Y-m-d') ?: '—',
        ];

        foreach ($targets->unique('id') as $u) {
            $u->notify(new ApprovalEventNotification($event, $payload));
        }
    }

    public static function notifyUser(User $user, ItemRequest $req, string $event, string $title, string $actorName)
    {
        $payload = [
            'request_id' => $req->id,
            'number'     => $req->number ?? $req->id,
            'status'     => $req->status,
            'actor'      => $actorName,
            'title'      => $title,
            'url'        => self::urlFor($req),
            'vendor'     => $req->vendor_name ?: '—',
            'requester'  => optional($req->requester)->name ?: optional($req->requester)->email ?: '—',
            'remarks'    => $req->remarks ?: '—',
            'posting'    => optional($req->posting_date)->format('Y-m-d') ?: '—',
        ];
        $user->notify(new ApprovalEventNotification($event, $payload));
    }
}