<?php

namespace App\Http\Controllers\Extranet;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Empresa;
use App\Models\Entidad;

class EntidadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        
        // dd($request);
        DB::beginTransaction();
        try {  

            // $id_de = Crypt::decryptString($id);
            $nom_empresa = "";
            $data = new Entidad;

            if($request->tipo_persona==1){

                // $id_empresa = 0;
                if($request->empresa=="true"){
                    // echo "existe la empresa";
                    $id_empresa = $request->idempresa;
                }else{
                    // echo "existe no empresa";
                    $empresa = new Empresa;
                    $empresa->ruc = $request->ruc;
                    $empresa->empresa = $request->razon_social;
                    $empresa->direccion = $request->direccion_empresa;
                    $empresa->save();
                    $id_empresa = $empresa->id;
                }
                $nom_empresa = '_____________'.$request->ruc."|".$request->razon_social;
                $data->tipo = 1;
                $data->id_empresa = $id_empresa;

            }else{
                $data->tipo = 0;
            }

            $data->id_tipo_documento = $request->tipo_documento;
            $data->documento = $request->documento;
            $data->paterno = strtoupper($request->paterno);
            $data->materno = strtoupper($request->materno);
            $data->nombres = strtoupper($request->nombres);
            $data->id_ubigeo = $request->distrito;
            $data->direccion = strtoupper($request->direccion);
            $data->telefono = $request->telefono;
            $data->email = $request->email;
            $data->save();

            // try {  

                // $id_en = Crypt::encryptString($data->id);
                // $mensaje["nombres"] = $data->nombres;
                // $mensaje["apellidos"] = $data->paterno." ".$data->materno;
                // $mensaje["url"] = url("/activation/".$id_en);
                // $mensaje["documento"] = $data->documento;
                // $mensaje["clave"] = $data->pass;
                // Mail::to($data->email)->send(new ActivacionMail($mensaje));

            // } catch (\Exception $e) {
                // $message = 'Error al Guardar. Intente otra vez.';
                // $status = false;
            // }

            DB::commit();
            $message = 'Registro Exitoso.';
            $status = true;
            $response["id"] = $data->id;
            $response["nombre"] = $data->documento.'|'.$data->paterno.' '.$data->materno.' '.$data->nombres.$nom_empresa;
        } catch (\Exception $e) {
            DB::rollback();
            $message = 'Sucedio un inconveniente al Registrar. Intente otra vez.';
            $status = false;
        }
        $response["status"] = $status;
        $response["message"] = $message;
        return $response;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function select2(Request $request){
        $search = $request->q;
        $response["items"] = DB::table("entidad as e")
                ->select(
                    "e.id",
                    DB::raw("
                        CONCAT(
                            e.documento,'|',
                            e.paterno,' ',
                            IFNULL(e.materno,''),' ',
                            IFNULL(e.nombres,''),
                            IF(em.ruc!='','_____________',''),
                            IFNULL(em.ruc,''),
                            IF(em.ruc!='','|',''),
                            IFNULL(em.empresa,'')
                            ) as text"),
                )
                ->where(function ($query)  use ($search){
                // ->where("nombre","like","%$request->q%")
                    $query->where("e.nombres","like","%$search%")
                        ->orWhere("e.paterno","like","%$search%")
                        ->orWhere("e.materno","like","%$search%")
                        ->orWhere(DB::raw("CONCAT(e.paterno,' ',e.materno)"), "LIKE", "%".$search."%")
                        ->orWhere("e.documento","like","%$search%")
                        ->orWhere("em.ruc","like","%$search%")
                        ->orWhere("em.empresa","like","%$search%");
                    // $query->where('type', 0)
                })
                ->leftJoin("empresa as em","em.id","e.id_empresa")
                ->get();
        return $response;
    }
}
