<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Request;

use App\Custom\SQLConnection;
use App\Custom\Misc;

use Shuchkin\SimpleXLSXGen;

class ImperiumController extends Controller {
	public static function clientes() {
		$periodo = Misc::periodoVencido('m/Y');
		return view('/imperium/clientes')->with(compact(['periodo']));
	}

	public static function datosClientes() {
		$clientes = SQLConnection::backendStoreProcedure('Imperium_buscar_clientes', array(), 'select');
		return json_encode($clientes);
	}

	// FUNCIONES PARA LAS VISTAS DE IMPERIUM DEL VERDE
	public static function clientesV() {
		$periodo = Misc::periodoVencido('m/Y');
		$hoy = new \DateTime();
		$mes = clone $hoy;
		$mes->sub(new \DateInterval('P1M'));

		return view('/imperium/clientes_verde')->with(compact('periodo', 'hoy', 'mes'));
	}

	public static function datosClientesV() {
		$desde = Request::input('desde');
		$hasta = Request::input('hasta');
		$clientes = SQLConnection::backendStoreProcedure('Imperium_buscar_clientes', array(NULL, $desde, $hasta), 'select');

		return $clientes;
	}

	public static function exportarDatosCliente() {
		// Obtener los datos del cliente y otras variables
		$cliente = Request::input('cliente');
		$cliente_nombre = Request::input('nombre_cliente');
		$desde = Request::input('desde');
		$hasta = Request::input('hasta');
		$accion = Request::input('accion');

		// Reemplazar espacios en el nombre del cliente por guiones bajos
		$cliente_nombre = str_replace(' ', '_', $cliente_nombre);

		// Obtener la fecha actual
		$fecha = date("Y-m-d");

		if ($accion == 'F') {
			// Configuracion para exportar datos de facturacion
			$nombreExcel = 'FACTURACION_' . $cliente_nombre . '_' . $fecha . '.xlsx';
			$store = 'Imperium_reporte_facturacion';
			$params = array($cliente, null, 'REPORTE_FECHA', $desde, $hasta);
			$header = ['estado_contratista', 'cuit_contratista', 'nombre_contratista', 'nombre_cliente', 'tipo_contratista', 'nombre_usuario', ',apellido_usuario', 'email', 'usuario', 'nombre__contratista_principal', 'cuit_contratista_principal', 'subcontratistas', 'empleados', 'vehiculos', 'total_recursos', 'SE_FACTURA'];
		} elseif ($accion == 'B') {
			// Configuracion para exportar datos de bajas
			$nombreExcel = 'BAJAS_' . $cliente_nombre . '_' . $fecha . '.xlsx';
			$store = 'Imperium_Reporte_Bajas_Desafectaciones';
			$params = array($desde, $hasta, $cliente);
			$header = ['nombre_cliente', 'CONTRATISTA', 'CUIT', 'ACCION', 'SECCION', 'TIPO', ',DESCRIPCION', 'EMPLEADO', 'CUIL', 'BAJA_AFIP', 'VEHICULO', 'DOMINIO', 'SUBCONTRATISTA', 'CUIT_SUBC', 'FECHA_HORA', 'USUARIO', 'EMAIL'];
		} elseif ($accion == 'RD') {
			// Configuracion para exportar un reporte
			$nombreExcel = 'REPORTE_' . $cliente_nombre . '_' . $fecha . '.xlsx';
			$store = 'Imperium_reporte_documentacion_FULL2';
			$params = array($cliente, $desde, $hasta, null, 'N,I,V,R', null, null);
			$header = ['CLIENTE', 'ACTIVIDAD', 'RAZON_SOCIAL', 'CUIT', 'CODIGO', 'ESTADO_CONTRATISTA', 'DOCUMENTO', 'SECCION', 'AÑO', 'MES', 'RECURSO', 'CUIT_EMPLEADO', 'ESTADO_RECURSO', 'TIPO_RECURSO', 'VTO_CARGA', 'FECHA_TOLERANCIA', 'ESTADO', 'DETALLE', 'CUMPLIMIENTO_ANUAL', 'CUMPLIMIENTO_ANUAL_TEXTO', 'SUBCONTRATISTA', 'CUIT_SUBCONTRATISTA', 'DIF_CARGA', 'DIF_VERIF', 'MODALIDAD'];
		}

		// Obtener datos del reporte, facturacion o baja 
		$data_reporte = SQLConnection::backendStoreProcedure($store, $params, 'select');
		// dd($store, $params);

		// Preparar el array para el archivo Excel
		$arreglo = [];
		array_push($arreglo, $header);
		foreach ($data_reporte as $row) {
			unset($row->kkk);
			unset($row->contratista_1);
			$row = get_object_vars($row);
			$row = array_values($row);
			array_push($arreglo, $row);
		}

		// Generar el archivo Excel con la libreria SimpleXLSXGen
		$xlsx = SimpleXLSXGen::fromArray($arreglo);
		$xlsx->saveAs(env('PATH_EXCEL_GEN') . '/' . $nombreExcel);

		// Devolver el nombre del archivo y la ruta para su descarga
		return json_encode(['filename' => $nombreExcel, 'path' => (ENV('RUTA_EXCEL_GEN') . '/' . $nombreExcel) . '?v=' . rand()]);
	}

	public static function contratistasV() {
		$periodo = Misc::periodoVencido('m/Y');
		$clientes = SQLConnection::backendStoreProcedure('Imperium_buscar_clientes', array(), 'select');

		return view('/imperium/contratistas_verde')->with(compact('periodo', 'clientes'));
	}

	public static function getRemoteLogin() {
		$contratista = Request::input('contratista');
		$cliente = Request::input('cliente');
		$data = SQLConnection::backendStoreProcedure('Imperium_buscar_contratistas', array('search', $contratista), 'selectOne');
		$c = urlencode(Misc::encrypt($data->cliente . '|' . $data->contratista . '|' . $data->user_id . '|' . date('Y-m-d')));
		$url = env('URL_IMPERIUM_CONTRATISTA') . '?identification=' . $c;

		return json_encode(array('url' => $url));
	}

	public static function datosContratistasV() {
		$cliente = Request::input('cliente');
		$cSearch = Request::input('cSearchVal');
		$tipo_busqueda = !empty($cSearch) ? 'RECURSOS' : 'SOLOCLIENTE';
		$cSearchFT = null;
		if (!empty($cSearch)) {
			$trimmed = trim($cSearch);
			$cSearchFT = (str_starts_with($trimmed, '"') && str_ends_with($trimmed, '"'))
				? $trimmed
				: '"' . $trimmed . '"';
		}
		//
		try {
			$resultado = SQLConnection::backendStoreProcedure(
				'led_busqueda_general',
				array($tipo_busqueda, $cliente, $cSearchFT),
				'select'
			);
			\Log::info('RESULTADO', ['data' => $resultado]);
			return response()->json($resultado);
		} catch (\Exception $e) {
			\Log::error('ERROR BUSQUEDA', ['msg' => $e->getMessage()]);
			return response()->json(['error' => $e->getMessage()], 500);
		}
	}
}
