<?php 

class git
{   
    public static function checkError(string $_string = NULL){
        $return = NULL;
        if($_string != NULL){
            if(strpos($_string, '-// SUCCESS //-') === TRUE){
                $return = TRUE;
            } else {
                return FALSE;
            }

            return $return;
        } else {
            return TRUE;
        }
    }

    public static function getCommitHash($_target = NULL){
        if($_target == NULL){
            $target = "HEAD";
        } else {
            $target = "origin/".$_target;
        }
        return substr(trim(exec('git log --pretty="%H" -n1 ' . $target)), 0, 10);
    }

    public static function getCommitDate($_target = NULL){
        if($_target == NULL){
            $target = "HEAD";
        } else {
            $target = "origin/".$_target;
        }
        $commitDate = new \DateTime(trim(exec('git log -n1 --pretty=%ci ' . $target)));
        $commitDate->setTimezone(new \DateTimeZone('Europe/Paris'));
        return $commitDate->format('d/m/Y à H:i:s');
    }

    public static function getCommitAuthor($_target = NULL){
        if($_target == NULL){
            $target = "HEAD";
        } else {
            $target = "origin/".$_target;
        }
        return exec('git log --pretty="%cn" -n1 ' . $target);
    }

    public static function getCommitName($_target = NULL){
        if($_target == NULL){
            $target = "HEAD";
        } else {
            $target = "origin/".$_target;
        }
        return exec('git log --pretty="%s" -n1 ' . $target);
    }

    public static function getBranchName($_target = NULL){
        if($_target == NULL){
            return exec('git rev-parse --abbrev-ref HEAD');
        } else {
            return $_target;
        }
    }

    public static function printVersion($_target = NULL){
        echo sprintf(
            '<h6>%s <span class="badge bg-info">%s</span> <span class="badge bg-success">%s</span></h6>
            <code>%s</code>
            <div class="media-body pb-3 mb-0 small lh-125">Le %s</div>', 
            self::getCommitAuthor($_target),         
            self::getBranchName($_target), 
            self::getCommitHash($_target),
            self::getCommitName($_target),
            self::getCommitDate($_target)
        );
    }
}
