<?php

namespace App\Http\Controllers\Admin\Contest;

use App\Enums\ContestStatusEnum;
use App\Exceptions\CustomWebException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Contest\ContestRequest;
use App\Models\Contest;
use App\Services\ModalIndexQuey;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class ContestController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        adminUserHasPermission(permission: 'read');

        $buttons = [
            [
                'label' => __('Add New Contest'),
                'icon' => 'ph ph-plus-bold',
                'type' => 'link',
                'link' => route('admin.contests.create'),
            ],
        ];

        $contests = ModalIndexQuey::get(model: Contest::query(), with: ['category:id,title']);

        $columns = [
            [
                'label' => __('Title'),
                'key' => 'translation.title',
                'header_class' => 'lg:w-[350px]',
                'render' => function ($contest) {
                    return Str::limit($contest->translation->title, 30);
                },
            ],
            [
                'label' => __('Category'),
                'key' => 'category.title',
            ],
            [
                'label' => __('Image'),
                'key' => 'image',
                'render' => function ($contest) {
                    return $contest->image
                        ? '<img src="'.asset($contest->image).'" alt="'.$contest->translation->title.'" class="w-16 h-16 object-cover rounded-md">'
                        : '<span class="text-gray-500">'.__('No Image').'</span>';
                },
            ],
            [
                'label' => __('Start Date'),
                'key' => 'start_date',
                'render' => function ($contest) {
                    return Carbon::parse($contest->start_date)->format('d-m-Y');
                },
            ],
            [
                'label' => __('End Date'),
                'key' => 'end_date',
                'render' => function ($contest) {
                    return Carbon::parse($contest->end_date)->format('d-m-Y');
                },
            ],
            [
                'label' => __('Is Free'),
                'key' => 'is_free',
                'render' => function ($contest) {
                    return $contest->is_free ? __('Yes') : __('No');
                },
            ],
            [
                'label' => __('Entry Fee'),
                'key' => 'entry_fee',
            ],
            [
                'label' => __('Participant Limit'),
                'key' => 'participant_limit',
            ],
            [
                'label' => __('Is Featured'),
                'key' => 'is_featured',
                'render' => function ($contest) {
                    return $contest->is_featured ? __('Yes') : __('No');
                },
            ],
            [
                'label' => __('Status'),
                'key' => 'status',
                'render' => function ($contest) {
                    return '<span class="status '.$contest->status->color().'">'.__($contest->status->label()).'</span>';
                },
            ],
            [
                'label' => __('Action'),
                'render' => function ($contest) {
                    $buttons = [];
                    if ($contest->status == ContestStatusEnum::COMPLETED && $contest->winners()->count()) {
                        $buttons[] = [
                            'label' => __('Winners'),
                            'icon' => 'ph ph-trophy',
                            'type' => 'link',
                            'href' => route('admin.winners.index', ['contest_id' => $contest->id]),
                        ];
                    }
                    $action_buttons = [
                        ...$buttons,
                        [
                            'label' => __('Questions'),
                            'icon' => 'ph ph-list',
                            'type' => 'link',
                            'href' => route('admin.contests.questions.index', ['contest' => $contest->id]),
                        ],
                        [
                            'label' => __('Prizes'),
                            'icon' => 'ph ph-list',
                            'type' => 'link',
                            'href' => route('admin.contests.prizes.index', ['contest' => $contest->id]),
                        ],
                        [
                            'label' => __('Edit'),
                            'icon' => 'ph ph-pencil',
                            'type' => 'link',
                            'href' => route('admin.contests.edit', $contest->id),
                        ],
                        [
                            'label' => __($contest->status == ContestStatusEnum::DRAFT ? 'Publish' : 'Unpublish'),
                            'icon' => $contest->status == ContestStatusEnum::DRAFT ? 'ph ph-toggle-right' : 'ph ph-toggle-left',
                            'type' => 'link',
                            'href' => $contest->status == ContestStatusEnum::DRAFT ? route('admin.contests.publish', $contest->id) : route('admin.contests.unpublish', $contest->id),
                        ],
                        [
                            'label' => __('Delete'),
                            'icon' => 'ph ph-trash',
                            'type' => 'delete',
                            'href' => route('admin.contests.destroy', $contest->id),
                        ],
                    ];

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

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

    public function create()
    {
        adminUserHasPermission(permission: 'create');

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

        $categories = \App\Models\ContestCategory::all()->pluck('title', 'id');

        return view('admin.pages.contests.create', compact('buttons', 'categories'));
    }

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

        try {
            DB::beginTransaction();

            $contest = Contest::create([
                ...$request->contestValidated(),
                'status' => ContestStatusEnum::DRAFT,
            ]);

            $contest->translations()->createMany($request->lang);

            DB::commit();
        } catch (\Throwable $th) {
            DB::rollBack();
            throw new CustomWebException($th->getMessage());
        }

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

    public function edit(Contest $contest)
    {
        adminUserHasPermission(permission: 'edit');

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

        $contest->load('translations');

        return view('admin.pages.contests.edit', compact('contest', 'buttons'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(ContestRequest $request, Contest $contest)
    {
        adminUserHasPermission(permission: 'edit');

        if ($contest->status !== ContestStatusEnum::DRAFT) {
            throw new CustomWebException(__('Contest is not in draft status.'));
        }

        try {
            DB::beginTransaction();

            $contest->update($request->contestValidated());

            $contest->translations()->delete();

            $contest->translations()->createMany($request->lang);

            DB::commit();
        } catch (\Throwable $th) {
            DB::rollBack();
            throw new CustomWebException($th->getMessage());
        }

        Cache::forget('contest_list');

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

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

        $contest->delete();

        Cache::forget('contest_list');

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