<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use MongoDB\Client as MongoDBClient;


class ForensicController extends Controller
{
    protected $mongoDB;

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

    public function index($camera_id, $page = 1)
    {

        $collection = $this->mongoDB->dataprocess->photo_frame_detect;

        // $mainFrames1 = $collection->find([
        //     'camera_id' => new \MongoDB\BSON\ObjectID($camera_id),
        // ]);
        // $mainFrames1 = $collection->find(
        //     [],
        //     [
        //         'limit' => 12,
        //         'sort' => ['created_at' => 1]
        //     ]
        // );

        $limit = 10; // Number of items per page

        $mainFrames1 = $collection->find(
            ['camera_id' => new \MongoDB\BSON\ObjectID($camera_id)],
            [
                'limit' => $limit,
                'skip' => ($page - 1) * $limit // Calculate the number of documents to skip for pagination
            ]
        );

        $mainFrames = [];
        foreach ($mainFrames1 as $document) {
            // Convert BSONDocument to array
            $frameArray = $document->getArrayCopy();

            // Convert BSONArray within the document to array if exists
            if (isset($frameArray['info']) && $frameArray['info'] instanceof \MongoDB\Model\BSONArray) {
                $frameArray['info'] = $frameArray['info']->getArrayCopy();
            } elseif (isset($frameArray['info']) && is_array($frameArray['info'])) {
                // Ensure all items in 'info' are arrays
                foreach ($frameArray['info'] as &$infoItem) {
                    if ($infoItem instanceof \MongoDB\Model\BSONDocument) {
                        $infoItem = $infoItem->getArrayCopy();
                    }
                }
            }

            $mainFrames[] = $frameArray;
        }


        // Count total items for pagination
        $totalItems = $collection->count(['camera_id' => new \MongoDB\BSON\ObjectID($camera_id)]);
        $totalPages = ceil($totalItems / $limit);

        return view("forensic.view_frame", compact('mainFrames', 'page', 'totalPages', 'camera_id'));
    }


    public function face_detected_list($camera_id, $photo_frame_id)
    {

        $collection = $this->mongoDB->dataprocess->photo_face_detect;

        $faces_list = $collection->find([
            'camera_id' => new \MongoDB\BSON\ObjectID($camera_id),
            'main_frame_id' => new \MongoDB\BSON\ObjectID($photo_frame_id),
        ]);

        return view("forensic.view_face", compact('faces_list'));
    }

}
