<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PaymentMethods;
use App\Exceptions\GlobalException;

class PaymentsMethodController extends Controller
{


    
    public function create(Request $request){
    $paymentMethod = new PaymentMethods();

    if ($request->isMethod('POST')) {
        $data = $request->all();

        // Validación del nombre
        if (!isset($data["name"]) || trim($data["name"]) === "") {
            return redirect()->back()
                ->withInput()
                ->with('error', __('Name required'));
        }

        try {
            // Generar ID y verificar existencia
            $id = strtoupper(md5(trim(strtoupper($data["name"]))));
            if (PaymentMethods::where("id", $id)->exists()) {
                return redirect()->back()
                    ->withInput()
                    ->with('error', __("Payment method already exist"));
            }

            // Crear y guardar
            $paymentMethod->id = $id;
            $paymentMethod->title = strtoupper($data["name"]);
            
            if ($paymentMethod->save()) {
                $redirect = isset($data["redirectToCreatePayment"])
                    ? redirect()->route("/admin/create-payment") // Asegurar nombre de ruta correcto
                    : redirect()->route('/admin/create-payments-method');

                return $redirect->with('success', __('Payment method created successfully'));
            }

        } catch (Throwable $th) {
            return redirect()->back()
                ->withInput()
                ->with('error', $th->getMessage());
        }
    }

    return view("create-payments-method", [
        'paymentMethod' => $paymentMethod
    ]);
}

     /**
     * 
     */
    public function view(Request $request){
        try{
             $data = $request->all();
             return view("view-payments-method",$data);
        }catch (Throwable $th) {
             throw new GlobalException($th->getMessage());
         }
     }
 
     /**
      * 
      */
     public function detail(Request $request){
         try{
             $data = $request->all();
             return view("detail-payments-method");
         }catch (Throwable $th) {
             throw new GlobalException($th->getMessage());
         }
     }


     
    /**
     * 
     */
    public function update(Request $request){
        try{
         $data = $request->all();
         return view("detail-payments-method");
        }catch (Throwable $th) {
             throw new GlobalException($th->getMessage());
         }
     }
}
