<?php

namespace App\Http\Controllers;

use App\Models\Devis;
use App\Models\DevisStatus;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\Facture;
use App\Models\Notification;
use App\Models\Observation;
use App\Models\Signature;
use App\Models\TypeDocument;
use App\Models\User;
use Illuminate\Support\Facades\Response;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Image;


class DocumentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id)
    {
        $this->authorize('viewAny', Document::class);

        $user = User::whereId(Auth::user()->id)->with('typedocument')->firstOrFail();
        $array = [];
        foreach ($user->typedocument as $type) {
            array_push($array, $type->id);
        };
        $types = TypeDocument::whereIn('id', $array)->whereHas('document', function ($query) use ($id) {
            $query->where('dossier_id', $id);
        })->get();
        $imgs = Document::where('dossier_id', $id)->whereIn('type_document_id', $array)->whereHas('typedocument', function ($query) {
            $query->where('is_pdf', 0);
        })->get();

        $pdfs = Document::where('dossier_id', $id)->whereIn('type_document_id', $array)->whereHas('typedocument', function ($query) {
            $query->where('is_pdf', 1);
        })->get();

        return view('document.index', compact('imgs', 'pdfs', 'id', 'types'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $this->authorize('create', Document::class);
        if (Auth::user()->role_id != 6) {
            $types = TypeDocument::where('is_pdf', false)->whereNotIn('id', [30, 29, 4, 8, 18, 9, 11])->get();
        } else {
            $user = User::whereId(Auth::user()->id)->with('typedocument')->first();
            $types = TypeDocument::where('is_pdf', false)->whereIn('id', $user->typedocument->pluck('id'))->whereNotIn('id', [30, 29, 4, 8, 18, 9, 11])->get();
        }
        $dossier = Dossier::whereId($id)->firstOrFail();
        if ($dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }

        return view('document.create', compact('types', 'id', 'dossier'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->authorize('create', Document::class);

        $validator = Validator::make(
            $request->all(),
            [
                'type' => 'required',
                'files' => 'required',
                'files.*' => 'required|file'
            ],
            [
                'files.*.required' => 'Ce champ est Obligatoire',
                'files.*.file' => 'Seuls les fichiers images et PDF sont autorisés',
            ]
        );

        if ($validator->fails()) {
            return Redirect::back()->withErrors($validator->messages());
        }

        $dossier = Dossier::whereId($request->dossier)->firstOrFail();
        if ($dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        $type = TypeDocument::whereId($request->type)->firstOrFail();
        if ($type->id == 2) {
            if (!$dossier->guarantee) {
                return redirect()->back()->with('error', 'merci de selectionner une garantie avant d ajouter constat');
            }
        }

        if ($type->id == 5) {
            $devis = Devis::where('dossier_id', $dossier->id)->where('devis_status_id', 9)->get();
            $devicount = count($devis);
            if ($devicount > 0) {
                $status = DevisStatus::whereId(4)->first();
                foreach ($devis as $d) {
                    $d->devis_status_id = $status->id;
                    $d->update();
                    $d->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
                }
            }
        }

        if ($type->id == 6) {
            $facture = Facture::where('dossier_id', $dossier->id)->where('devis_status_id', 9)->get();
            $facturecount = count($facture);
            if ($facturecount > 0) {
                $status = DevisStatus::whereId(4)->first();
                foreach ($facture as $f) {
                    $f->devis_status_id = $status->id;
                    $f->update();
                    $f->facturestatus()->attach($status, ['user_id' => Auth::user()->id]);
                }
            }
        }

        if ($request->pdfs) {
            $array = explode(",", $request->pdfs);
            for ($i = 1; $i < count($array); $i += 2) {
                $image = base64_decode($array[$i]);
                $img = Image::make($image);
                $watermark = Image::make(public_path('/img/amea2.png'))->resize(100, 120)->opacity(50);
                $img->insert($watermark, 'top-left', 10, 10);
                $text = $dossier->ref . " : " . $type->type . " par " . Auth::user()->name . " " . now();

                $img->text($text, 80, 30, function ($font) {
                    $font->file(public_path('fonts/gnuolane.ttf'));
                    $font->size(21);
                    $font->color('#FF0000');
                    $font->align('top');
                    $font->valign('right');
                    $font->angle(0);
                });
                $filename = uniqid() . '.' . 'png';
                Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                Document::create([
                    'path' => $path,
                    'dossier_id' => $dossier->id,
                    'type_document_id' => $type->id
                ]);
            }
        }

        if ($request->file('files')) {
            $files = $request->file('files');
            foreach ($files as $file) {
                $pdfMimes = ['application/pdf', 'application/x-pdf', 'application/acrobat', 'application/vnd.pdf', 'text/pdf', 'text/x-pdf'];
                $isPdf = in_array($file->getMimeType(), $pdfMimes) || strtolower($file->getClientOriginalExtension()) == 'pdf';
                
                if (!$isPdf) {
                    $img = Image::make($file);
                    $watermark = Image::make(public_path('/img/amea2.png'))->resize(100, 120)->opacity(50);
                    $img->insert($watermark, 'top-left', 10, 10);
                    $text = $dossier->ref . " : " . $type->type . " par " . Auth::user()->name . " " . now();
                    $img->text($text, 80, 30, function ($font) {
                        $font->file(public_path('fonts/gnuolane.ttf'));
                        $font->size(21);
                        $font->color('#FF0000');
                        $font->align('top');
                        $font->valign('right');
                        $font->angle(0);
                    });
                    $filename = uniqid() . '.' . File::extension($file->getClientOriginalName());
                    Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                    $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                    // Store the file in the disk
                    Document::create([
                        'path' => $path3,
                        'type_document_id' => $request->type,
                        'dossier_id' => $dossier->id,
                    ]);
                }
            }
            $body = "a Ajouter des nouveaux Document au dossier Ref :" . $dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $dossier->id,
                'body' => $body
            ]);
            \App\Services\SidebarCache::clear();
            return redirect()->route('Dossier.show', $dossier->id)->with('success', 'les Fichier sont Telecharger Avec Succés');
        }


        return redirect()->back();
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Document  $document
     * @return \Illuminate\Http\Response
     */

    public function search($dossier_id, $type_id)
    {
        if ($type_id == "ALL") {
            $documents = Document::whereHas('typedocument', function ($query) {
                $query->where('is_pdf', 0);
            })->whereNotIn('id', [9])->where('dossier_id', $dossier_id)->get();
        } else {
            $documents = Document::where('type_document_id', $type_id)->whereHas('typedocument', function ($query) {
                $query->where('is_pdf', 0);
            })->whereNotIn('id', [9])->where('dossier_id', $dossier_id)->get();
        }
        $array = [];

        foreach ($documents as $document) {
            $d = Storage::disk('s3')->temporaryUrl($document->path, now()->addMinutes(30));
            $document->image = $d;
        }

        return response()->json($documents);
    }

    public function show($id)
    {
        $document = Document::whereId($id)->first();
        return view('document.show', compact('document'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Document  $document
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->authorize('update', Document::class);

        $document = Document::whereId($id)->whereHas('typedocument', function ($query) {
            $query->where('is_pdf', 0);
        })->firstOrFail();

        $dossier = Dossier::whereId($document->dossier_id)->firstOrFail();
        $typedocuments = TypeDocument::where('is_pdf', '0')->whereHas('document', function ($query) use ($dossier) {
            $query->where('dossier_id', $dossier->id);
        })->get();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        $documents = Document::where('dossier_id', $document->dossier_id)
            ->whereHas('typedocument', function ($query) {
                $query->where('is_pdf', 0);
            })->get();

$imageContent = Storage::disk('s3')->get($document->path);
$image = Image::make($imageContent);
$imagePath = Storage::disk('s3')->temporaryUrl($document->path, now()->addMinutes(30));
        // Get the width and height of the image
        // $document->width = $image->width();
        $document->height = $image->height();
        return view('dossiers.editor', compact('document', 'documents', 'dossier', 'typedocuments'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Document  $document
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->authorize('update', Document::class);

        $document = Document::whereId($id)->with('devis', 'facture')->first();
        $dossier = Dossier::whereId($document->dossier_id)->first();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }

        if ($document->type_document_id == 21) {
            $document->signer = 1;
            $document->update();
            $body = "A Signer les Documents A Signer:" . $dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $dossier->id,
                'body' => $body
            ]);
        }

        if ($request->img) {
            $type = TypeDocument::whereId($document->type_document_id)->firstOrFail();
            $url = [];
            $url = explode(",", $request->img);
            $image = base64_decode($url[1]);
            $filename = uniqid() . '.' . 'png';
            Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $image);
            $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
            $doc = Document::create([
                'path' => $path,
                'dossier_id' => $dossier->id,
                'type_document_id' => $type->id,
                'edited' => 1,
                'signer' => 1,
                'facture_mo'=>$document->facture_mo
            ]);
            if ($document->type_document_id == 4 || $document->type_document_id == 29) {
                $devis = Devis::whereId($document->devis[0]->id)->firstOrFail();
                $devis->document()->attach($doc->id);
            }
            if ($document->type_document_id == 8 || $document->type_document_id == 30) {
                $facture = Facture::whereId($document->facture[0]->id)->firstOrFail();
                $facture->document()->attach($doc->id);
            }
        }

        return redirect()->back();
    }



    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Document  $document
     * @return \Illuminate\Http\Response
     */
    public function pdf(Request $request)
    {
        $this->authorize('download', Document::class);

        $array = explode(",", $request->attachements);
        $documents = Document::whereIn('id', $array)->get()->groupBy('typedocument.type');
        if ($request->input('action') == "pdf") {
            $pdf = Pdf::loadView('configuration.pdf.download', compact('documents'));
            return $pdf->stream();
        } elseif ($request->input('action') == "zip") {

            $zipFileName = 'documents.zip';
            $zipFilePath = public_path($zipFileName);
            $zip = new \ZipArchive();
            // Create the ZIP file
            if ($zip->open($zipFilePath, \ZipArchive::CREATE) === TRUE) {
                foreach ($documents as $type => $groupedDocuments) {
                    foreach ($groupedDocuments as $document) {
                        // Get the file path from S3
                        $filePath = $document->path; // The file path in S3

                        // Fetch the file content from S3 as a string
                        $fileContent = Storage::disk('s3')->get($filePath);

                        // Add the content directly to the ZIP file using addFromString
                        // basename($filePath) will be used as the name of the file in the ZIP
                        $zip->addFromString(basename($filePath), $fileContent);
                    }
                }

                // Close the ZIP archive
                $zip->close();

                // Return the ZIP file for download and delete it after sending
                return response()->download($zipFilePath)->deleteFileAfterSend(true);
            } else {
                return response()->json(['error' => 'Failed to create the ZIP file'], 500);
            }
        } else if ($request->input('action') == "delete") {
            $this->authorize('download', Document::class);

            $array = explode(",", $request->attachements);
            $documents = Document::whereIn('id', $array)->where('type_document_id', '!=', 4)->where('type_document_id', '!=', 8)->get();
            foreach ($documents as $document) {
                $document->delete();
            }
            return redirect()->route('home')->with('success', 'Document Supprimer Avec Succés');
        } else {
            foreach ($documents as $doc) {
                $filepath = Storage::disk('s3')->temporaryUrl($doc->path, now()->addMinutes(30));
                Response::download($filepath, $doc->path);
            }
        }
        // add action button in blade and elseif
    }

    // public function deleteAll(Request $request)
    // {
    //     $this->authorize('download', Document::class);



    //     return redirect()->back();

    // }

    public function asigner(Request $request, $id)
    {
        $dossier = Dossier::whereId($id)->firstOrFail();
        $this->authorize('signer', Document::class);

        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        $c = Document::where('dossier_id', $id)->where('type_document_id', 21)->where('signer', 0)->count();
        if ($c < 1) {
            return redirect()->back()->with('error', 'Aucun Document A Signer');
        }
        $imgs = Document::where('dossier_id', $id)->where('type_document_id', 21)->where('signer', 0)->get();
        $dossier = Dossier::whereId($id)->firstOrFail();

        return view('document.signatures', compact('imgs', 'id'));
    }


    public function signer(Request $request, $id)
    {
        $dossier = Dossier::whereId($id)->firstOrFail();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }

        $this->authorize('signer', Document::class);

        $array = explode(",", $request->attachements);
        $documents = Document::whereIn('id', $array)->get();

        if ($request->input('action') == "rejeter") {
            $request->validate([
                'observation' => 'required'
            ]);
            Observation::create([
                'observation' => $request->observation,
                'dossier_id' => $dossier->id,
                'user_id' => Auth::user()->id
            ]);
            foreach ($documents as $doc) {
                $doc->rejected = 1;
                $doc->update();
            }
            $body = "A Rejeté les Documents A Signer:" . $dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $dossier->id,
                'body' => $body
            ]);
            \App\Services\SidebarCache::clear();
            return redirect()->route('Dossier.show', $id)->with('success', 'Document Rejeté Avec Succés');
        } elseif ($request->input('action') == "signer") {
            $type = TypeDocument::whereId(21)->firstOrfail();
            $watermark = Image::make(public_path('/img/sign.png'))->resize(140,130);
            foreach ($documents as $doc) {
               $imageContent = Storage::disk('s3')->get($doc->path);
$image = Image::make($imageContent);

                // Calculate the watermark width as 10% of the document image width
                $watermarkWidth = $image->width() * 0.2;
                $watermarkHeight = $watermarkWidth * ($watermark->height() / $watermark->width());

                // Resize the watermark
                $watermark->resize($watermarkWidth, $watermarkHeight);

                $image->insert($watermark, 'bottom-right', 10, 10);
                $filename = uniqid() . '.png';
                Storage::disk('s3')->put(
                    'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename,
                    $image->stream()
                );
                $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                $doc->path = $path;
                $doc->signer = 1;
                $doc->update();
            }


            $body = "A Signer les Documents A Signer:" . $dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $dossier->id,
                'body' => $body
            ]);
            \App\Services\SidebarCache::clear();
            return redirect()->route('Dossier.show', $id)->with('success', 'Document Signer Avec Succés');
        } elseif ($request->input('action') == "signer2") {
            $type = TypeDocument::whereId(21)->firstOrfail();
            $watermark = Image::make(public_path('/img/sign.png'))->resize(140, 130);
            foreach ($documents as $doc) {
$imageContent = Storage::disk('s3')->get($doc->path);
$image = Image::make($imageContent);

                // Calculate the watermark width as 10% of the document image width
                $watermarkWidth = $image->width() * 0.2;
                $watermarkHeight = $watermarkWidth * ($watermark->height() / $watermark->width());

                // Resize the watermark
                $watermark->resize($watermarkWidth, $watermarkHeight);

                $image->insert($watermark, 'bottom-left', 10, 10);
                $filename = uniqid() . '.png';
                Storage::disk('s3')->put(
                    'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename,
                    $image->stream()
                );
                $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                $doc->path = $path;
                $doc->signer = 1;
                $doc->update();
            }


            $body = "A Signer les Documents A Signer:" . $dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $dossier->id,
                'body' => $body
            ]);
            \App\Services\SidebarCache::clear();
            return redirect()->route('Dossier.show', $id)->with('success', 'Document Signer Avec Succés');
        }
        elseif ($request->input('action') == "signer3") {
            $type = TypeDocument::whereId(21)->firstOrfail();
            $watermark = Image::make(public_path('/img/sign.png'))->resize(140, 130);
            foreach ($documents as $doc) {
$imageContent = Storage::disk('s3')->get($doc->path);
$image = Image::make($imageContent);

                // Calculate the watermark width as 10% of the document image width
                $watermarkWidth = $image->width() * 0.2;
                $watermarkHeight = $watermarkWidth * ($watermark->height() / $watermark->width());

                // Resize the watermark
                $watermark->resize($watermarkWidth, $watermarkHeight);

                $image->insert($watermark, 'bottom-center', 10, 10);
                $filename = uniqid() . '.png';
                Storage::disk('s3')->put(
                    'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename,
                    $image->stream()
                );
                $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                $doc->path = $path;
                $doc->signer = 1;
                $doc->update();
            }


            $body = "A Signer les Documents A Signer:" . $dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $dossier->id,
                'body' => $body
            ]);
            \App\Services\SidebarCache::clear();
            return redirect()->route('Dossier.show', $id)->with('success', 'Document Signer Avec Succés');
        }
    }


    public function reject(Request $request, $id)
    {
        $dossier = Dossier::whereId($id)->firstOrFail();
        if ($dossier->update != 0 && Auth::user()->role_id != 4 ||  $dossier->dossier_status_id == 3 && Auth::user()->role_id != 4) {
            return redirect()->route('Dossier.show', $dossier->id)->with('error', 'Dossier est interdit de le modifier Envoyer une demande a Admin ');
        }
        if (Auth::user()->role_id != 4) {
            abort(403);
        }
        $type = TypeDocument::whereId(21)->firstOrfail();
        $array = explode(",", $request->attachements);
        $documents = Document::whereIn('id', $array)->get();
        foreach ($documents as $doc) {
            $doc->rejected = 1;
            $doc->update();
        }
        $body = "A Rejeté les Documents A Signer:" . $dossier->ref;
        Notification::create([
            'user_id' => Auth::user()->id,
            'dossier_id' => $dossier->id,
            'body' => $body
        ]);
        return redirect()->route('Dossier.show', $id)->with('success', 'Document Rejeté Avec Succés');
    }

    public function destroy($id)
    {
        if (Auth::user()->role_id == 4) {

            $doc = Document::whereId($id)->firstOrFail();
            $doc->delete();
            \App\Services\SidebarCache::clear();
            return redirect()->back()->with('success', 'Document Supprimer Avec Succés');
        }
    }

    public function test()
    {
        return view('document.test');
    }

    public function fileStore(Request $request)
    {
        $file = $request->file('file');
        $type = TypeDocument::whereId($request->type)->first();
        $dossier = Dossier::whereId($request->id)->firstOrFail();
        if ($type->id == 5) {
            $devis = Devis::where('dossier_id', $dossier->id)->where('devis_status_id', 9)->get();
            $devicount = count($devis);
            if ($devicount > 0) {
                $status = DevisStatus::whereId(4)->first();
                foreach ($devis as $d) {
                    $d->devis_status_id = $status->id;
                    $d->update();
                    $d->devisstatus()->attach($status, ['user_id' => Auth::user()->id]);
                }
            }
        }

        if ($type->id == 6) {
            $facture = Facture::where('dossier_id', $dossier->id)->where('devis_status_id', 9)->get();
            $facturecount = count($facture);
            if ($facturecount > 0) {
                $status = DevisStatus::whereId(4)->first();
                foreach ($facture as $f) {
                    $f->devis_status_id = $status->id;
                    $f->update();
                    $f->facturestatus()->attach($status, ['user_id' => Auth::user()->id]);
                }
            }
        }
// Check if file is PDF
        $pdfMimes = ['application/pdf', 'application/x-pdf', 'application/acrobat', 'application/vnd.pdf', 'text/pdf', 'text/x-pdf'];
        $isPdf = in_array($file->getMimeType(), $pdfMimes) || strtolower($file->getClientOriginalExtension()) == 'pdf';
        
        if ($isPdf) {
            // Convert PDF to images using Imagick
            $tempDir = storage_path('app/temp/pdf_' . uniqid());
            if (!file_exists($tempDir)) {
                mkdir($tempDir, 0755, true);
            }
            
            $tempPdfPath = $tempDir . '/' . uniqid() . '.pdf';
            copy($file->getRealPath(), $tempPdfPath);
            $docIds = [];
            
            if (extension_loaded('imagick')) {
                $imagick = new \Imagick();
                $imagick->setResolution(150, 150);
                $imagick->readImage($tempPdfPath);
                $pageCount = $imagick->getNumberImages();
                
                for ($i = 0; $i < $pageCount; $i++) {
                    $imagick->setIteratorIndex($i);
                    $imagick->setImageFormat('png');
                    $imagick->setImageCompressionQuality(90);
                    $imagick->setImageBackgroundColor('white');
                    $imagick->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
                    
                    $tempImagePath = $tempDir . '/' . uniqid() . '.png';
                    $imagick->writeImage($tempImagePath);
                    
                    $img = Image::make($tempImagePath);
                    $watermark = Image::make(public_path('/img/amea2.png'))->resize(100, 120)->opacity(50);
                    $img->insert($watermark, 'top-left', 10, 10);
                    $text = $dossier->ref . " :" . $type->type . " par " . Auth::user()->name . " " . now();
                    $img->text($text, 80, 30, function ($font) {
                        $font->file(public_path('fonts/gnuolane.ttf'));
                        $font->size(21);
                        $font->color('#FF0000');
                        $font->align('top');
                        $font->valign('right');
                        $font->angle(0);
                    });
                    
                    $filename = uniqid() . '.png';
                    Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
                    $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                    $doc = Document::create([
                        'path' => $path3,
                        'type_document_id' => $request->type,
                        'dossier_id' => $dossier->id,
                    ]);
                    $docIds[] = $doc->id;
                    unlink($tempImagePath);
                }
                $imagick->clear();
                $imagick->destroy();
            }
            
            unlink($tempPdfPath);
            rmdir($tempDir);
            \App\Services\SidebarCache::clear();
            return response()->json(['success' => $docIds[0] ?? true, 'count' => count($docIds)]);
        }
        
        // Process regular image
        $img = Image::make($file);
        $watermark = Image::make(public_path('/img/amea2.png'))->resize(100, 120)->opacity(50);
        $img->insert($watermark, 'top-left', 10, 10);
        $text = $dossier->ref . " :" . $type->type . " par " . Auth::user()->name . " " . now();

        $img->text($text, 80, 30, function ($font) {
            $font->file(public_path('fonts/gnuolane.ttf'));
            $font->size(21);
            $font->color('#FF0000');
            $font->align('top');
            $font->valign('right');
            $font->angle(0);
        });
        $filename = uniqid() . '.' . File::extension($file->getClientOriginalName());
        Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $img->stream());
        $path3 = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
        // Store the file in the disk
        $doc = Document::create([
            'path' => $path3,
            'type_document_id' => $request->type,
            'dossier_id' => $dossier->id,
        ]);
        \App\Services\SidebarCache::clear();
        return response()->json(['success' => $doc->id]);
    }
    public function fileDestroy(Request $request)
    {
        $filename =  $request->get('filename');
        Document::whereId($filename)->delete();
        \App\Services\SidebarCache::clear();
        return $filename;
    }
    
    public function getTemporaryUrl($id)
{
    try {
        $document = Document::findOrFail($id);
        
        // Check if user has permission to view this document
        // You may want to add additional authorization checks here
        
        // Generate temporary URL (valid for 30 minutes)
        $url = Storage::disk('s3')->temporaryUrl(
            $document->path,
            now()->addMinutes(30)
        );
        
        return response()->json([
            'success' => true,
            'url' => $url,
            'type' => $document->typedocument->type ?? 'Document',
            'filename' => basename($document->path)
        ]);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => 'Document not found or inaccessible'
        ], 404);
    }
}
/**
 * Download document (streams from S3)
 * 
 * @param int $id Document ID
 * @return \Symfony\Component\HttpFoundation\StreamedResponse
 */
public function download($id)
{
    try {
        $document = Document::findOrFail($id);
        
        // Get the file extension
        $extension = pathinfo($document->path, PATHINFO_EXTENSION);
        $filename = 'document_' . $id . '.' . $extension;
        
        // Stream download from S3
        return Storage::disk('s3')->download($document->path, $filename);
        
    } catch (\Exception $e) {
        abort(404, 'Document not found');
    }
}
}
