<?php

namespace App\Http\Controllers;

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


class AreaController extends Controller
{
    /**
     * 
     */
    public function view(Request $request)
    {
        try {
            $data = $request->all();
            return view("view-areas", $data);
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    public function create(Request $request)
    {
        $especiality = new Especiality();
    
        if ($request->isMethod('POST')) {
            try {
                $data = $request->all();
    
                // Validación del nombre
                if (!isset($data["name"]) || trim($data["name"]) === "") {
                    return redirect()->back()->withInput()->with('error', __('Name is required.'));
                }

    
                // Generar ID y verificar duplicados
                $id = str_replace(" ", "", strtoupper(preg_replace('/[^\p{L}]/u', '', iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $data["name"]))));
                if (Especiality::withoutGlobalScope('active')->where("id", $id)->exists()) {
                    return redirect()->back()->withInput()->with('error', __('error-500.area_exists'));
                }
                
                // Crear y guardar la especialidad
                $especiality->id = $id;

                $name = preg_replace('/[^\p{L}\s]/u', '', $data["name"]);
                $name = preg_replace('/\s+/', ' ', $name);
                $name = trim($name);

                $especiality->name = strtoupper($name);
                
                $especiality->active = 1;
                
                if ($especiality->save()) {
                    try{
                     $especiality->createHistoryConfiguration();
                    }catch(Throwable $th){
                        throw $th;
                    }
                    return redirect()->route('/admin/create-areas')->with('success', __('Area created successfully!'));

                }
    
            } catch (Throwable $th) {
                return redirect()->back()->withInput()->with('error', $th->getMessage());
            }
        }
    
        return view("create-areas", [
            "especiality" => $especiality
        ]);
    }
}
