<?php

namespace App\Http\Controllers\SIS;

use App\Http\Controllers\Controller;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class RecibosController extends Controller
{

    /**
     * NubeController constructor.
     * @param $IDAOCliente
     * @param $IDAOClienteDireccion
     */
    private $disk = "app/public";

    public function __construct()
    {
    }


    public function listar_recibos(Request $request)
    {

        $data_request = $this->get_data_request($request);

        $flag_request = false;

        if ($this->ACCESSTOKEN($data_request['token'], $data_request['credenciales'], $Usr, $errors)) {

            DB::beginTransaction();

            try {
                ob_start();
                date_default_timezone_set('America/Mexico_City');
                setlocale(LC_TIME, 'es_VE.UTF-8', 'esp');
                set_time_limit(0);

                $ruta = $data_request['data']['ruta'];
                $result = array();


                if($ruta) {
                    $directories = Storage::disk('local')->directories('public/recibos'. '/'.$ruta);
                    foreach ($directories as $row) {
                        $output = str_replace("\\/", "/", $row);
                        $output = str_replace("public/recibos/", "", $output);
                        $result[] = $output;
                    }

                    $files = Storage::disk('local')->files('public/recibos'. '/'.$ruta);
                    if (count($files) > 0) {
                        foreach ($files as $row) {
                            $arc = explode('/', $row);

                            if ($arc[count($arc) - 1] != ".DS_Store") {
                                $output = str_replace("\\/", "/", $row);
                                $output = str_replace("public/recibos/", "", $output);
                                $result[] = $output;
                            }
                        }
                    }
                } else {
                    $files = Storage::disk('local')->directories('public/recibos');
                    foreach ($files as $row) {
                        $output = str_replace("\\/", "/", $row);
                        $output = str_replace("public/recibos/", "", $output);
                        $result[] = $output;
                    }
                }


                /*if ($handler = opendir("public/recibos/")) {
                    while (false !== ($file = readdir($handler))) {
                        if ($file != '.' && $file != '..') {
                            $files[] = $file;
                        }
                    }
                    closedir($handler);
                }*/

                if ($result == null) {
                    $flag_request = true;
                    $status = 400;
                    $message = "No se encontraron datos.";
                    $data = array();
                    DB::rollback();
                } else {
                    $flag_request = true;
                    $status = 200;
                    $message = "Datos encontrados.";
                    $data = $result;
                    DB::commit();
                }

                $response = [
                    "success" => $flag_request,
                    "status" => $status,
                    "message" => $message,
                    "data" => $data,
                ];

            } catch (Exception $e) {
                DB::rollback();
                $log = $this->ErrorTransaction($e, $request);
                return $log;
            }
        } else {
            $response = array(
                'success' => $flag_request,
                'status' => 400,
                'message' => 'Acceso denegado, token de acceso no válido',
                "errors" => $errors
            );
        }

        return $response;
    }

    public function descargar_zip_recibos(Request $request)
    {
        $data_request = $this->get_data_request($request);

        $flag_request = false;

        if ($this->ACCESSTOKEN($data_request['token'], $data_request['credenciales'], $Usr, $errors)) {

            $validator = Validator::make($data_request['data'], [
                'ruta' => '',
            ]);

            if (!$validator->fails()) {

                DB::beginTransaction();

                try {
                    $ruta = $data_request['data']['ruta'];

                    $body = json_encode([
                        "path" => $ruta
                    ]);

                    $client = new Client([
                        'headers' => [
                            'Authorization' => 'Bearer ' . env('DROPBOX_ACCESS_TOKEN'),
                            'Dropbox-API-Arg' => $body,
                        ],
                    ]);

                    $data = $client->post('https://content.dropboxapi.com/2/files/download_zip');
                    Storage::put('dropboxxxxx.zip', $data->getBody());
                    //dd($data);
                    //$result = json_decode($data->getBody()->getContents());

                    if ($data == null) {
                        $flag_request = true;
                        $status = 400;
                        $message = "No se encontraron datos.";
                        $data = array();
                        DB::rollback();
                    } else {
                        $flag_request = true;
                        $status = 200;
                        $message = "Datos encontrados.";
                        $data = $data;
                        DB::commit();
                    }


                    $response = [
                        "success" => $flag_request,
                        "status" => $status,
                        "message" => $message,
                        "data" => $data
                    ];

                } catch (Exception $e) {
                    DB::rollback();
                    $log = $this->ErrorTransaction($e, $request);
                    return $log;
                }
            } else {
                $response = [
                    "success" => $flag_request,
                    "status" => 400,
                    "message" => "No se encontraron datos.",
                    "errors" => $validator->errors()->messages()
                ];
            }

        } else {
            $response = array(
                'success' => $flag_request,
                'status' => 400,
                'message' => 'Acceso denegado, token de acceso no válido',
                "errors" => $errors
            );
        }

        return $response;
    }

}
