<?php

namespace App\Http\Controllers;

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

class CurrenciesController extends Controller
{
    public function create(Request $request)
{
    $currency = new Currencies();

    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 (Currencies::where("id", $id)->exists()) {
                return redirect()->back()
                    ->withInput()
                    ->with('error', __("Currency already exist"));
            }

            // Crear y guardar
            $currency->id = $id;
            $currency->title = strtoupper($data["name"]);
            
            if ($currency->save()) {
                $redirect = isset($data["redirectToCreatePayment"])
                    ? redirect()->route("/admin/create-payment")
                    : redirect()->route('/admin/create-currency');

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

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

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


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


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