<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use MongoDB\Client as MongoDBClient;
use MongoDB\BSON\UTCDateTime;
use MongoDB\BSON\ObjectId;
use App\Helper\MongoHelper;
use Illuminate\Support\Facades\Auth;



class AdminPortalController extends Controller
{


    protected $mongoDB;
    protected $mongoHelper;

    public function __construct(MongoDBClient $mongoDB)
    {
        $this->middleware('auth');
        $this->mongoDB = $mongoDB;
        $this->mongoHelper = new MongoHelper($this->mongoDB);
    }

    /**
     * Display a listing of the resource.
     */
    public function index($camera_id = "")
    {
        $collection = $this->mongoDB->dataprocess->cameras;
        $cameras = $collection->find(['user_id' => Auth::user()->uuid]);

        $collection_custom_alarm = $this->mongoDB->dataprocess->camera_alarms_settings;

        $camera_settings = "";
        if ($camera_id) {
            $camera_settings = $collection_custom_alarm->findOne([
                'camera_id' => new \MongoDB\BSON\ObjectID($camera_id),
            ]);
        }

        return view('admin_portal.index', compact('cameras', 'camera_id', 'camera_settings'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function store(Request $request)
    {

        if(!$request->region_id || !$request->camera_id){
            return redirect()->back()->with('error', 'Please select a camera');
        }
        $collection = $this->mongoDB->dataprocess->camera_alarms_settings;

        $threshold_values = [
            '240' => '250',    // Medium quality threshold for 240p
            '360' => '600',    // Medium quality threshold for 360p
            '480' => '1000',   // Medium quality threshold for 480p
            '720' => '2000',   // Medium quality threshold for 720p
            '1080' => '4000',  // Medium quality threshold for 1080p
            '1440' => '6000',  // Medium quality threshold for 1440p
            '2160' => '10000'  // Medium quality threshold for 2160p (4K)
        ];


        $setThreshold_value = isset($threshold_values[$request->input('threshold_value')]) ? $threshold_values[$request->input('threshold_value')] : $request->input('threshold_value');



        $alarmConfig = [
            'camera_id' => new ObjectId($request->input('camera_id')),
            'region_id' => new ObjectId($request->input('region_id')),
            'user_id' => auth()->user()->uuid,
            'blur_detection' => $request->has('blur_detection') ? 1 : 0,
            'black_detection' => $request->has('black_detection') ? 1 : 0,
            'motion_detection' => $request->has('motion_detection') ? 1 : 0,
            'enable_disable_stream' => $request->has('enable_disable_stream') ? 1 : 0,
            'threshold' => $request->has('threshold') ? 1 : 0,
            'threshold_value' => $setThreshold_value,
            'latency' => $request->has('latency') ? 1 : 0,
            'latency_value' => $request->input('latency_value') ?? 1,
            'updated_at' => new \MongoDB\BSON\UTCDateTime(now()),
        ];





        // Log the configuration for debugging
        // \Log::info('Alarm Configuration:', $alarmConfig);

        try {
            // Check if a document already exists
            $existingConfig = $collection->findOne([
                'camera_id' => new ObjectId($request->camera_id),
                'user_uuid' => $request->input('user_uuid')
            ]);

            if ($existingConfig) {
                // Update existing document
                $result = $collection->updateOne(
                    [
                        'camera_id' => new ObjectId($request->camera_id),
                        'user_uuid' => $request->input('user_uuid')
                    ],
                    ['$set' => $alarmConfig]
                );
                $success = $result->getModifiedCount() > 0;
            } else {
                // Insert new document
                $result = $collection->insertOne($alarmConfig);
                $success = $result->getInsertedCount() > 0;
            }

            if ($success) {
                return redirect()->route('admin_portal_index', ['camera_id' => $request->camera_id])->with('success', 'Alarm configuration saved successfully.');
            } else {
                return redirect()->back()->with('info', 'No changes were made to the alarm configuration.');
            }
        } catch (\Exception $e) {
            \Log::error('Error saving alarm configuration: ' . $e->getMessage());
            return redirect()->back()->with('error', 'An error occurred while saving the alarm configuration.');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
