<?php namespace App\Http\Controllers;

use Session;
use Request; 
use App\Custom\SQLConnection;
use App\Custom\Misc;

use Exception;

class ScreeningController extends Controller {

	
	public function screeningTxtCliente(){
	    if ( ! Misc::restriccionPermiso('PROCESOS') ){ 
	    	return redirect('/menu'); 
	    }
	    $menu = Misc::obtenerPermisosNavigatorNoCuit();
		return view('screening/formulario_carga_txt_cliente')->with(compact('menu'));
	}

	public function screeningSubirTxtCliente(){
		$cliente = Request::Input('cliente');
		$afip    = Request::Input('afip') ?? 1;
	 	$user_id 		= Session::get("usuario")->user_id;
		$user_name = Session::get('usuario')->username;
		$archivo = $_FILES['archivo']['name'];
		$url_temporal = $_FILES['archivo']['tmp_name'];
		$destino = "/var/www/html/compartido/screening/" . $cliente . "/";
		if(!is_dir($destino)){
			mkdir($destino, 0777,true);
		}

		$cuits = [];
		if(move_uploaded_file($url_temporal, $destino.$archivo)) {
			chmod($destino, 0777);
			$file = fopen($destino.$archivo, 'r');
			while (!feof($file)){
				$linea = fgets($file);
				/* Solo deja los numeros */
				$numero = ''; 
				$numero = preg_replace("/[^0-9]/", "", $$linea);
				dd ($numero); 
				if ($numero !== '')
				{
					$cuit[] = (strlen($v) > 0) ? $v : '';
				}
			}
			
			$cant = 0; 
			foreach($cuit as $key => $v) {
				$cant += 1; 
				try {
					SqlConnection::backendStoreProcedure('screening_insertar', array($cliente,$cuit[$key],null,$afip));
				} catch (Exception $e) {
					$mensaje = $e->getMessage();
					return view("/screening/mensaje")->with(compact(['mensaje']));
				}
			}

			if ($cant == 0)
			{
				$mensaje = 'No se ha cargado ningún regiestro';
			}
			else
			{
				$mensaje = 'Archivo cargado correctamente. Total de registros a procesar: ' . $cant;
			}
			return view("/screening/mensaje")->with(compact(['mensaje']));
		}
		else 
		{
			$mensaje = "Se produjo un error al subir el archivo.";
			return view("/screening/mensaje")->with(compact(['mensaje']));
		}
 }



}
