<?php

/*
 * Copyright 2017-08-31  Cámara de Comercio de Santa Marta para el Magdalena.
 * Autor: Luis Montoya <lmontoya@ccsm.org.co at www.ccsm.org.co>.
 * Archivo: Conexion.
 *
 * Licenciado bajo la Licencia Apache, Versión 2.0;
 * Usted no puede usar este archivo excepto en conformidad con la Licencia.
 * Usted puede obtener una copia de la Licencia en
 *
 *   	http://www.apache.org/licenses/LICENSE-2.0
 *
 * A menos que sea requerido por la ley aplicable o acordado por escrito, el software
 * Distribuido bajo la licencia se distribuye en una "AS IS" o  "COMO ESTA" BASE,
 * SIN GARANTÍAS NI CONDICIONES DE NINGÚN TIPO, expresas o implícitas.
 * Consulte la Licencia para los permisos y Limitaciones bajo la Licencia.
 */

/**
 * Description of Conexion
 *
 * @author Luis Montoya <lmontoya@ccsm.org.co at www.ccsm.org.co>
 */
class Conexion extends PDO {

    public static $instancia = null;

    public function __construct() {
        self::bdLocal();
        try {
            parent::__construct(
                    'mysql:host=' . HOST . ';dbname=' . BD_NAME, BD_USER, BD_PASSWORD, array(
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
                PDO::ATTR_PERSISTENT => true
                    )
            );
            $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }
    }

    public static function singleton() {
        if (!isset(self::$instancia)) {
            $miclase = __CLASS__;
            self::$instancia = new $miclase;
        }
        return self::$instancia;
    }

    public static function selectUnaFila($sqlQuery, $datosQuery = NULL) {
        $conexion = Conexion::singleton();
        try {
            $conexion->beginTransaction();
            $sentenciaSql = $conexion->prepare($sqlQuery);
            $sentenciaSql->execute($datosQuery);
            $datos = $sentenciaSql->fetch(PDO::FETCH_OBJ);
            $conexion->commit();
            if (!empty($datos)) {
                return $datos;
            }
            return NULL;
        } catch (PDOException $error) {
            $conexion->rollBack();
            throw $error;
        }
    }

    public static function selectVariasFilas($sqlQuery, $datosQuery = NULL) {
        $conexion = Conexion::singleton();
        try {
            $conexion->beginTransaction();
            $sentenciaSql = $conexion->prepare($sqlQuery);
            $sentenciaSql->execute($datosQuery);
            $datos = $sentenciaSql->fetchAll(PDO::FETCH_OBJ);
            $conexion->commit();
            if (!is_null($datos)) {
                return $datos;
            }
            return NULL;
        } catch (PDOException $error) {
            $conexion->rollBack();
            throw $error;
        }
    }

    public static function insertFila($sqlQuery, $datosQuery = NULL) {
        $conexion = Conexion::singleton();
        try {            
            $conexion->beginTransaction();
            $sentenciaSql = $conexion->prepare($sqlQuery);
            $sentenciaSql->execute($datosQuery);
            $ultimoInsert = $conexion->lastInsertId();
            $conexion->commit();
            if (!is_null($ultimoInsert)) {
                return $ultimoInsert;
            }
            return NULL;
        } catch (PDOException $error) {
            $conexion->rollBack();
            throw $error;
        }
    }

    public static function actualizarFila($sqlQuery, $datosQuery = NULL) {
        $conexion = Conexion::singleton();
        try {
            $conexion->beginTransaction();
            $sentenciaSql = $conexion->prepare($sqlQuery);
            $sentenciaSql->execute($datosQuery);
            $modificados = $sentenciaSql->rowCount();
            $conexion->commit();
            if (!is_null($modificados)) {
                return $modificados;
            }
            return NULL;
        } catch (PDOException $error) {
            $conexion->rollBack();
            throw $error;
        }
    }

    private static function bdLocal() {
        define('HOST', 'ccsm.org.co');
        define('BD_NAME', 'ccsm_sicam32_dev');
        define('BD_NAME_LOG', '***************');
        define('BD_USER', 'ccsm_dev');
        define('BD_PASSWORD', 'T=u93175JJ#&');
    }

    private static function bdPreProduccion() {
        define('HOST', '');
        define('BD_NAME', '');
        define('BD_USER', '');
        define('BD_PASSWORD', '');
    }

    private static function bdProduccion() {
        define('HOST', '');
        define('BD_NAME', '');
        define('BD_USER', '');
        define('BD_PASSWORD', '');
    }

}

