<?php

namespace App\Http\Controllers\Backend;

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

class BankController extends Controller
{
    public function index(Request $request)
    {
        $q = Bank::query();

        if ($s = $request->get('q')) {
            $q->where(function ($w) use ($s) {
                $w->where('name', 'like', "%{$s}%")
                    ->orWhere('slug', 'like', "%{$s}%")
                    ->orWhere('holder_name', 'like', "%{$s}%")
                    ->orWhere('account_number', 'like', "%{$s}%")
                    ->orWhere('branch_name', 'like', "%{$s}%");
            });
        }

        if (!is_null($request->get('active')) && $request->get('active') !== '') {
            $q->where('is_active', (bool) $request->get('active'));
        }

        $banks = $q->orderBy('name')->paginate(12)->withQueryString();

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

    public function create()
    {
        return view('backend.banks.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'            => ['required', 'string', 'max:255'],
            'slug'            => ['nullable', 'string', 'max:191', 'unique:banks,slug'],
            'holder_name'     => ['nullable', 'string', 'max:255'],     // 🔹 new
            'account_number'  => ['nullable', 'string', 'max:100'],     // 🔹 new
            'branch_name'     => ['nullable', 'string', 'max:255'],     // 🔹 new
            'min_transaction' => ['required', 'numeric', 'min:0'],
            'reward_percent'  => ['required', 'numeric', 'min:0'],
            'is_active'       => ['required', 'in:0,1'],
            'logo_path'       => ['nullable', 'string', 'max:600'],
            'logo_file'       => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp,svg', 'max:2048'],
        ]);

        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }

        if ($request->hasFile('logo_file')) {
            $data['logo_path'] = $request->file('logo_file')->store('uploads/banks', 'public');
        }

        Bank::create($data);

        return redirect(url('/admin/banks'))->with('success', 'Bank created.');
    }

    public function show($id)
    {
        $bank = Bank::findOrFail($id);

        return view('backend.banks.show', compact('bank'));
    }

    public function edit($id)
    {
        $bank = Bank::findOrFail($id);

        return view('backend.banks.edit', compact('bank'));
    }

    public function update(Request $request, $id)
    {
        $bank = Bank::findOrFail($id);

        $data = $request->validate([
            'name'            => ['required', 'string', 'max:255'],
            'slug'            => [
                'nullable',
                'string',
                'max:191',
                Rule::unique('banks', 'slug')->ignore($bank->id),
            ],
            'holder_name'     => ['nullable', 'string', 'max:255'],     // 🔹 new
            'account_number'  => ['nullable', 'string', 'max:100'],     // 🔹 new
            'branch_name'     => ['nullable', 'string', 'max:255'],     // 🔹 new
            'min_transaction' => ['required', 'numeric', 'min:0'],
            'reward_percent'  => ['required', 'numeric', 'min:0'],
            'is_active'       => ['required', 'in:0,1'],
            'logo_path'       => ['nullable', 'string', 'max:600'],
            'logo_file'       => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp,svg', 'max:2048'],
            'remove_logo'     => ['nullable', 'boolean'],
        ]);

        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }

        if ($request->boolean('remove_logo') && $bank->logo_path && Storage::disk('public')->exists($bank->logo_path)) {
            Storage::disk('public')->delete($bank->logo_path);
            $data['logo_path'] = null;
        }

        if ($request->hasFile('logo_file')) {
            $path = $request->file('logo_file')->store('uploads/banks', 'public');
            if ($bank->logo_path && Storage::disk('public')->exists($bank->logo_path)) {
                Storage::disk('public')->delete($bank->logo_path);
            }
            $data['logo_path'] = $path;
        }

        $bank->update($data);

        return redirect(url('/admin/banks'))->with('success', 'Bank updated.');
    }

    public function destroy($id)
    {
        $bank = Bank::findOrFail($id);

        if ($bank->logo_path && Storage::disk('public')->exists($bank->logo_path)) {
            Storage::disk('public')->delete($bank->logo_path);
        }

        $bank->delete();

        return redirect(url('/admin/banks'))->with('success', 'Bank deleted.');
    }

    public function toggle($id)
    {
        $bank = Bank::findOrFail($id);
        $bank->update(['is_active' => !$bank->is_active]);

        return back()->with('success', 'Status toggled.');
    }
}
