<?php

namespace App\Http\Controllers;

use Kreait\Firebase\Factory;
use Illuminate\Http\Request;
use Kreait\Firebase\ServiceAccount;
use Google\Cloud\Firestore\FirestoreClient;


class FirebaseController extends Controller
{
    public function getEvidencesFolders(String $a)
    {
        $firebase = (new Factory)->withServiceAccount('../firebase_credentail.json')->withDatabaseUri('zero-dez-f2c25.appspot.com');
        $storage = $firebase->createStorage();

        // Substitua 'sua-pasta-raiz' pelo nome da pasta raiz no Firebase
        $bucket = $storage->getBucket();
        //metodos de $bucket podem ser encontrados em https://cloud.google.com/storage/docs/json_api/v1/buckets


        $objects = $bucket->objects(
            [
                'prefix' => $a,


            ]
        );




        $folders = [];
        $sucata_qnt = 0;
        foreach ($objects as $object) {
            if (str_contains($object->name(), 'SUCATA')) {
                $sucata_qnt++;
            }

            $name  = explode('/', $object->name())[1];
            $folders[] = $name;
        }

        $folders[] = (string) $sucata_qnt;
        $folders = array_values(array_unique($folders));
        // foreach ($names as $name) {
        //     $cava_name = explode('/', $name)[1];
        // }

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

    public function getProduction(String $date1, String $date2, String $worker=NULL){

      

        $firebase = (new Factory)->withServiceAccount('../firebase_credentail.json')->withDatabaseUri('zero-dez-f2c25.appspot.com')->createFirestore();
  
        $firestore = $firebase->database();
 

        $query = $firestore->collection($worker);
        $documents = $query->documents();
        
        $dataArray = [];
        
        foreach ($documents as $document) {
            if ($document->exists()) {
                $data = $document->data();
        
                if ($document->id() >= $date1 && $document->id() <= $date2) {
                    $dataArray[] = [
                        'date' => $data['date'],
                        'A' => $data['A'],
                        'production' => $data['production']
                    ];
                }
            } else {
                $dataArray[] = ['error' => 'Documento não encontrado'];
            }
        }
        
        // Retornar dados em JSON
        header('Content-Type: application/json');
        return response()->json($dataArray);
        
  
    
    }
}
