<?php

namespace PT;

use Sabre\DAV\Auth\Backend\AbstractBearer;

class TokenAuth extends AbstractBearer
{
    public $tableName = "users";
    private $pdo;
    private $apiURL = "https://da-api.drywallaptitude.co.uk/users/";
    private $userId = 1;

    function __construct(\PDO $pdo)
    {

        $this->pdo = $pdo;

    }

    function createCalendar()
    {

    }

    function validateBearerToken($token)
    {
        try {
//            $this->userId = $_GET['userId'];
            $user = $this->makeAPICall($token);
            if ($user == null) {
                return null;
            }
            $stmt = $this->pdo->prepare('SELECT username FROM ' . $this->tableName . ' WHERE username = ?');
            $stmt->execute([$user->email]);
            if ($data = $stmt->fetchColumn()) {
                return "principals/" . $data;
            }
        } catch (\Exception $e) {
            return null;
        }

    }

    function makeAPICall($token)
    {
        try {
            $ch = curl_init();
            $headers = array(
                'Content-type: application/json',
                'Authorization: Bearer ' . $token,
            );
            // set url
            curl_setopt($ch, CURLOPT_URL, $this->apiURL . $this->userId);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            //return the transfer as a string
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // $output contains the output string
            $output = curl_exec($ch);
            $userData = json_decode($output);
            // close curl resource to free up system resources
            curl_close($ch);
            if ($userData->id) {
                return $userData;
            } else {
                return null;
            }
        } catch (\Exception $e) {

        }

    }
}