<?php

namespace Televox\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReproducirArchivos extends Controller
{
    public function reproducir(Request $request, $id)
    {
        if (!$request->session()->get('descargar', false)) {
            abort(403, 'No tiene permisos para descargar grabaciones');
        } else {
            $datos = $request->validate([
                'archive' => 'boolean|required',
            ]);

            $recording_log = 'recording_log';
            if (array_key_exists('archive', $datos) && $datos['archive'] != null && $datos['archive'] == true) {
                $recording_log = 'recording_log_archive';
            }

            $result = DB::connection('Dialvox')->table("$recording_log AS rl")->join('vicidial_list AS vl', 'rl.lead_id', '=', 'vl.lead_id')->where('rl.recording_id', '=', $id)->addSelect('rl.recording_id AS Nombre')->addSelect(DB::raw("date(rl.start_time) as 'FechaInicio'"))->addSelect(DB::raw("time(rl.start_time) AS 'HoraInicio'"))->addSelect(DB::raw("time(rl.end_time) AS 'HoraFin'"))->addSelect(DB::raw("sec_to_time(rl.length_in_sec) AS 'Duracion'"))->addSelect('rl.filename AS GRAB_ID')->addSelect('rl.user')->addSelect(DB::raw("substr(rl.location,Locate('MP3/',rl.location)+4) AS 'GRAB_FILE'"))->addSelect('rl.extension AS phone_number')->addSelect('rl.lead_id AS lead_id')->first();
            if ($result) {
                if (!\is_dir(public_path('audios'))) {
                    mkdir(public_path('audios'));
                }
                if (!file_exists(\public_path('audios/' . $result->GRAB_ID . '.mp3'))) {
                    if (file_exists(\env('RUTAGRAB', '/mnt/Grabaciones') . DIRECTORY_SEPARATOR . "$result->GRAB_FILE")) {
                        copy(\env('RUTAGRAB', '/mnt/Grabaciones') . DIRECTORY_SEPARATOR . "$result->GRAB_FILE", public_path('audios') . DIRECTORY_SEPARATOR . $result->GRAB_ID . '.mp3');
                    } else {
                        if (file_exists(\env('RUTAGRAB', '/mnt/Grabaciones') . DIRECTORY_SEPARATOR . str_replace('-', '/', $result->FechaInicio) . '/' . str_replace(str_replace('-', '/', $result->FechaInicio) . '/', '', $result->GRAB_FILE))) {
                            copy(\env('RUTAGRAB', '/mnt/Grabaciones') . DIRECTORY_SEPARATOR . str_replace('-', '/', $result->FechaInicio) . '/' . str_replace(str_replace('-', '/', $result->FechaInicio) . '/', '', $result->GRAB_FILE), public_path('audios') . DIRECTORY_SEPARATOR . $result->GRAB_ID . '.mp3');
                        } else {
                            return ['Estado' => 'error', 'Descripcion' => 'No se logro encontrar la grabacion'];
                        }
                    }
                }
                if (\file_exists(\public_path('audios/' . $result->GRAB_ID . '.mp3'))) {
                    DB::connection('Televox')->table('tbl_log')->insertGetId(['ip' => $request->ip(), 'fecha' => date('Y-m-d H:i:s'), 'id_usuario' => $request->session()->get('id'), 'tipo' => 4, 'detalle' => 'El usuario ' . $request->session()->get('usuario') . " escucho la grabacion: $result->GRAB_ID Ext/Usuario: $result->user: Fecha: $result->FechaInicio Hora: $result->HoraInicio"]);
                    DB::connection('Televox')->table('audios_listen')->insert(['id_grab' => $result->GRAB_ID, 'id_usuario' => $request->session()->get('id')]);

                    return ['Estado' => 'ok', 'Nombre' => $result->GRAB_ID . '.mp3'];
                } else {
                    return ['Estado' => 'error', 'Descripcion' => 'No se pudo reproducir la grabacion'];
                }
            } else {
                return ['Estado' => 'error', 'Descripcion' => 'Grabacion no encontrada'];
            }

        }
    }
}
