<?php

namespace App\Http\Controllers;

use App\Models\Call;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\Notification;
use App\Models\TypeDocument;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use OpenTok\MediaMode;
use OpenTok\OpenTok;
use OpenTok\Role;

class CallController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function create(Request $request)
    {
        $this->authorize('create', Call::class);

        $dossier = Dossier::whereId($request->dossier_id)->first();
        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 ');
        }
        // Create a Guzzle client
        $client = new Client();

        // API endpoint URL
        $apiEndpoint = 'https://api.whereby.dev/v1/meetings';

        // Data to be sent in the POST request
        $postData = [
            "isLocked" => false,
            "roomNamePrefix" => "",
            "roomNamePattern" => "uuid",
            "roomMode" => "normal",
            "endDate" => "2099-03-25T13:30:00.000Z",
            "fields" => []
        ];

        // Your authentication token
        $accessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmFwcGVhci5pbiIsImF1ZCI6Imh0dHBzOi8vYXBpLmFwcGVhci5pbi92MSIsImV4cCI6OTAwNzE5OTI1NDc0MDk5MSwiaWF0IjoxNjk2OTQ3NTY0LCJvcmdhbml6YXRpb25JZCI6MTk2NjMyLCJqdGkiOiJlOWE0MzJhMC0xZWVkLTQyNWUtYjhkZi1lOTRmMmMyZDhlNzkifQ.L7_IlSsjeRgbHE6KieJmOQC-nWzU1mbnJSRNF3Im2_Y';

        // Make a POST request to the API with the authentication token in the headers
        $response = $client->post($apiEndpoint, [
            'headers' => [
                'Authorization' => 'Bearer ' . $accessToken,
                'Content-Type' => 'application/json', // adjust the content type based on the API requirements
            ],
            'json' => $postData,
        ]);
        $responseBody = $response->getBody()->getContents();

        if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
            // Successful request, handle the response
            $responseData = json_decode($responseBody, true);
            // Do something with $responseData

            $body = "A Creer une Appele Video Dossier Ref :" . $dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $dossier->id,
                'body' => $body
            ]);

            return view('call.whereby', compact('dossier', 'responseData'));
        } else {
            return redirect()->back()->with('error', 'Erreur');
        }
    }

    public function createClass(Request $request)
    {
        $this->authorize('create', Call::class);
        // Get the currently signed-in user
        $user = $request->user();
        // Throw 403 if student tries to create a class
        // if ($user->role_id != 4) return back(403);

        $dossier = Dossier::whereId($request->dossier_id)->first();
        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 ');
        }
        // Instantiate a new OpenTok object with our api key & secret
        $opentok = new OpenTok(env('VONAGE_API_KEY'), env('VONAGE_API_SECRET'));
        // Creates a new session (Stored in the Vonage API cloud)
        $session = $opentok->createSession(array('mediaMode' => MediaMode::ROUTED));
        // Create a new virtual class that would be stored in db
        $class = new Call();
        // Generate a name based on the name the teacher entered
        $class->name = $user->name . $request->input("name");
        // Store the unique ID of the session
        $class->session_id = $session->getSessionId();
        $class->dossier_id = $request->dossier_id;
        // Save this class as a relationship to the teacher
        $user->call()->save($class);
        // Send the teacher to the classroom where real-time video goes on
        $uid = uniqid();
        $url = URL::temporarySignedRoute(
            'classroom',
            now()->addMinutes(30),
            ['dossier_id' => $request->dossier_id, 'class_id' => $class->id, 'token' => $uid]
        );
        $body = "A Creer une Appele Video Dossier Ref :" . $dossier->ref;
        Notification::create([
            'user_id' => Auth::user()->id,
            'dossier_id' => $dossier->id,
            'body' => $body
        ]);

        return view('call.show', compact('dossier', 'url'));
    }

    public function showClassRoom(Request $request, $dossier_id, $class_id)
    {
        if (!$request->hasValidSignature()) {
            abort(403);
        }
        // Get the currently authenticated user

        $user = $request->user();
        // Find the virtual class associated by provided id

        $virtualClass = Call::whereId($class_id)->firstOrFail();
        $dossier = Dossier::whereId($dossier_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 ');
        }

        // dd($virtualClass);
        // Gets the session ID
        $sessionId = $virtualClass->session_id;
        // Instantiates new OpenTok object
        $opentok = new OpenTok(env('VONAGE_API_KEY'), env('VONAGE_API_SECRET'));
        // Generates token for client as a publisher that lasts for one week
        $token = $opentok->generateToken($sessionId, ['role' => Role::PUBLISHER, 'expireTime' => time() + (7 * 24)]);
        // Open the classroom with all needed info for clients to connect

        $types = TypeDocument::whereIn('id', [5, 6, 7])->get();

        return view('call.class', compact('token', 'user', 'sessionId', 'dossier_id', 'types'));
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $dossier_id)
    {
        $this->authorize('viewAny', Call::class);
        $dossier = Dossier::whereId($dossier_id)->first();
        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 ');
        }
        $user = $request->user();
        $classes = Call::where('dossier_id', $dossier_id)->orderBy('name', 'asc')->take(10);
        return view('call.create', compact('user', 'classes', 'dossier_id', 'dossier'));
    }

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

        try {
            $dossier = Dossier::whereId($request->dossier_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 ');
            }
            $dossier = Dossier::whereId($dossier_id)->first();
            $type = TypeDocument::whereId(9)->first();

            // Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type  ,  $request->video);
            // Store the file in the disk
            $file = $request->video;
            $filename = uniqid() . '.mp4';
            $path3 = $file->storeAs('documents/' . $dossier->ref . '/' . $type->type, $filename, 's3');
            Document::create([
                'path' => $path3,
                'type_document_id' => $type->id,
                'dossier_id' => $dossier_id,
            ]);
            $body = "a Ajouter un Enregistement Dossier Ref :" . $dossier->ref;
            Notification::create([
                'user_id' => Auth::user()->id,
                'dossier_id' => $dossier->id,
                'body' => $body
            ]);
        } catch (\Throwable $th) {
            return response()->json([
                'status' => false,
                'message' => $th->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Call  $call
     * @return \Illuminate\Http\Response
     */
    public function saved($dossier_id)
    {
        $this->authorize('viewAny', Call::class);

        $dossier = Dossier::whereId($dossier_id)->with('document')->first();
        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 ');
        }
        $documents = Document::where('dossier_id', $dossier_id)->where('type_document_id', 9)->get();
        return view('call.saved', compact('documents'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Call  $call
     * @return \Illuminate\Http\Response
     */
    public function picture($dossier_id, Request $request)
    {
        $this->authorize('screen', Call::class);
        //need try catch

        $dossier = Dossier::whereId($dossier_id)->with('document')->first();
        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(11)->first();
        //store screenshots
        if ($request->img) {
            $array = explode(",", $request->img);

                $image = base64_decode($array[1]);
                $filename = uniqid() . '.' . 'png';
                Storage::disk('s3')->put('documents/' . $dossier->ref . '/' . $type->type . '/' . $filename, $image);
                $path = 'documents/' . $dossier->ref . '/' . $type->type . '/' . $filename;
                Document::create([
                    'path' => $path,
                    'dossier_id' => $dossier->id,
                    'type_document_id' => $type->id
                ]);

        }

        return redirect()->route('Dossier.show', $dossier->id);
    }


    // /**
    //  * Update the specified resource in storage.
    //  *
    //  * @param  \Illuminate\Http\Request  $request
    //  * @param  \App\Models\Call  $call
    //  * @return \Illuminate\Http\Response
    //  */
    public function update(Request $request)
    {

        // //handle base64 encoded images here
        // $name = Str::random(15) . '.png';
        // // decode the base64 file
        // $file = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $request->input('photo')));
        // Storage::put($name, $file);
        // Storage::put($name, $file);

        // //to stream the upload with putFileAs or putFile,
        // //a resource of Illuminate\Http\File or  //Illuminate\Http\UploadedFile type is required
        // $file = new File(public_path($name));
        // $response = Storage::disk('s3')
        //     ->putFileAs('images', $file, $name);
        // if ($response) {
        //     //clean up local storage before response
        //     Storage::delete($name);
        //     return response()->json(
        //         [
        //             'message' => 'File uploaded',
        //             'data' => ['file' => $response]
        //         ]
        //     );
        // } else {
        //     return response()->json(['message' => 'Error uploading File',
        //     'data' => ['file' => $response]], 400);
        // }

    }

    // /**
    //  * Remove the specified resource from storage.
    //  *
    //  * @param  \App\Models\Call  $call
    //  * @return \Illuminate\Http\Response
    //  */
    // public function destroy( Call $call)
    // {
    //     //
    // }

}
