<?php

namespace App\Http\Controllers\Dashboard\PaymentSystem;

use App\Http\Controllers\Controller as ExController;
use Illuminate\Http\Request;
use App\Models\PaymentSystemModel as PaymentSystem;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class PaymentSystemController extends ExController
{
    public function index(Request $request)
    {
        $paymentSystems = PaymentSystem::latest('id')->paginate(30);

        return view('dashboard.payment-systems.index', compact('paymentSystems'));
    }

    public function create()
    {
        return view('dashboard.payment-systems.create');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'title_uz' => 'required|string',
            'title_ru' => 'required|string',
        ]);

        // generate slug from title_uz
        $slug = Str::slug($request->slug);

        PaymentSystem::create([
            'title' => [
                'uz' => $request->title_uz,
                'ru' => $request->title_ru,
            ],
            'slug' => $slug,
        ]);

        $this->info(trans('admin.messages.created'));
        return redirect()->route('dashboard.payment-systems.index');
    }

    public function edit($systemId)
    {
        $paymentSystem = PaymentSystem::findOrFail($systemId);
        return view('dashboard.payment-systems.edit', compact('paymentSystem'));
    }

    public function update(Request $request, $systemId)
    {
        $paymentSystem = PaymentSystem::findOrFail($systemId);

        $this->validate($request, [
            'title_uz' => 'required|string',
            'title_ru' => 'required|string',
        ]);

        // generate slug from title_uz
        $slug = Str::slug($request->slug);

        $paymentSystem->update([
            'title' => [
                'uz' => $request->title_uz,
                'ru' => $request->title_ru,
            ],
            'slug' => $slug,
        ]);

        $this->info(trans('admin.messages.updated'));
        return redirect()->route('dashboard.payment-systems.index');
    }

    public function destroy($systemId)
    {
        $paymentSystem = PaymentSystem::findOrFail($systemId);

        // delete related items and their logos
        foreach ($paymentSystem->items as $item) {
            Storage::delete($item->logo);
            $item->delete();
        }

        $paymentSystem->delete();

        $this->info(trans('admin.messages.deleted'));
        return redirect()->back();
    }
}
