<?php

namespace App\Http\Controllers;

use Kreait\Firebase\Factory;
use Illuminate\Http\Request;
use Google\ApiCore\RequestBuilder;
use \DataTime;
use League\CommonMark\Extension\CommonMark\Node\Block\ListItem;

use function Termwind\render;

class ZdezController extends Controller

{

    function index(Request $request)
    {


        if ($request->input('search-download')) {
            return redirect()->route('download_dashboard', ['a' => $request->input('search-download')]);
        }


        if ($request->input('search-report')) {
            $tipo_report = $request->input('type');
           // dd($request->input('search-report'));
            return redirect()->route('report_dashboard', ['a' => $request->input('search-report'), 'tipo' => $tipo_report]);
        }


        return view('dashboard');
    }
    public function show(String $a, String $tipo)
    {

         
         $factory = (new Factory)->withServiceAccount('../firebase_credentail.json')->withDatabaseUri('zero-dez-f2c25.appspot.com')->createStorage();

        $objects =  $factory->getBucket()->objects([
            'prefix' => $a,
             
        ]);


        $names = [];
        foreach ($objects as $object) {
            $name  = $object->name();
            $names[] = $name;
        }

        $folders = [];
        //dd($names);

        foreach ($names as $name) {
            $cond_manutencao = explode('/', $name)[0] == 'CONSTRUCAO';
            if($cond_manutencao){
                $cava_name = explode('/', $name)[4];
                $photo_id = explode('.', explode('/', $name)[5])[0];
                
            }else{
                $cava_name = explode('/', $name)[1];
                $photo_id = explode('.', explode('/', $name)[2])[0];
                
            }
             
            
            if ($tipo == "S001") {
                //dd($cava_name);
                $cond_report = str_contains(strtolower($cava_name), 'explosivo') || str_contains(strtolower($cava_name), 'embasamento') ||  str_contains(strtolower($cava_name), 'rocha');
             } elseif ($tipo == "S002") {
                $cond_report = (str_contains(strtolower($cava_name), 'poda'));
            } elseif ($tipo == "S003") {
                $cond_report = (str_contains(strtolower($cava_name), 'arrastamento'));
            } elseif ($tipo == 'S004') {
                $cond_report = (str_contains(strtolower($cava_name), 'sucata'));
            } elseif ($tipo == 'S005') {
                $cond_report = true;
            }


            if ($cond_report) {

                $url = $factory->getBucket()->object($name)->signedUrl(new \DateTime('+1 hour'));

                if (key_exists($cava_name, $folders)) {

                    array_push($folders[$cava_name], [$photo_id, $url]);
                } else {
                    $folders[$cava_name] = [[$photo_id, $url]];
                };
            }
        };

        switch ($tipo) {
            case 'S001':
                return view('templates-report.S001',  ['a' => $a,  'folders' => $folders]);
                break;
            case 'S002':
                return view('templates-report.S002',  ['a' => $a,  'folders' => $folders]);
                break;
            case 'S003':
                return view('templates-report.S003',  ['a' => $a,  'folders' => $folders]);
                break;
            case 'S004':
                return view('templates-report.S004',  ['a' => $a,  'folders' => $folders]);
                break;
            default:
                # code...
                break;
        }
        
    }


    public function download(String $a)
    {
        $factory = (new Factory)->withServiceAccount('../firebase_credentail.json')->withDatabaseUri('zero-dez-f2c25.appspot.com')->createStorage();
        // $st = $factory->createStorage()->getBucket();
        // dd($st);

        //$objets =  $factory->getBucket()->objects(['prefix'=>['A']]);



        $objets =  $factory->getBucket()->objects([
            'prefix' => $a,
        ]);





        // if(empty(iterator_to_array($objets))){
        //     return view('nocavas');
        // }

        $zipFilePath = __DIR__ . '/temp.zip';
        // Criar um objeto ZipArchive
        $zip = new \ZipArchive();

        if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === TRUE) {
            // Listar os arquivos e diretórios no caminho do Firebase Storage
            $files = $factory->getBucket()->objects([
                'prefix' => $a,
            ]);

            foreach ($files as $file) {
                $filePath = $file->name();
                // Obter o conteúdo do arquivo do Firebase Storage
                $fileContent = $factory->getBucket()->object($filePath)->downloadAsString();
                // Adicionar o conteúdo do arquivo ao zip
                $zip->addFromString(substr($filePath, strlen($a)), $fileContent);
            }
            // Fechar o arquivo zip
            $zip->close();

            // Define os cabeçalhos HTTP para forçar o download do arquivo zip
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="' . $a . '.zip" ');
            header('Content-Length: ' . filesize($zipFilePath));

            // Envie o arquivo zip para o navegador
            readfile($zipFilePath);

            // Exclua o arquivo zip temporário
            unlink($zipFilePath);
        } else {
            echo 'Não foi possível criar o arquivo zip';
        }

        // foreach($objets as $obj) {
        //         print( $factory->getBucket()->object($obj->name())->signedUrl(New \DateTime('+1 hour') ).'<br>');
        // }


    }

 

   

    public function manutencao_list(String $ano, String $mes) {
        $factory = (new Factory)
            ->withServiceAccount('../firebase_credentail.json')
            ->withDatabaseUri('https://zero-dez-f2c25.firebaseio.com');
    
        $storage = $factory->createStorage();
        $bucket = $storage->getBucket();
         
        $objects = $bucket->objects([
            
           'prefix'=> 'CONSTRUCAO/'.$ano.'/'.$mes,
        ]);

        $names = [];
        foreach ($objects as $object) {
            // Explode o caminho e pega o valor desejado (por exemplo, a posição 3 ou 4)
            $parts = explode('/', $object->name());
            $key = $parts[3] ?? null; // Posição 3
            $value = $parts[4] ?? null; // Posição 4
        
            // Apenas adiciona ao array se o valor não for nulo e ainda não estiver presente
            if ($key !== null && $value !== null) {
                if (!isset($names[$key])) {
                    $names[$key] = []; // Inicializa o array para este key
                }
                if (!in_array($value, $names[$key])) {
                    $names[$key][] = $value; // Adiciona apenas valores únicos
                }
            }  
        }      

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

}
