<?php

namespace App\Http\Controllers\Admin\Advertisement;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Advertisement\AdRequest;
use App\Models\Advertisement;
use App\Services\ModalIndexQuey;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;

class AdController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $buttons = [
            [
                'label' => __('Add New Ads'),
                'icon' => 'ph ph-plus',
                'type' => 'link',
                'link' => route('admin.settings.ads.create'),
            ],
        ];

        $ads = ModalIndexQuey::get(model: Advertisement::query());

        $columns = [
            [
                'label' => __('Title'),
                'key' => 'title',
                'header_class' => 'lg:w-[350px]',
            ],
            [
                'label' => __('Position'),
                'key' => 'position',
                'render' => fn ($ad) => $ad->position->label(),
            ],
            [
                'label' => __('Type'),
                'key' => 'type',
                'render' => fn ($ad) => $ad->type->label(),
            ],
            [
                'label' => __('Status'),
                'key' => 'status',
                'render' => function ($ad) {
                    return '<span class="status '.$ad->status->color().'">'.$ad->status->label().'</span>';
                },
                'is_sortable' => true,
            ],
            [
                'label' => __('Action'),
                'render' => function ($ad) {
                    $action_buttons = [

                        [
                            'label' => __('Edit'),
                            'icon' => 'ph ph-pencil',
                            'type' => 'link',
                            'href' => route('admin.settings.ads.edit', $ad->id),
                        ],
                        [
                            'label' => $ad->status === \App\Enums\AdsStatusEnum::ACTIVE ? __('Inactive') : __('Active'),
                            'icon' => 'ph ph-swap',
                            'type' => 'link',
                            'href' => route('admin.settings.ads.toggle-status', $ad->id),
                        ],
                        [
                            'label' => __('Delete'),
                            'icon' => 'ph ph-trash',
                            'type' => 'delete',
                            'href' => route('admin.settings.ads.destroy', $ad->id),
                        ],
                    ];

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

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

    public function store(AdRequest $request)
    {
        $validated = $request->validated();

        $same_position_exists = Advertisement::where('position', $validated['position'])->where('status', \App\Enums\AdsStatusEnum::ACTIVE)->exists();

        if ($same_position_exists) {
            throw ValidationException::withMessages(['position' => __('Same position already exists. Please choose another position or deactivate the existing ad')]);
        }

        Advertisement::create($validated);

        Cache::forget('ads_list');

        return response()->json([
            'message' => __('Ads created successfully'),
            'redirect' => route('admin.settings.ads.index'),
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-left',
                'type' => 'link',
                'link' => route('admin.settings.ads.index'),
            ],
        ];

        return view('admin.pages.settings.ads.create', compact('buttons'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Advertisement $ad)
    {
        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-left',
                'type' => 'link',
                'link' => route('admin.settings.ads.index'),
            ],
        ];

        return view('admin.pages.settings.ads.edit', compact('ad', 'buttons'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(AdRequest $request, Advertisement $ad)
    {
        $validated = $request->validated();

        $same_position_exists = Advertisement::where('position', $validated['position'])
            ->where('status', \App\Enums\AdsStatusEnum::ACTIVE)
            ->where('id', '!=', $ad->id)
            ->exists();

        if ($same_position_exists) {
            throw ValidationException::withMessages(['position' => __('Same position already exists. Please choose another position or deactivate the existing ad')]);
        }

        $ad->update($validated);

        Cache::forget('ads_list');

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

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Advertisement $ad)
    {
        $ad->delete();

        Cache::forget('ads_list');

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

    /**
     * Toggle the status of the specified resource.
     */
    public function toggleStatus(Advertisement $ad)
    {
        $newStatus = $ad->status === \App\Enums\AdsStatusEnum::INACTIVE
            ? \App\Enums\AdsStatusEnum::ACTIVE
            : \App\Enums\AdsStatusEnum::INACTIVE;

        $ad->update(['status' => $newStatus]);

        Cache::forget('ads_list');

        return back()->withSuccess(__('Ads status updated successfully'));
    }
}
