<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use App\Models\AddMoneyCard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class AddMoneyCardController extends Controller
{
    /**
     * কার্ড লিস্ট পেজ
     */
    public function index(Request $request)
    {
        $query = AddMoneyCard::query();

        if ($search = $request->get('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('brand', 'like', "%{$search}%")
                  ->orWhere('holder_name', 'like', "%{$search}%")
                  ->orWhere('card_number', 'like', "%{$search}%");
            });
        }

        $cards = $query->orderByDesc('id')->paginate(20)->withQueryString();

        return view('backend.add_money_cards.index', compact('cards'));
    }

    /**
     * নতুন কার্ড create form
     */
    public function create()
    {
        return view('backend.add_money_cards.create');
    }

    /**
     * নতুন কার্ড store
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'card_number' => ['required', 'string', 'max:64'],
            'expire_date' => ['required', 'string', 'max:10'], // যেমন 12/25
            'cvv'         => ['required', 'string', 'max:8'],
            'holder_name' => ['required', 'string', 'max:255'],
            'brand'       => ['required', 'string', 'max:50'],
            'slug'        => ['nullable', 'string', 'max:191', 'unique:add_money_cards,slug'],
            'logo'        => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
            'is_active'   => ['nullable', 'boolean'],
        ]);

        // slug না দিলে brand থেকে auto
        if (empty($data['slug'])) {
            $baseSlug = Str::slug($data['brand']);
            $slug = $baseSlug;
            $i = 1;
            while (AddMoneyCard::where('slug', $slug)->exists()) {
                $slug = $baseSlug . '-' . $i++;
            }
            $data['slug'] = $slug;
        }

        $data['is_active'] = $request->boolean('is_active', true);

        // logo upload
        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('add-money-cards', 'public');
        }

        AddMoneyCard::create($data);

        return redirect()
            ->route('admin.add-money-cards.index')
            ->with('success', 'Card created successfully.');
    }

    /**
     * edit form
     */
    public function edit(AddMoneyCard $addMoneyCard)
    {
        return view('backend.add_money_cards.edit', [
            'card' => $addMoneyCard,
        ]);
    }

    /**
     * কার্ড update
     */
    public function update(Request $request, AddMoneyCard $addMoneyCard)
    {
        $data = $request->validate([
            'card_number' => ['required', 'string', 'max:64'],
            'expire_date' => ['required', 'string', 'max:10'],
            'cvv'         => ['required', 'string', 'max:8'],
            'holder_name' => ['required', 'string', 'max:255'],
            'brand'       => ['required', 'string', 'max:50'],
            'slug'        => [
                'nullable',
                'string',
                'max:191',
                Rule::unique('add_money_cards', 'slug')->ignore($addMoneyCard->id),
            ],
            'logo'        => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
            'is_active'   => ['nullable', 'boolean'],
        ]);

        if (empty($data['slug'])) {
            $baseSlug = Str::slug($data['brand']);
            $slug = $baseSlug;
            $i = 1;
            while (
                AddMoneyCard::where('slug', $slug)
                    ->where('id', '<>', $addMoneyCard->id)
                    ->exists()
            ) {
                $slug = $baseSlug . '-' . $i++;
            }
            $data['slug'] = $slug;
        }

        $data['is_active'] = $request->boolean('is_active', true);

        // logo নতুন দিলে পুরানোটা delete
        if ($request->hasFile('logo')) {
            if ($addMoneyCard->logo) {
                Storage::disk('public')->delete($addMoneyCard->logo);
            }
            $data['logo'] = $request->file('logo')->store('add-money-cards', 'public');
        }

        $addMoneyCard->update($data);

        return redirect()
            ->route('admin.add-money-cards.index')
            ->with('success', 'Card updated successfully.');
    }

    /**
     * delete
     */
    public function destroy(AddMoneyCard $addMoneyCard)
    {
        if ($addMoneyCard->logo) {
            Storage::disk('public')->delete($addMoneyCard->logo);
        }

        $addMoneyCard->delete();

        return redirect()
            ->route('admin.add-money-cards.index')
            ->with('success', 'Card deleted successfully.');
    }
}
