<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Upi;
use Illuminate\Http\Request;

class AdminUpiManagementController extends Controller
{
    public function UpiManagement()
    {
        $upis = Upi::latest()->paginate(10);
        return view('adminDashboard.upi-management', compact('upis'));
    }

    public function DeleteUpi($id)
    {
        $upi = Upi::find($id);
        if ($upi) {
            $upi->delete();
            return redirect()->back()->with('message', 'Upi Deleted Successfully');
        } else {
            return redirect()->back()->with('message', 'Upi Not Found');
        }
    }

    public function AddUpi(Request $request)
    {
        $request->validate([
            'type' => 'required',
        ]);

        // Save the UPI record based on the type
        $upi = new Upi();
        // If the selected type is UPI, validate UPI ID
        if ($request->type === 'upi') {
            $request->validate([
                'upi_id' => 'required',
            ]);

            // Check if UPI ID already exists
            $checkUpi = Upi::where('upi_id', trim($request->upi_id))->first();
            if ($checkUpi) {
                return redirect()->back()->with('message', 'UPI ID Already Exists');
            }
        }

        // If the selected type is QR, validate QR field
        if ($request->type === 'qr') {
            $request->validate([
                'qr' => 'required|image|mimes:jpeg,png,jpg|max:2048',
            ]);
            $image = $request->file('qr');
            $ext = $image->extension();
            $image_name = time() . uniqid() . '.' . $ext;
            request()->qr->move(public_path('assets/img/qr_code'), $image_name);
            $upi->qr = 'qr_code/' . $image_name;
        }

        // If the selected type is Bank, validate bank details
        if ($request->type === 'bank') {
            $request->validate([
                'bank' => 'required',
                'banking_name' => 'required',
                'account_number' => 'required',
                'ifsc' => 'required',
            ]);
        }

        $upi->type = $request->type;

        // Set fields based on type
        if ($request->type === 'upi') {
            $upi->upi_id = trim($request->upi_id);
        } elseif ($request->type === 'bank') {
            $upi->bank = trim($request->bank);
            $upi->banking_name = trim($request->banking_name);
            $upi->account_number = trim($request->account_number);
            $upi->ifsc = trim($request->ifsc);
        }

        $upi->save();

        return redirect()->back()->with('message', ucfirst($request->type) . ' Added Successfully');
    }
}
