<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\PaymentMethod;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class PaymentMethodController extends Controller
{
      // List
    public function index(Request $request)
    {
        $q = PaymentMethod::query();

        if ($search = $request->get('q')) {
            $q->where(function ($x) use ($search) {
                $x->where('name', 'like', "%{$search}%")
                  ->orWhere('slug', 'like', "%{$search}%")
                  ->orWhere('type', 'like', "%{$search}%");
            });
        }
        if ($request->filled('active')) {
            $q->where('is_active', (bool) $request->boolean('active'));
        }

        $methods = $q->latest()->paginate(12)->withQueryString();
        return view('backend.payment_methods.index', compact('methods'));
    }

    // Create form
    public function create()
    {
        return view('backend.payment_methods.create');
    }

    // Store (upload + slug logic here; model এ কিছু নেই)
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'       => 'required|string|max:255',
            'slug'       => 'nullable|string|max:255|unique:payment_methods,slug',
            'type'       => 'required|string|max:100',
            'account_no' => 'nullable|string|max:191',
            'daily_min'  => 'nullable|integer|min:0',
            'daily_max'  => 'nullable|integer|min:0|gte:daily_min',
            'is_active'  => 'sometimes|boolean',
            'logo'       => 'nullable|image|max:2048',
            'meta'       => 'nullable|json',
        ]);

        // slug auto (if empty)
        if (empty($validated['slug'])) {
            $validated['slug'] = $this->uniqueSlug($validated['name']);
        }

        // logo upload
        if ($request->hasFile('logo')) {
            $validated['logo'] = $request->file('logo')
                ->store('uploads/payment_methods', 'public');
        } else {
            $validated['logo'] = null;
        }

        // meta string -> array
        if (isset($validated['meta']) && is_string($validated['meta'])) {
            $validated['meta'] = json_decode($validated['meta'], true) ?: null;
        }

        PaymentMethod::create($validated);
        return redirect(url('/admin/payment-methods'))->with('success', 'Payment method created.');
    }

    // Show
    public function show($id)
    {
        $pm = PaymentMethod::findOrFail($id);
        return view('backend.payment_methods.show', compact('pm'));
    }

    // Edit form
    public function edit($id)
    {
        $pm = PaymentMethod::findOrFail($id);
        return view('backend.payment_methods.edit', compact('pm'));
    }

    // Update (upload + slug logic here; model এ কিছু নেই)
    public function update(Request $request, $id)
    {
        $pm = PaymentMethod::findOrFail($id);

        $validated = $request->validate([
            'name'       => 'required|string|max:255',
            'slug'       => 'nullable|string|max:255|unique:payment_methods,slug,' . $pm->id,
            'type'       => 'required|string|max:100',
            'account_no' => 'nullable|string|max:191',
            'daily_min'  => 'nullable|integer|min:0',
            'daily_max'  => 'nullable|integer|min:0|gte:daily_min',
            'is_active'  => 'sometimes|boolean',
            'logo'       => 'nullable|image|max:2048',
            'meta'       => 'nullable|json',
            'remove_logo'=> 'sometimes|boolean',
        ]);

        // slug auto (if empty)
        if (empty($validated['slug'])) {
            $validated['slug'] = $this->uniqueSlug($validated['name'], $pm->id);
        }

        // meta parse
        if (isset($validated['meta']) && is_string($validated['meta'])) {
            $validated['meta'] = json_decode($validated['meta'], true) ?: null;
        }

        // logo cases: remove | replace | keep
        if ($request->boolean('remove_logo')) {
            if ($pm->logo) {
                Storage::disk('public')->delete($pm->logo);
            }
            $validated['logo'] = null;
        } elseif ($request->hasFile('logo')) {
            if ($pm->logo) {
                Storage::disk('public')->delete($pm->logo);
            }
            $validated['logo'] = $request->file('logo')
                ->store('uploads/payment_methods', 'public');
        } else {
            unset($validated['logo']); // keep old
        }

        $pm->update($validated);
        return redirect(url('/admin/payment-methods'))->with('success', 'Payment method updated.');
    }

    // Delete
    public function destroy($id)
    {
        $pm = PaymentMethod::findOrFail($id);
        if ($pm->logo) {
            Storage::disk('public')->delete($pm->logo);
        }
        $pm->delete();
        return redirect(url('/admin/payment-methods'))->with('success', 'Payment method deleted.');
    }

    // Quick toggle active
    public function toggle($id)
    {
        $pm = PaymentMethod::findOrFail($id);
        $pm->update(['is_active' => !$pm->is_active]);
        return back()->with('success', 'Status toggled.');
    }

    // Helper: unique slug creator (keeps logic out of model)
    private function uniqueSlug(string $name, ?int $ignoreId = null): string
    {
        $base = Str::slug($name) ?: 'item';
        $slug = $base; $i = 1;

        $query = PaymentMethod::where('slug', $slug);
        if ($ignoreId) $query->where('id', '!=', $ignoreId);

        while ($query->exists()) {
            $slug = $base.'-'.$i++;
            $query = PaymentMethod::where('slug', $slug);
            if ($ignoreId) $query->where('id', '!=', $ignoreId);
        }
        return $slug;
    }
}

