<?php
class GitLab{
	public $token,$host;
	
	public function projects($id = null){
		$projects = $this->rest('GET','/projects');
		return $projects;
	}
	public function groups($id = null){
		$projects = $this->rest('GET','/groups?per_page=1000');

		return $projects;
	}

	public function project_save($group,$label,$slug){
		$body = array(
	        "name"=> $slug,
	        "path"=> $slug,
	        "description"=> $label,
	        'namespace_id' => $group
	       
		);
		$project = $this->rest('POST','/projects',json_encode($body));
		return $project;
	}

	public function groupe_save($label,$slug){
		$body = array(
	        "name"=> $slug,
	        "path"=> $slug,
	        "description"=> $label,
	        "visibility"=> "internal",
	        "share_with_group_lock"=> false,
	        "require_two_factor_authentication"=> false,
	        "two_factor_grace_period"=> 48,
	        "project_creation_level"=> "developer",
	        "auto_devops_enabled"=> null,
	        "subgroup_creation_level"=> "owner",
	        "emails_disabled"=> null,
	        "mentions_disabled"=> null,
	        "lfs_enabled"=> true,
	        "default_branch_protection"=> 1,
	        "avatar_url"=> null,
	        "request_access_enabled"=> false,
	        "parent_id"=> null
		);
		$project = $this->rest('POST','/groups',json_encode($body));
		return $project;
	}


	//Requete rest
	public function rest($method,$action,$body='',$headers=array()){
		$url = $this->host.$action;
		$ch = curl_init();
		$options[CURLOPT_URL] =  $url;
		$options[CURLOPT_RETURNTRANSFER] =  true;
		$options[CURLOPT_SSL_VERIFYPEER] =  false;
		$options[CURLOPT_FOLLOWLOCATION] = true;
		$options[CURLOPT_SSL_VERIFYPEER] = false;
		$options[CURLOPT_USERAGENT] = 'Awesome erp';
		$options[CURLOPT_CUSTOMREQUEST] = $method;

		if(!empty($body)) $options[CURLOPT_POSTFIELDS] = $body;

		$headers = array();
		$headers[] = 'Content-Type: application/json';
		$headers[] = 'Accept: application/json';
		$headers[] = 'Private-Token: '.$this->token;

		$options[CURLOPT_HTTPHEADER] = $headers;

		curl_setopt_array($ch,$options);

		$response = curl_exec($ch);

		if($response === false) throw new Exception(curl_error($ch));

		curl_close($ch);
		return json_decode($response,true);
	}	
}
?>