<?php

namespace App\Http\Controllers\Admin\Badge;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Badge\BadgeRequest;
use App\Models\Badge;
use App\Services\ModalIndexQuey;
use App\Services\Quiz\BadgeService;
use Illuminate\Support\Facades\Cache;

class BadgeController extends Controller
{
    public function index()
    {
        adminUserHasPermission(permission: 'read');

        $badges = ModalIndexQuey::get(Badge::query());

        $columns = [
            [
                'label' => __('Title'),
                'key' => 'title',
                'header_class' => 'lg:w-[350px]',
            ],
            [
                'label' => __('Image'),
                'key' => 'image',
                'render' => function ($badge) {
                    return $badge->icon
                        ? '<img src="'.asset($badge->icon).'" alt="'.$badge->title.'" class="w-16 h-16 object-cover rounded-md">'
                        : '<span class="text-gray-500">'.__('No Image').'</span>';
                },
            ],
            [
                'label' => __('Criteria Type'),
                'key' => 'criteria',
                'render' => function ($badge) {
                    $criteria = is_array($badge->criteria)
                        ? $badge->criteria
                        : json_decode($badge->criteria, true);
                    if (! $criteria) {
                        return '<span class="text-gray-500">'.__('No Criteria').'</span>';
                    }

                    return '<div><strong>'.'</strong> '.e(snackCaseToNormalWord($criteria['type'] ?? '-')).'</div>';
                },
            ],
            [
                'label' => __('Criteria Value'),
                'key' => 'criteria',
                'render' => function ($badge) {
                    $criteria = is_array($badge->criteria)
                        ? $badge->criteria
                        : json_decode($badge->criteria, true);
                    if (! $criteria) {
                        return '<span class="text-gray-500">'.__('No Criteria').'</span>';
                    }

                    return '<strong>'.'</strong> '.e($criteria['value'] ?? '-').'</div>';
                },
            ],
            [
                'label' => __('Status'),
                'key' => 'status',
                'render' => function ($badge) {
                    return '<span class="status '.$badge->status->color().'">'.__($badge->status->label()).'</span>';
                },
            ],
            [
                'label' => __('Action'),
                'render' => function ($badge) {
                    $action_buttons = [
                        [
                            'label' => __('Edit'),
                            'icon' => 'ph ph-pencil',
                            'type' => 'link',
                            'href' => route('admin.badges.edit', $badge->id),
                        ],
                        [
                            'label' => __('Show'),
                            'icon' => 'ph ph-eye',
                            'type' => 'link',
                            'href' => route('admin.badges.show', $badge->id),
                        ],
                        [
                            'label' => __('User'),
                            'icon' => 'ph ph-user',
                            'type' => 'link',
                            'href' => route('admin.badge-users', $badge->id),
                        ],
                        [
                            'label' => __('Delete'),
                            'icon' => 'ph ph-trash',
                            'type' => 'delete',
                            'href' => route('admin.badges.destroy', $badge->id),
                        ],
                    ];

                    return view('admin.components.table-action', compact('action_buttons'))->render();
                },
            ],
        ];

        return view('admin.pages.badges.index', compact('badges', 'columns'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(BadgeRequest $request)
    {
        adminUserHasPermission(permission: 'create');

        Badge::create($request->badgeValidated());

        Cache::forget('badge_list');

        return response()->json([
            'message' => __('Badge was successfully created'),
            'redirect' => route('admin.badges.index'),
        ]);
    }

    public function edit(Badge $badge)
    {
        adminUserHasPermission(permission: 'edit');

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-clockwise',
                'type' => 'link',
                'link' => route('admin.badges.index'),
            ],
        ];

        $criteriaTypes = BadgeService::getCriteriaWithDescriptions();

        return view('admin.pages.badges.edit', compact('badge', 'buttons', 'criteriaTypes'));
    }

    public function update(BadgeRequest $request, Badge $badge)
    {
        adminUserHasPermission(permission: 'edit');

        $badge->update($request->validated());

        Cache::forget('badge_list');

        return response()->json([
            'message' => __('Badge was successfully updated'),
            'reload' => true,
        ]);
    }

    /**
     * Show the specified resource in storage.
     */
    public function show(Badge $badge)
    {
        adminUserHasPermission(permission: 'read');

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-clockwise',
                'type' => 'link',
                'link' => route('admin.badges.index'),
            ],
        ];

        $criteriaTypes = BadgeService::getCriteriaTypes();

        return view('admin.pages.badges.show', compact('badge', 'buttons', 'criteriaTypes'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Badge $badge)
    {
        adminUserHasPermission(permission: 'delete');

        $badge->delete();

        Cache::forget('badge_list');

        return response()->json([
            'message' => __('Badge was successfully deleted'),
            'reload' => true,
        ]);
    }

    public function badgeUsers(Badge $badge)
    {

        adminUserHasPermission(permission: 'read');

        $badge_users = $badge->users()->withPivot('earned_at')->paginate(15);

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-clockwise',
                'type' => 'link',
                'link' => route('admin.badges.index'),
            ],
        ];

        $columns = [
            [
                'label' => __('Name'),
                'key' => 'fullname',
            ],
            [
                'label' => __('Email'),
                'key' => 'email',
            ],
            [
                'label' => __('Earned At'),
                'key' => 'earned_at',
                'render' => function ($user) {
                    return $user->pivot->earned_at ?? '-';
                },
            ],
        ];

        return view('admin.pages.badges.users.index', compact('badge_users', 'columns', 'buttons'));
    }
}
