<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class NextCloudController extends Controller
{
    public function download($file)
    {
        // Decode the file path (should match what was encoded)
        $filePath = base64_decode($file);

        // Nextcloud configuration
        $baseUrl  = rtrim(env('NEXT_CLOUD_URL'), '/'); // e.g. "https://mkt.tunggal-pharma.com"
        $username = env('NEXT_CLOUD_USERNAME');         // e.g. "user_dev"
        $password = env('NEXT_CLOUD_PASSWORD');         // e.g. "userdev12345"

        // Clean up and encode the file path segments
        $filePath = trim((string)$filePath);
        $segments = explode('/', ltrim($filePath, '/'));
        $encodedPath = implode('/', array_map('rawurlencode', $segments));

        // Build the full Nextcloud URL (without embedded credentials)
        $relativePath = "remote.php/dav/files/{$username}/" . $encodedPath;
        $url = $baseUrl . '/' . $relativePath;

        // Initialize cURL to fetch the file
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Set Basic Authentication
        curl_setopt($ch, CURLOPT_USERPWD, "{$username}:{$password}");
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

        // SSL Options (adjust if needed)
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        // *** Add the cookie header to bypass the "Strict Cookie" error ***
        curl_setopt($ch, CURLOPT_COOKIE, "oc_sessionPassphrase=");

        $response  = curl_exec($ch);
        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        // Handle errors
        if ($httpCode !== 200) {
            return response()->json([
                'error' => "Error: Failed to fetch file (HTTP Code: {$httpCode}). " .
                           ($curlError ? " cURL Error: {$curlError}" : '')
            ], $httpCode);
        }

        // Determine the filename for download
        $filename = basename($filePath);

        // Return the file content with download headers
        return response($response, 200)
            ->header('Content-Description', 'File Transfer')
            ->header('Content-Type', 'application/octet-stream')
            ->header('Content-Disposition', "attachment; filename=\"{$filename}\"")
            ->header('Expires', '0')
            ->header('Cache-Control', 'must-revalidate')
            ->header('Pragma', 'public')
            ->header('Content-Length', strlen($response));
    }
}
