<?php

namespace App\Helpers;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Spatie\Image\Image;

class NextCloudHelper
{
    /**
     * Create a folder in Nextcloud.
     *
     * @param string $baseUrl Nextcloud Base URL
     * @param string $username Nextcloud Username
     * @param string $password Nextcloud Password
     * @param string $folderPath Folder Path to Create
     * @return array Response Data
     */
    public static function createFolder($baseUrl, $username, $password, $folderPath)
    {
        $client = new Client();
        $folders = explode('/', ltrim($folderPath, '/'));  // Split the folder path into an array
        $currentPath = '';  // Initialize an empty string to build the path progressively

        foreach ($folders as $folder) {
            $currentPath .= '/' . $folder;  // Add the current folder to the path

            // Build the URL to create the folder
            $url = rtrim($baseUrl, '/') . "/remote.php/dav/files/{$username}" . $currentPath;

            try {
                // Attempt to create the current folder
                $response = $client->request('MKCOL', $url, [
                    'auth' => [$username, $password],
                    'verify' => false // Disable SSL verification (only for testing purposes)
                ]);

                // If folder creation is successful, proceed to the next folder
                if ($response->getStatusCode() === 201) {
                    echo "Folder '$currentPath' created successfully.\n";
                }
            } catch (RequestException $e) {
                // Handle errors, such as folder already existing
                if ($e->getCode() === 409) {
                    echo "Folder '$currentPath' already exists.\n";
                } else {
                    // For other errors
                    echo "Failed to create folder '$currentPath': " . $e->getMessage() . "\n";
                }
            }
        }

        return [
            'success' => true,
            'status' => 200,
            'message' => 'All folders processed.'
        ];
    }
    
    public static function uploadFile($folderPath, $fileObject, $fileName)
    {
        $baseUrl = env('NEXT_CLOUD_URL');
        $username = env('NEXT_CLOUD_USERNAME');
        $password = env('NEXT_CLOUD_PASSWORD');

        // Ensure the folder exists (or create it)
        $folderResponse = self::createFolder($baseUrl, $username, $password, $folderPath);

        if (!$folderResponse['success']) {
            return [
                'success' => false,
                'status' => $folderResponse['status'],
                'message' => 'Failed to create folder: ' . $folderResponse['message']
            ];
        }

        $client = new Client();
        $url = rtrim($baseUrl, '/') . "/remote.php/dav/files/{$username}/" . ltrim($folderPath, '/') . '/' . $fileName;

        try {
            // Check if the file is an image
            if (Str::endsWith($fileName, ['.jpeg', '.png', '.jpg', '.gif', '.svg', '.heic', '.heif'])) {
                // Save the uploaded file or raw content to a temporary path
                $tempPath = tempnam(sys_get_temp_dir(), 'image_') . '.' . pathinfo($fileName, PATHINFO_EXTENSION);

                if (is_string($fileObject)) {
                    // If fileObject is raw content, write it to the temp file
                    file_put_contents($tempPath, $fileObject);
                } elseif ($fileObject instanceof \Illuminate\Http\UploadedFile) {
                    // If fileObject is an UploadedFile, move it to the temp file
                    $fileObject->move(dirname($tempPath), basename($tempPath));
                }

                // Optimize the image
                Image::load($tempPath)
                    ->optimize()
                    ->quality(50)
                    ->save();

                // Replace fileObject with the optimized file content
                $fileObject = file_get_contents($tempPath);

                // Remove the temporary file
                unlink($tempPath);
            }

            // Upload the file
            $response = $client->request('PUT', $url, [
                'auth' => [$username, $password],
                'body' => $fileObject,
                'verify' => false // Disable SSL verification (only for testing purposes)
            ]);

            return [
                'success' => true,
                'status' => $response->getStatusCode(),
                'message' => 'File uploaded successfully.'
            ];
        } catch (RequestException $e) {
            return [
                'success' => false,
                'status' => $e->getCode(),
                'message' => $e->getMessage(),
            ];
        }
    }

    public static function getFileUrl($filePath)
    {
        // Instead of returning the direct Nextcloud URL,
        // return a URL to your own download route.
        return route('admin.nextcloud.download', ['file' => base64_encode($filePath)]);
    }

    public static function getNextcloudFile($filePath)
    {
        // Check if the file exists
        if (Storage::disk('webdav')->exists($filePath)) {
            // Get the file contents
            $content = Storage::disk('webdav')->get($filePath);

            // Return the file as a response for download
            return response($content)
                ->header('Content-Type', 'application/pdf')
                ->header('Content-Disposition', 'inline; filename="' . basename($filePath) . '"');
        } else {
            return response()->json(['error' => 'File not found'], 404);
        }
    }

    /**
     * Create a user in Nextcloud.
     *
     * @param string $baseUrl Nextcloud Base URL
     * @param string $adminUsername Admin Username
     * @param string $adminPassword Admin Password
     * @param string $userId New User ID
     * @param string $password New User Password
     * @param string $displayName New User Display Name
     * @param string $email New User Email
     * @return array Response Data
     */
    public static function createUser($baseUrl, $adminUsername, $adminPassword, $userId, $password, $displayName, $email)
    {
        $client = new Client();
        $url = rtrim($baseUrl, '/') . "/ocs/v1.php/cloud/users";
        
        try {
            $response = $client->request('POST', $url, [
                'auth' => [$adminUsername, $adminPassword],
                'headers' => [
                    'OCS-APIRequest' => 'true',
                ],
                'form_params' => [
                    'userid' => $userId,
                    'password' => $password,
                    'displayName' => $displayName,
                    'email' => $email
                ]
            ]);

            return [
                'success' => true,
                'status' => $response->getStatusCode(),
                'message' => 'User created successfully.'
            ];
        } catch (RequestException $e) {
            return [
                'success' => false,
                'status' => $e->getCode(),
                'message' => $e->getMessage(),
            ];
        }
    }
    
	/**
	 * Add a user to a group in Nextcloud.
	 *
	 * @param string $baseUrl Nextcloud Base URL
	 * @param string $adminUsername Admin Username
	 * @param string $adminPassword Admin Password
	 * @param string $userId New User ID
	 * @param string $groupName Group Name
	 * @return array Response Data
	*/
	public static function addUserToGroup($baseUrl, $adminUsername, $adminPassword, $userId, $groupName)
	{
	    $client = new Client();
	    $url = rtrim($baseUrl, '/') . "/ocs/v1.php/cloud/groups/{$groupName}";
	
	    try {
	        $response = $client->request('POST', $url, [
	            'auth' => [$adminUsername, $adminPassword],
	            'headers' => [
	                'OCS-APIRequest' => 'true',
	            ],
	            'form_params' => [
	                'userid' => $userId
	            ]
	        ]);
	
	        return [
	            'success' => true,
	            'status' => $response->getStatusCode(),
	            'message' => 'User added to group successfully.'
	        ];
	    } catch (RequestException $e) {
	        return [
	            'success' => false,
	            'status' => $e->getCode(),
	            'message' => $e->getMessage(),
	        ];
	    }
	}
}
