<?php

namespace Simulador\Database;

use mysqli;
use PDO;

class DBCotacao
{

    /**
     * @return []
     * @throws ApiException
     */
    private static function getLogin(): array
    {
        $login['hostname'] = 'localhost';
        $login['charset'] = 'utf8';
        if ($_SERVER['SERVER_NAME'] !== 'proteauto-simulador-v3.test') {

            $login['username'] = 'qsnjlxoz_user';
            $login['password'] = 'buvPhMm7CUcq';
            $login['database'] = 'qsnjlxoz_simula';
        } else {
            $login['username'] = 'root';
            $login['password'] = '';
            $login['database'] = 'proteauto_simulador';
        }
        return $login;
    }

    /**
     * @return mysqli
     * @throws ApiException
     */
    public static function get(): mysqli
    {
        static $db;
        if ($db === null) {
            mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
            $login = self::getLogin();

            $db = new mysqli($login['hostname'], $login['username'], $login['password'], $login['database']);
            $db->set_charset($login['charset']);
        }
        return $db;
    }

    /**
     * @return PDO
     * @throws ApiException
     */
    public static function getPDO(): PDO
    {

        static $dbPDO;

        if ($dbPDO === null) {
            mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
            $login = self::getLogin();

            $driver = "mysql:host={$login['hostname']};dbname={$login['database']}";
            $dbPDO = new PDO($driver, $login['username'], $login['password']);

            $stmt = $dbPDO->prepare(/** @lang MySQL */'SET CHARACTER SET :var1');
            $stmt->execute([':var1' => $login['charset']]);

            $dbPDO->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $dbPDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        }

        return $dbPDO;
    }

}
