<?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/auth/verify";

    function __construct(\PDO $pdo)
    {

        $this->pdo = $pdo;

    }

    function validateBearerToken($token)
    {
        try {
            $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 ($username = $stmt->fetchColumn()) {
                return "principals/" . $username;
            }

            return null;
        } 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);
            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->user) {
                return $userData->user;
            } else {
                return null;
            }
        } catch (\Exception $e) {

        }

    }
}