<?php


namespace App\Providers;

use \App\Providers\Database;

/**
*
*/
class DBMySql extends Database
{
    private $conn = null;


    private $lid = null;
    

    public function __construct(string $host, string $name, string $user, string $pass)
    {
        $dsn = $this->dsnBuilder('mysql', $host, $name);

        $this->conn = $this->connect($dsn, $user, $pass);
    }


    private function dsnBuilder(string $driver, string $host, string $name)
    {
        return "$driver:host=$host; dbname=$name";
    }


    public function run(string $query, array $parameter = [], $returnAs = 'object')
    {
        $outputAs = $this->outputFormat($returnAs);

        $statement = $this->conn->prepare($query);

        $statement->execute($parameter);
        $data = $statement->fetch($outputAs);

        $statement->closeCursor();

        return $data;
    }


    public function all(string $query, array $parameter = [], $returnAs = 'object')
    {
        $outputAs = $this->outputFormat($returnAs);

        $statement = $this->conn->prepare($query);

        $statement->execute($parameter);
        $data = $statement->fetchAll($outputAs);
        
        $statement->closeCursor();

        return $data;
    }


    public function count(string $query, array $parameter = [], $returnAs = 'object')
    {
        $outputAs = $this->outputFormat($returnAs);

        $statement = $this->conn->prepare($query);

        $statement->execute($parameter);
        $data = $statement->rowCount($outputAs);

        $this->lid = $this->conn->lastInsertId();
        
        $statement->closeCursor();

        return $data;
    }


    public function lid()
    {
        $lid = $this->lid;
        $this->lid = null;
        return $lid;
    }
}
