<?php

namespace App\Http\Controllers;

use App\Models\WebRTCSession;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class WebRTCController extends Controller
{
    // public function uploadData(Request $request)
    // {
    //     try {
    //         $request->validate([
    //             'files' => 'required|array',
    //             'files.*' => 'required|file|max:10240', // optional: 10MB max
    //         ], [
    //             'files.required' => 'Please select at least one folder or file.',
    //             'files.array' => 'Uploaded data must be a group of files.',
    //             'files.*.required' => 'Files are required.',
    //             'files.*.file' => 'Each item must be a valid file.',
    //             'files.*.max' => 'Each file must not exceed 10MB.', // only needed if you use `max`
    //         ]);

    //         // $uuid = Str::uuid()->toString();
    //         // // $folderPath = storage_path("app/files-folders/{$uuid}");
    //         // $folderPath = storage_path("app/files-folders");
    //         // if (!is_dir($folderPath)) {
    //         //     mkdir($folderPath, 0777, true);
    //         // }
    //         // mkdir($folderPath, 0777, true);

    //         foreach ($request->file('files') as $file) {
    //             // function storeImage($file, $path, $existed_file = "")
    //             // {
    //             //     if (!empty($existed_file) && file_exists(public_path($existed_file))) {
    //             //         $this->removeImage($existed_file);
    //             //     }

    //             //     $fileName = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
    //             //     $filePath = $path . $fileName;
    //             //     $file->move(public_path($path), $fileName);
    //             //     return $filePath;
    //             // }
    //             $originalName = $file->getClientOriginalName();
    //             $relativePath = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension(); // preserves folder structure
    //             print_r($relativePath);
    //             // $fullPath = $folderPath . '/' . $relativePath;

    //             // if (!is_dir(dirname($fullPath))) {
    //             //     mkdir(dirname($fullPath), 0777, true);
    //             // }

    //             // file_put_contents($fullPath, file_get_contents($file));
    //         }

    //         $passcode = rand(100000, 999999);

    //         return response()->json([
    //             'status' => 'success',
    //             'data' => $request->all(),
    //             // 'message' => 'Data uploaded Successfully!',
    //             // 'name' => 'Data uploaded Successfully!',
    //             // 'link' => env('APP_URL') . '/d/' . $uuid,
    //             // 'passcode' => $passcode,
    //         ], 201);
    //     } catch (ValidationException $e) {
    //         return response()->json([
    //             'status' => 'error',
    //             'message' => 'Validation failed',
    //             'errors' => $e->errors()
    //         ], 422);
    //     }
    // }

    public function checkFiles(Request $request)
    {
        return response()->json([
            'status' => 'success',
            'message' => $request->file()
        ], 200);
        try {
            $request->validate([
                'room_id' => 'required|string',
                'offer' => 'required|array',
                'passcode' => 'required|string',
            ]);

            WebRTCSession::updateOrCreate(
                ['room_id' => $request->room_id],
                ['offer' => $request->offer, 'passcode' => $request->passcode]
            );

            // Store offer in cache or database
            Cache::put('offer:' . $request->room_id, [
                'offer' => $request->offer,
                'passcode' => $request->passcode,
            ], now()->addMinutes(10));

            return response()->json([
                'status' => 'success',
                'message' => 'Offer stored'
            ], 200);
        } catch (ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        }
    }

    public function sendOffer(Request $request)
    {
        try {
            $request->validate([
                'room_id' => 'required|string',
                'offer' => 'required|array',
                'passcode' => 'required|string',
            ]);

            WebRTCSession::updateOrCreate(
                ['room_id' => $request->room_id],
                ['offer' => $request->offer, 'passcode' => $request->passcode]
            );

            // Store offer in cache or database
            Cache::put('offer:' . $request->room_id, [
                'offer' => $request->offer,
                'passcode' => $request->passcode,
            ], now()->addMinutes(10));

            return response()->json([
                'status' => 'success',
                'message' => 'Offer stored'
            ], 200);
        } catch (ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        }
    }

    public function sendAnswer(Request $request)
    {
        try {
            $request->validate([
                'room_id' => 'required|string',
                'answer' => 'required|array',
            ]);

            $session = WebRTCSession::where('room_id', $request->room_id)->first();

            if (!$session || $session->passcode !== $request->passcode) {
                return response()->json(['error' => 'Invalid passcode'], 403);
            }

            $session->update(['answer' => $request->answer]);

            // Store offer in cache or database
            Cache::put('answer:' . $request->room_id, $request->answer, now()->addMinutes(10));

            return response()->json([
                'status' => 'success',
                'message' => 'Answer stored'
            ], 200);
        } catch (ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        }
    }

    public function getAnswer($roomId)
    {
        try {
            $session = WebRTCSession::where('room_id', $roomId)->first();

            if (!$session) return response()->json(['error' => 'Room not found'], 404);

            $raw = json_decode($session->answer, true);  // first decode
            $answer = is_string($raw) ? json_decode($raw, true) : $raw; // second decode if needed

            return response()->json(['answer' => $answer]);
        } catch (ValidationException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Validation failed',
                'errors' => $e->errors()
            ], 422);
        }
    }

    public function getOffer($roomId)
    {
        $session = WebRTCSession::where('room_id', $roomId)->first();

        if (!$session) return response()->json(['error' => 'Room not found'], 404);

        return response()->json([
            'offer' => $session->offer,
            'passcode' => $session->passcode
        ]);
    }
}
