<?php

namespace App\Http\Controllers\ThirdPartyServices;

use App\Http\Controllers\Controller;
use App\Mail\sendExportNotice;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use RuntimeException;

class NextcloudService extends Controller
{
    private $nextcloud_url;
    private $nextcloud_user;
    private $nextcloud_password;

    public function __construct()
    {
        $this->nextcloud_url = config('app.nextcloud_url', false);
        $this->nextcloud_user = config('app.nextcloud_user', false);
        $this->nextcloud_password = config('app.nextcloud_password', false);
        $this->nextcloud_upload_folder_path = config('app.nextcloud_upload_folder_path', false);
        $this->nextcloud_upload_folder_web_link = config('app.nextcloud_upload_folder_web_link', false);
    }

    function nextcloud_upload_csv(string $file_name, string $file_path)
    {
        try {
            $nextcloud_url = $this->nextcloud_url . '/remote.php/dav/files/' . $this->nextcloud_user . '/' . $this->nextcloud_upload_folder_path . '/' . $file_name;
            $file_contents = fopen($file_path, 'r');
            try {
                $res = Http::withBasicAuth($this->nextcloud_user, $this->nextcloud_password)
                    ->attach($file_name, $file_contents)
                    ->put($nextcloud_url);
                $res->throw();
            } catch (\Exception $e) {
                Log::error('nextcloud_upload_csv Upload error - ' . $e->getMessage());
                throw new RuntimeException("E-NEXTCLOUD-UPLOAD");
            }
            // Close the file handle
            fclose($file_contents);
            return $res;
        } catch (\Exception $e) {
            return false;
        }
    }
}