<?php

namespace App\Domain\Logger\Repository;

use PDO;
use Illuminate\Database\Connection;
use Exception;

/**
 * Repository.
 */
class LoggerRepository
{
    /**
     * @var PDO The database connection
     */
    private $connection;
    /**
     * Constructor.
     *
     * @param PDO $connection The database connection
     */
    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }

    /**
     * Insert user row.
     *
     * @param array $datos de los usuarios
     *
     * @return int The new ID
     */
    
    public function InsertRecord(array $Logger):array{

            $row = [
                'id_user' => $Logger['idUser'],
                'date' => date('Y-m-d H:i:s'),
                'tipo' => $Logger['type'],
                'observacion' => $Logger['observation']
            ];

            try { 

                $this->connection->table('auditorias')->insert($row);
                $vErr=0;
                $result = [
                    
                        'SqlState' => 'Transaccion ejecutada correctamente',
                        'ErrNumber' => $vErr,
                        'UniqueViolation' => 'Ok',
                        'Description' => 'El registro se creo correctamente',
                    
                    ];

              } catch(\Illuminate\Database\QueryException $ex){ 

                $error=explode(":",$ex->getMessage());
                  //$descripcion=
                $err=substr($error[0],9,-1);

                  $result = [
                        'SqlState' => $error[0],
                        'ErrNumber' => $err,
                        'UniqueViolation' => $error[1],
                        'Description' => 'Ocurrio un error al momento de crear el registro',
                        'FullInfo' => trim($error[4]),
                    ];
                    // Note any method of class PDOException can be called on $ex.
                
              }
            
       return $result;
       // return (int)$this->connection->lastInsertId();
    }

    public function SearchRecords():string {
        $payload = $this->connection->table('auditorias')->sharedLock()->get();
        return $payload;  
    }
    
    public function GetItemsForLocat(string $fk_id):string {

      $payload=$this->connection->table('ubicacion')
      ->select('ubicacion.id_ubicacion as ID','ubicacion.nombre as location','ubicacion.fk_id_sede as fk_id',$this->connection->raw('count(activos.id_activo) as items'))
      ->leftJoin('activos', 'activos.fk_id_ubicacion', '=' ,'ubicacion.id_ubicacion')
      ->where('ubicacion.fk_id_sede','=',$fk_id)
      ->groupBy('ubicacion.nombre')
      ->orderby('ubicacion.nombre')
      ->sharedLock()
      ->get();

      return $payload;  
    }

    public function SearchRecord(string $email,string $pass):string{
        $payload=$this->connection->table('usuarios')
        ->where('correo','=', $email)->get();
        return $payload;  
    }

    public function DeleteRecord(string $id):array {

      try { 

      $this->connection->table('Logger')
      ->where(['id' => $id])
      ->delete();
      $result = [
                    
        'SqlState' => 'Transaccion ejecutada correctamente',
        'ErrNumber' => '0',
        'UniqueViolation' => 'Ok',
        'Description' => 'El registro se elimino correctamente',
    
      ];

      }catch(\Illuminate\Database\QueryException $ex){ 
        //var_dump($ex->getMessage());  
        $error=explode(":",$ex->getMessage());
          //$descripcion=
        $err=substr($error[0],9,-1);
          $result = [
                'SqlState' => $error[0],
                'ErrNumber' => $err,
                'UniqueViolation' => $error[1],
                'Description' => 'Ocurrio un error al momento de eliminar el registro',
                'FullInfo' => trim($error[4]),
        ];
        // Note any method of class PDOException can be called on $ex.
      }

    return $result;
    }

    public function UpdateRecord(array $Logger, string $id):array{

        $row = [
            'id_tercero' => $Logger['id_tercero'],
            'nombre' => $Logger['nombre'],
            'direccion' => $Logger['direccion'],
            'descripcion' => $Logger['descripcion'],
            'vicepresidencia' => $Logger['vicepresidencia'],
            'supervisor' => $Logger['supervisor'],
            'telefono' => $Logger['telefono'],
            'email' => $Logger['email'],
            'condicion_entrega' => $Logger['condicion_entrega'],
        ];

            try { 
                $this->connection->table('Logger')
                ->where(['id' => $id])
                ->update($row);
                $result = [
                    
                        'SqlState' => 'Transaccion ejecutada correctamente',
                        'ErrNumber' => '0',
                        'UniqueViolation' => 'Ok',
                        'Description' => 'El registro se actualizo correctamente',
                    
                    ];
              } catch(\Illuminate\Database\QueryException $ex){ 
                //var_dump($ex->getMessage());  
                $error=explode(":",$ex->getMessage());
                  //$descripcion=
                $err=substr($error[0],9,-1);
                  $result = [
                        'SqlState' => $error[0],
                        'ErrNumber' => $err,
                        'UniqueViolation' => $error[1],
                        'Description' => 'Ocurrio un error al momento de actualizar el registro',
                        'FullInfo' => trim($error[4]),
                ];
                // Note any method of class PDOException can be called on $ex.
              }

            
       return $result;
    }

}