<?php

namespace App\Services\Dav;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Sabre\DAV\Auth\Backend\AbstractBasic;
use Sabre\DAV\Auth\Backend\BasicCallBack;
use Sabre\HTTP\RequestInterface;
use Sabre\HTTP\ResponseInterface;

class LaravelSabreAuthBackend extends AbstractBasic
{
    public function __construct()
    {
        \Log::info('LaravelSabreAuthBackend instantiated');
    }

    public function challenge(RequestInterface $request, ResponseInterface $response)
    {
        $response->addHeader('WWW-Authenticate', 'Basic realm="WebDAV", charset="UTF-8"');
    }

    protected function validateUserPass($username, $password)
    {
        $user = User::where('email', $username)->first();

        if ($user && Hash::check($password, $user->password)) {
            // THIS is the new required step
            $this->currentPrincipal = 'principals/' . $user->email;

            \Log::info('validateUserPass auth success', ['principal' => $this->currentPrincipal, 'username' => $username]);

            return true;
        }

        \Log::warning('validateUserPass auth failed', ['username' => $username]);
        return false;
    }

    public function getCurrentPrincipal()
    {
        \Log::debug('getCurrentPrincipal', ['current' => $$this->currentPrincipal]);
        return $this->currentPrincipal;
    }
}
