<?php

namespace App\Support;

use App\Models\Attachment;
use App\Models\User;

class PortalViewData
{
    public function forFrontHeader(?User $user): array
    {
        return [
            'portalStudent' => $user,
            'portalWalletAmount' => (float) ($user?->wallet?->walletamount ?? 0),
            'portalProfileImageUrl' => $this->attachmentUrl(
                (int) ($user?->profileimh ?? 0),
                ASSETURL.'public/frontend/images/userrank.png'
            ),
        ];
    }

    public function forAdminHeader(?User $user): array
    {
        return [
            'adminHeaderProfileUrl' => $this->adminProfileUrl($user),
            'adminHeaderImageUrl' => $this->attachmentUrl(
                (int) ($user?->profileimh ?? 0),
                ASSETURL.'public/frontend/images/logo.png'
            ),
            'adminHeaderRoleLabel' => $this->adminRoleLabel($user),
            'adminLogoutRoute' => $this->adminLogoutRoute($user),
            'adminLogoutFormId' => $this->adminLogoutFormId($user),
        ];
    }

    public function forAdminLayout(?User $user): array
    {
        return [
            'adminSidebarView' => $this->adminSidebarView($user),
        ];
    }

    private function attachmentUrl(int $attachmentId, string $fallbackUrl): string
    {
        if ($attachmentId <= 0) {
            return $fallbackUrl;
        }

        $attachment = Attachment::query()->find($attachmentId);

        return $attachment ? ASSETURL.'files/'.$attachment->att_url : $fallbackUrl;
    }

    private function adminProfileUrl(?User $user): string
    {
        if (! $user) {
            return route('welcome');
        }

        return match ((int) ($user->usertype ?? 0)) {
            1 => route('admin.instituteprofile'),
            3 => route('admin.editschoolprofile', ['id' => $user->id]),
            default => route('admin.changepassword', ['userid' => $user->id]),
        };
    }

    private function adminRoleLabel(?User $user): string
    {
        return match ((int) ($user?->usertype ?? 0)) {
            1 => 'Institute',
            3 => 'School',
            default => 'Administrator',
        };
    }

    private function adminLogoutRoute(?User $user): string
    {
        return in_array((int) ($user?->usertype ?? 0), [1, 3], true)
            ? route('institutelogout')
            : route('logout');
    }

    private function adminLogoutFormId(?User $user): string
    {
        return in_array((int) ($user?->usertype ?? 0), [1, 3], true)
            ? 'portal-institute-logout-form'
            : 'portal-admin-logout-form';
    }

    private function adminSidebarView(?User $user): string
    {
        return match ((int) ($user?->usertype ?? 0)) {
            1 => 'include.intsidebar',
            3 => 'include.schoolsidebar',
            default => 'include.sidebar',
        };
    }
}
