<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Permisos;
use App\Models\Mediosdepago;
use App\Models\Mediodepagoreserva;
use App\Models\Reserva;
use App\Models\Ingeg;
use App\Models\Tiporeserva;
use App\Models\Nota;
use App\Models\Sala;
use App\Models\Empleado;
use App\Models\Config_email;
use App\Models\Reservahistorial;
use App\Models\Historicomedios;
use App\Http\Controllers\SalasdisponiblesController;
use App\PHPMailer\PHPMailer;
use DB;
class AgendaController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    private $host;
    private $username;
    private $password;
    private $config_email;
    public $franquicia="";
    public function __construct()
    {
        $this->middleware('auth');
        date_default_timezone_set('America/Argentina/Buenos_Aires');
        $sqlnombre=\DB::select("Select name as nombre from users where id=22");
        $franquicia = $sqlnombre[0]->nombre;
        $cadena = $franquicia;
        $patron = '/escape room/i';
        $sustitucion = "";
        $nombre=preg_replace($patron, $sustitucion, $cadena);
        $this->franquicia=trim($nombre);
        $this->host       = 'mail.escaperoomargentina.com';                     //Set the SMTP 
        $this->username   = 'reservas@escaperoomargentina.com';                     //SMTP username
        $this->password   = 'c9sFWKDLR9ay'; 
        $emails =Config_email::where('id',1)->get();
        $this->config_email=array('confirmacion'=>explode(',',$emails[0]['confirmacion']),'intento_reserva'=>explode(',',$emails[0]['intento_reserva']),'error_google_agenda'=>explode(',',$emails[0]['error_google_agenda']),'cambio_cantidad'=>explode(',',$emails[0]['cambio_cantidad']),'backup'=>explode(',',$emails[0]['backup']));
         //$this->emailcc($this->config_email,"prueba","Cambio en cantidad","cambio_cantidad",$nombrearchivo="");
         
    }
    public function emailcc($arrayto,$titulo,$mensaje,$tipo="confirmacion",$archivo="")
    {
        $subject = 'Nuevo mensaje del sistema';
        $url_sistema = url('/mensajes');
                // Message
        $message = "<html>
                    <head>
                      <title>$titulo</title>
                    </head>
                    <body>
                        $mensaje
                    </body>
                    </html>";
            // To send HTML mail, the Content-type header must be set
        //$headers[] = 'Cc: birthdayarchive@example.com';
        //$headers[] = 'Bcc: birthdaycheck@example.com';
        $mail = new PHPMailer(true);
        try {
        //Server settings
            $mail->SMTPDebug = false;//SMTP::DEBUG_SERVER;                      //Enable verbose debug output
            $mail->CharSet = 'UTF-8';
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $this->host;                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $this->username;                    //SMTP username
            $mail->Password   =$this->password;                               //SMTP password
            $mail->SMTPSecure ='ssl';// Mail::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
            $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
            //Recipients
         $franquicia_nombre="Sistema";
            $franquicia_email="reservas@escaperoomargentina.com";
            $mail->setFrom($franquicia_email, $franquicia_nombre);
            $to = $arrayto[$tipo][0];
            $mail->addAddress($to);     //Add a recipient
            // $mail->addAddress('ellen@example.com');               //Name is optional
            // $mail->addReplyTo('info@example.com', 'Information');
            if(count($arrayto[$tipo])>1){
                for($i=1;$i<count($arrayto[$tipo]);$i++){
                    $mail->addCC(trim($arrayto[$tipo][$i]));
                }
            }
            // $mail->addCC(\Auth::user()->email);
            //  $mail->addBCC('bcc@example.com');
            //Attachments
            if($archivo)
            {
            $mail->addAttachment($archivo); 
            }
            //   $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
            //  $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name
            //Content
             /*  if($archivo)
            {
                $mail->addAttachment($archivo); 
            }*/
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $titulo;
            $mail->Body    =  $message;
            $mail->AltBody = $titulo;
            $mail->send();
                            return true;
            } catch (Exception $e) {
                return false;
            }
    }
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function mostrar(Request $request)
    {   
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $fecha = $request->get('fecha')? $request->get('fecha'):date('Y-m-d');
        $desde = (int)$request->get('desde');
        $fecha_formateada =  date('d-m-Y',strtotime($fecha));
        $array_dias = array('Dom','Lun','Mar','Mie','Jue','Vie','Sab');
        $nombre_dia = $array_dias[date('w',strtotime($fecha))];
        $dia = date('d',strtotime($fecha));
        $consulta =  \DB::select("SELECT s.id,s.id_turno, s.sala,s.ncorto,s.ncorto AS titulo,s.nombre, s.hora_inicio, hour(s.hora_inicio) as hora,minute(s.hora_inicio) AS minutos,s.cantidad,s.tipo_reserva,s.trasnoche,s.ticket,s.cpago FROM reservas as s WHERE s.fecha='$fecha' and s.trasnoche=0 and s.id_turno IS NOT NULL");
      $consultatrasnoche =  \DB::select("SELECT s.id,s.id_turno, s.sala,s.ncorto,s.ncorto AS titulo,s.nombre, s.hora_inicio, hour(s.hora_inicio) as hora,minute(s.hora_inicio) AS minutos,s.cantidad,s.tipo_reserva,s.trasnoche,s.ticket,s.cpago FROM reservas as s WHERE s.fecha='$fecha' and s.trasnoche=1 and s.id_turno IS NOT NULL");
        $consulta_turnoaux =  \DB::select("SELECT s.id,s.id_turno, s.sala,s.ncorto,s.ncorto AS titulo,s.nombre, s.hora_inicio, hour(s.hora_inicio) as hora,minute(s.hora_inicio) AS minutos,s.cantidad,s.tipo_reserva,s.trasnoche,s.ticket,s.cpago FROM reservas as s WHERE s.fecha='$fecha' and s.id_turno IS NULL");
        $tiporeserva =  \DB::select("SELECT id,color,letra FROM tiporeserva");
        $css_reserva="";
        $datos=array();
        $datostrasnoche=array();
        $array_salas=array();
        $salas =  \DB::select("SELECT s.ncorto  FROM salas as s LEFT JOIN salausuarios as su ON s.id=su.id_sala WHERE su.id_usuario='22' ORDER BY s.orden ASC");
        $n=0;
        foreach($salas as $sala){
            $array_salas[$sala->ncorto]=$n;
            $n++;
        }
        $salasdisponibles = new SalasdisponiblesController();
       $turnos = $salasdisponibles->mostrardisponibilidad('22',$fecha,0);
foreach ($turnos as $key => $value) {
   $array_turnos_sala =json_decode($value['turnos'],true);
   $entro=0;
   foreach ($array_turnos_sala as $turno => $valor) {
       $arrayhoramin = explode(':',$valor['hora_inicio'],2);
       $hora =$arrayhoramin[0];
       $minuto =$arrayhoramin[1];
       $datos[$hora][$value['sala']->ncorto][]=array('id'=>0,'id_turno'=>0,'sala'=>$value['sala']->ncorto,'titulo'=>"",'tipo_reserva'=>"",'cantidad'=>"",'nombre'=>"",'ticket'=>"",'minutos'=>$minuto,'cpago'=>"",'hora'=>$hora,'trasnoche'=>$valor['trasnoche']);
   }
}

        foreach($consulta as $dato){
            $datos[$dato->hora][$dato->ncorto][]=array('id'=>$dato->id,'id_turno'=>$dato->id_turno,'sala'=>$dato->sala,'titulo'=>$dato->titulo,'tipo_reserva'=>$dato->tipo_reserva,'cantidad'=>$dato->cantidad,'nombre'=>$dato->nombre,'ticket'=>$dato->ticket,'minutos'=>$dato->minutos,'cpago'=>$dato->cpago,'hora'=>$dato->hora);
        }
        foreach($consultatrasnoche as $dato){
            $datostrasnoche[$dato->hora][$dato->ncorto][]=array('id'=>$dato->id,'id_turno'=>$dato->id_turno,'sala'=>$dato->sala,'titulo'=>$dato->titulo,'tipo_reserva'=>$dato->tipo_reserva,'cantidad'=>$dato->cantidad,'nombre'=>$dato->nombre,'ticket'=>$dato->ticket,'minutos'=>$dato->minutos,'cpago'=>$dato->cpago,'hora'=>$dato->hora);
        }
         foreach($consulta_turnoaux as $dato){
            $datos[$dato->hora][$dato->ncorto][]=array('id'=>$dato->id,'id_turno'=>0,'sala'=>$dato->sala,'titulo'=>$dato->titulo,'tipo_reserva'=>$dato->tipo_reserva,'cantidad'=>$dato->cantidad,'nombre'=>$dato->nombre,'ticket'=>$dato->ticket,'minutos'=>$dato->minutos,'cpago'=>$dato->cpago,'hora'=>$dato->hora);
        }
$notas = nota::where('fecha',$fecha)->get();
$notaaimprimir="<small>";
foreach ($notas as $nota => $value) {
$notaaimprimir.=$value->nota."<br>";
    // code...
}
$notaaimprimir.="</small>";
$nombrefranquicia=$this->franquicia;
$salas =Sala::orderBy('orden','ASC')->get();
$tiporeserva=Tiporeserva::all();
$gamemaster = Empleado::all();
 $colores =  \DB::select("SELECT id,titulo,color,letra FROM tiporeserva ORDER BY id asc");
        return view('agenda.index', compact('permisos','fecha_formateada','fecha','dia','nombre_dia','datos','datostrasnoche','array_salas','turnos','notaaimprimir','salas','notas','desde','nombrefranquicia','tiporeserva','gamemaster','colores'));
    }
    public function datosaux($arraydatos)
    {
         for ($i=8; $i <= 23 ; $i++) { 
    // code...
            if($i<10){
                $hora = "0".$i;
            }else{
                $hora=$i;
            }
              if(isset($datos[$i])){
              }
        }
    }
    public function veragenda($id,$fechaagenda,$desde="")
    {
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $datos =  \DB::select("SELECT r.*, n.nombre as nivelsuspenso,i.nombre as idioma,tp.color,tp.letra FROM reservas as r LEFT JOIN nivelsuspensos AS n ON r.id_nivel_suspenso=n.id LEFT JOIN tiporeserva as tp ON r.tipo_reserva=tp.id LEFT OUTER JOIN idiomas as i ON r.id_idioma=i.id  WHERE r.id='$id'");
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'home','index');
        $mediosdepago=Mediosdepago::where('estado',1)->orderBy('orden','asc')->get();
        $mediosdepagoreservas=Mediodepagoreserva::where('id_reserva',$id)->get();
        $array_medios=array();
        foreach($mediosdepagoreservas as $mediosdepagoreserva){

            $array_medios[$mediosdepagoreserva->id_medio_pago][$mediosdepagoreserva->id_categoria_medio]=array('valor'=>$mediosdepagoreserva->valor,'factura'=>$mediosdepagoreserva->factura,'fecha'=>$mediosdepagoreserva->fecha,'ticket'=>$mediosdepagoreserva->ticket);
        }
        
        $empleados =Empleado::all();
        
        $idsala= \DB::select("SELECT su.id FROM salas as s,salausuarios as su where s.nombre like '".$datos['0']->sala."' and s.id=su.id_sala ");
       
        $salaid= isset($idsala[0]->id)? $idsala[0]->id:0;
        // Select id from salausuarios where id_sala=$salaid;
        $colores =  \DB::select("SELECT id,titulo,color,letra FROM tiporeserva ORDER BY id asc");
        $gamemaster = Empleado::all();
        return view('agenda.show', compact('permisos','datos','mediosdepago','mediosdepagoreservas','fechaagenda','array_medios','colores','empleados','desde','salaid','gamemaster'));
    }
    public function verinforme(Request $request,$fecha_inicio="",$fecha_fin="")
    {
        $fecha_inicio=$request->get('fecha_inicio');
        $fecha_fin=$request->get('fecha_fin');
        if($fecha_inicio=="" and $fecha_fin==""){
            $fecha_inicio=date('Y-m-d')."T00:00";
            $fecha_fin=date('Y-m-d')."T23:59";
        }
        $vfecha_inicio=$fecha_inicio;
        $vfecha_fin=$fecha_fin;
       // echo $fecha_fin;
        $tfecha_fin =explode("T", $fecha_fin);
       // var_dump($fecha_inicio);
        $fecha_fin =$tfecha_fin[0];
        $hora_fin = $tfecha_fin[1];
        $tfecha_inicio =explode("T", $fecha_inicio);
        $fecha_inicio =$tfecha_inicio[0];
        $hora_inicio= $tfecha_inicio[1];
 
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $sql ="SELECT * from reservas WHERE fecha<='$fecha_fin' AND fecha>='$fecha_inicio' AND hora_inicio>='$hora_inicio' AND hora_inicio<='$hora_fin' AND tipo_reserva!=44 ORDER BY ticket asc, trasnoche ASC, fecha, hora_inicio ASC";
        //echo $sql;
        $datos =  \DB::select($sql);
        $nombresitio = \DB::select("SELECT name from users where id=22");
        $nombrefranquicia = $nombresitio[0]->name;
        $nombrefranquicia= preg_replace('/ /','-', $nombrefranquicia);
        $array_medios=array();
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'home','index');
        $mediosdepago=Mediosdepago::orderBy('orden', 'ASC')->get();
        $fecha_inicio_aux=$fecha_inicio.' 00:00:00';
        $fecha_fin_aux=$fecha_fin.' 23:59:59';
        $gastos = Ingeg::where('tipo','=',2)->where('id_categoria','!=',3)->where('fecha','>=',$fecha_inicio_aux)->where('fecha','<=',$fecha_fin_aux)->get();
        $ingresos = Ingeg::where('tipo','=',1)->where('id_categoria','!=',3)->where('fecha','>=',$fecha_inicio_aux)->where('fecha','<=',$fecha_fin_aux)->get();
        $retiros = Ingeg::where('id_categoria','=',3)->where('fecha','>=',$fecha_inicio_aux)->where('fecha','<=',$fecha_fin_aux)->get();
        $senias = Mediodepagoreserva::where('id_medio_pago','=',3)->where('fecha','>=',$fecha_inicio)->where('fecha','<=',$fecha_fin)->orwhere('id_medio_pago','=',5)->where('fecha','>=',$fecha_inicio)->where('fecha','<=',$fecha_fin)->orderBy('ticket','asc')->get();;

        $colores =  \DB::select("SELECT id,color,letra FROM tiporeserva ORDER BY id asc");
        // $colores =  \DB::select("SELECT cpago as color FROM reservas GROUP BY cpago");
        return view('agenda.informe', compact('permisos','mediosdepago','datos','vfecha_inicio','vfecha_fin','fecha_inicio','fecha_fin','gastos','senias','ingresos','retiros','nombrefranquicia','colores'));
    }
        public function cajadiaria(Request $request,$fecha_inicio="",$fecha_fin="")
    {
        $fecha_inicio=$request->get('fecha_inicio');
        $fecha_fin=$request->get('fecha_fin');
        if($fecha_inicio=="" and $fecha_fin==""){
            $fecha_inicio=date('Y-m-d')."T00:00";
            $fecha_fin=date('Y-m-d')."T23:59";
        }
        $vfecha_inicio=$fecha_inicio;
        $vfecha_fin=$fecha_fin;
       // echo $fecha_fin;
        $tfecha_fin =explode("T", $fecha_fin);
       // var_dump($fecha_inicio);
        $fecha_fin =$tfecha_fin[0];
        $hora_fin = $tfecha_fin[1];
        $tfecha_inicio =explode("T", $fecha_inicio);
        $fecha_inicio =$tfecha_inicio[0];
        $hora_inicio= $tfecha_inicio[1];
 
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $sql ="SELECT * from reservas WHERE fecha<='$fecha_fin' AND fecha>='$fecha_inicio' AND hora_inicio>='$hora_inicio' AND hora_inicio<='$hora_fin' AND tipo_reserva!=44 ORDER BY ticket asc,trasnoche ASC, fecha asc, hora_inicio ASC";
        //echo $sql;
        $datos =  \DB::select($sql);
        $nombresitio = \DB::select("SELECT name from users where id=22");
        $nombrefranquicia = $nombresitio[0]->name;
        $nombrefranquicia= preg_replace('/ /','-', $nombrefranquicia);
        $array_medios=array();
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'home','index');
        $mediosdepago=Mediosdepago::orderBy('orden', 'ASC')->get();
        $fecha_inicio_aux=$fecha_inicio.' 00:00:00';
        $fecha_fin_aux=$fecha_fin.' 23:59:59';
        $gastos = Ingeg::where('tipo','=',2)->where('id_categoria','!=',3)->where('fecha','>=',$fecha_inicio_aux)->where('fecha','<=',$fecha_fin_aux)->get();
        $ingresos = Ingeg::where('tipo','=',1)->where('id_categoria','!=',3)->where('fecha','>=',$fecha_inicio_aux)->where('fecha','<=',$fecha_fin_aux)->get();
        $retiros = Ingeg::where('id_categoria','=',3)->where('fecha','>=',$fecha_inicio_aux)->where('fecha','<=',$fecha_fin_aux)->get();
        $senias = Mediodepagoreserva::where('id_medio_pago','=',3)->where('fecha','>=',$fecha_inicio)->where('fecha','<=',$fecha_fin)->orwhere('id_medio_pago','=',5)->where('fecha','>=',$fecha_inicio)->where('fecha','<=',$fecha_fin)->orderBy('ticket','asc')->get();

        $colores =  \DB::select("SELECT id,color,letra FROM tiporeserva ORDER BY id asc");
        // $colores =  \DB::select("SELECT cpago as color FROM reservas GROUP BY cpago");
        return view('agenda.cajadiaria', compact('permisos','mediosdepago','datos','vfecha_inicio','vfecha_fin','fecha_inicio','fecha_fin','gastos','senias','ingresos','retiros','nombrefranquicia','colores'));
    }
    public function verinforme11(Request $request,$fecha_inicio="",$fecha_fin="")
    {
        $fecha_inicio=$request->get('fecha_inicio');
        $fecha_fin=$request->get('fecha_fin');
        if($fecha_inicio=="" and $fecha_fin==""){
            $fecha_inicio=date('Y-m-d');
            $fecha_fin=date('Y-m-d');
        }
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'informe11','index');
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'home','index');       
        return view('agenda.informe11', compact('permisos','fecha_inicio','fecha_fin'));
    }
    public function verinforme12(Request $request,$fecha_inicio="",$fecha_fin="")
    {
        $fecha_inicio=$request->get('fecha_inicio');
        $fecha_fin=$request->get('fecha_fin');
        if($fecha_inicio=="" and $fecha_fin==""){
            $fecha_inicio=date('Y-m-d');
            $fecha_fin=date('Y-m-d');
        }
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'home','index');       
        return view('agenda.informe12', compact('permisos','fecha_inicio','fecha_fin'));
    }
        public function verinforme13(Request $request,$fecha_inicio="",$fecha_fin="")
    {
        $fecha_inicio=$request->get('fecha_inicio');
        $fecha_fin=$request->get('fecha_fin');
        if($fecha_inicio=="" and $fecha_fin==""){
            $fecha_inicio=date('Y-m-d');
            $fecha_fin=date('Y-m-d');
        }
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'home','index');       
        return view('agenda.informe13', compact('permisos','fecha_inicio','fecha_fin'));
    }
    public function verinforme2(Request $request,$mes_anio="")
    {
        $mes_anio=$request->get('mes_anio');
        if($mes_anio==""){
            $mes=date('m');
            $anio=date('Y');
            $mes_anio=$anio."-".$mes;
        }else{
            $array_mesanio = explode('-',$mes_anio);
            $mes=(isset($array_mesanio[1]))?$array_mesanio[1]:date('m');
            $anio=(isset($array_mesanio[0]))?$array_mesanio[0]:date('Y');
        }
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $datos =  \DB::select("SELECT fecha,COUNT(sala) as sumsalas,SUM(cantidad) as cantidadjugadores, SUM(precio) as cantidadprecio FROM `reservas` WHERE YEAR(fecha)='$anio' AND MONTH(fecha)='$mes' AND tipo_reserva!=44 GROUP BY fecha ORDER BY fecha ASC;");
        $array_medios=array();
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'home','index');
        $mediosdepago=Mediosdepago::orderBy('id', 'ASC')->get();
        return view('agenda.informe2', compact('permisos','mediosdepago','datos','mes_anio','mes','anio'));
    }
    
    public function actualizarreserva(Request $request)
    {
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $id_reserva =  $request->get('id_reserva');
        $reserva= Reserva::find($id_reserva);
        $reservahistorialexiste= Reservahistorial::where('id_reserva',$id_reserva)->get();
        if(!isset($reservahistorialexiste[0]) and $reserva->id){
            $reservahistorial = new Reservahistorial;
            $reservahistorial->id_reserva = $reserva->id;
            $reservahistorial->sala = $reserva->sala;
            $reservahistorial->id_usuario=$reserva->id_usuario;
            $reservahistorial->aux_telefono=$reserva->aux_telefono;
            $reservahistorial->id_nivel_suspenso=$reserva->id_nivel_suspenso;
            $reservahistorial->id_idioma=$reserva->id_idioma;
            $reservahistorial->nombre=$reserva->nombre;
            $reservahistorial->fecha=$reserva->fecha;
            $reservahistorial->hora_inicio=$reserva->hora_inicio;
            $reservahistorial->telefono=$reserva->telefono;
            $reservahistorial->cantidad=$reserva->cantidad;
            $reservahistorial->precio=$reserva->precio;
            $reservahistorial->cantidad_aux = $reserva->cantidad_aux;
            $reservahistorial->precio_aux  =  $reserva->precio_aux;
            $reservahistorial->ip=$reserva->ip;
            $reservahistorial->confirmada=$reserva->confirmada;
            $reservahistorial->bloqueada=$reserva->bloqueada;
            $reservahistorial->tipo_reserva=$reserva->tipo_reserva;
            $reservahistorial->observaciones=$reserva->observaciones; 
            $reservahistorial->ticket=$reserva->ticket; 
            $reservahistorial->cpago = $reserva->cpago;
            $reservahistorial->empleado = $reserva->empleado;
            $reservahistorial->sincobrar = $reserva->sincobrar;
            $reservahistorial->save();
            $medios =  $request->get('medios')?$request->get('medios'):[];
            foreach($medios as $medio){
            $historicomedio = Mediodepagoreserva::where('id_reserva',$reserva->id)->where('id_medio_pago',$medio['id'])->where('id_categoria_medio' ,$medio['id_categoria'])->get();
                            foreach ($historicomedio as $historico) {
                                $historicomediodepago=new Historicomedios;
                                $historicomediodepago->id_reserva=$reservahistorial->id;
                                $historicomediodepago->id_medio_pago=$historico->id_medio_pago;
                                $historicomediodepago->id_categoria_medio=$historico->id_categoria_medio;
                                $historicomediodepago->valor=$historico->valor;
                                $historicomediodepago->factura=$historico->factura;
                                $historicomediodepago->fecha=$historico->fecha;
                                $historicomediodepago->ticket=$historico->ticket;
                                $historicomediodepago->save();
                                // code...
                            }
            }
        }

$guardarhistorial=0;
        
        if(($reserva->sala_aux !=  $request->get('sala_aux')) or ($reserva->ticket  !=  $request->get('ticket')) or ($reserva->empleado  !=  $request->get('empleado')) or ($reserva->cantidad_aux  !=  $request->get('cantidad_aux')) or ( $reserva->precio_aux !=  $request->get('precio_aux')) or ($reserva->observaciones  !=  $request->get('observaciones')) or ( $reserva->cpago!=$request->get('cpago')) or ( $reserva->empleado!=$request->get('empleado'))){
            $guardarhistorial=1;

        }

        $cantidadactualizada =  $request->get('cantidadactualizada');
        $reserva->sala_aux  =  $request->get('sala_aux');
        $reserva->ticket  =  $request->get('ticket');
        $reserva->sincobrar= $request->get('sincobrar');
        if((int)$request->get('cantidad_aux')>0 or  $reserva->sala_aux !=$request->get('sala_aux') or strlen( $request->get('ticket') )>0 or (int)$request->get('precio_aux')>0 ){
            //$reserva->bloqueada=2;
        }

        if(strlen($request->get('empleado')>0)){
            $reserva->empleado  =  $request->get('empleado');
        }
        
        
        if($cantidadactualizada==0){
             $reserva->cantidad_aux  =  $request->get('cantidad_aux');
        }
        if( $reserva->cantidad_aux != $request->get('cantidad_aux')){
            $this->agregarlog($reserva,$request->get('cantidad_aux'));

        }
                if( $request->get('cpago')){
            $reserva->cpago=$request->get('cpago');
        }
        if( $request->get('empleado')){
            $reserva->empleado=$request->get('empleado');
        }
        
        $reserva->cantidad_aux = $request->get('cantidad_aux');
        $reserva->precio_aux  =  $request->get('precio_aux');
        $reserva->observaciones  =  $request->get('observaciones');
        if( $request->get('cpago')){
            $reserva->cpago=$request->get('cpago');
        }
            if( $request->get('empleado')){
            $reserva->empleado=$request->get('empleado');
        }

        if($reserva->save()){
            if($guardarhistorial==1){
                $reservahistorial1 = new Reservahistorial;
                $reservahistorial1->id_reserva = $reserva->id;
                $reservahistorial1->sala_aux  =  $request->get('sala_aux');
                $reservahistorial1->ticket  =  $request->get('ticket');
                $reservahistorial1->sala = $reserva->sala;
                $reservahistorial1->id_usuario=$reserva->id_usuario;
                $reservahistorial1->aux_telefono=$reserva->aux_telefono;
                $reservahistorial1->id_nivel_suspenso=$reserva->id_nivel_suspenso;
                $reservahistorial1->id_idioma=$reserva->id_idioma;
                $reservahistorial1->nombre=$reserva->nombre;
                $reservahistorial1->fecha=$reserva->fecha;
                $reservahistorial1->hora_inicio=$reserva->hora_inicio;
                $reservahistorial1->telefono=$reserva->telefono;
                $reservahistorial1->cantidad=$reserva->cantidad;
                $reservahistorial1->precio=$reserva->precio;
               // $reservahistorial1->cantidad_aux = $reserva->cantidad_aux;
               // $reservahistorial1->precio_aux  =  $reserva->precio_aux;
                $reservahistorial1->ip=$reserva->ip;
                $reservahistorial1->confirmada=$reserva->confirmada;
                $reservahistorial1->bloqueada=$reserva->bloqueada;
                $reservahistorial1->tipo_reserva=$reserva->tipo_reserva;
                $reservahistorial1->sincobrar = $reserva->sincobrar;
               // $reservahistorial1->observaciones=$reserva->observaciones; 
               // $reservahistorial1->ticket=$reserva->ticket; 
               // $reservahistorial1->cpago = $cpago;
               // $reservahistorial1->empleado = $empleado;
                  $reservahistorial1->cantidad_aux = $request->get('cantidad_aux');
        $reservahistorial1->precio_aux  =  $request->get('precio_aux');
        $reservahistorial1->observaciones  =  $request->get('observaciones');
        if( $request->get('cpago')){
            $reservahistorial1->cpago=$request->get('cpago');
        }
            if( $request->get('empleado')){
            $reservahistorial1->empleado=$request->get('empleado');
        }
                if(strlen($request->get('empleado')>0)){
            $reservahistorial1->empleado  =  $request->get('empleado');
        }
        if($cantidadactualizada==0){
             $reservahistorial1->cantidad_aux  =  $request->get('cantidad_aux');
        }
        $reservahistorial1->save();
        $medios =  $request->get('medios');
        if(is_array($medios)){
                foreach($medios as $medio){
                      $historicomedio = Mediodepagoreserva::where('id_reserva',$reserva->id)->where('id_medio_pago',$medio['id'])->where('id_categoria_medio' ,$medio['id_categoria'])->get();
               foreach ($historicomedio as $historico) {
                                $historicomediodepago=new Historicomedios;
                                $historicomediodepago->id_reserva=$reservahistorial1->id;
                                $historicomediodepago->id_medio_pago=$historico->id_medio_pago;
                                $historicomediodepago->id_categoria_medio=$historico->id_categoria_medio;
                                $historicomediodepago->valor=$historico->valor;
                                $historicomediodepago->factura=$historico->factura;
                                $historicomediodepago->fecha=$historico->fecha;
                                $historicomediodepago->ticket=$historico->ticket;
                                $historicomediodepago->save();
                                // code...
                            }
                }
        }
              
            }
            return 1;
        }else{
            return 0;
        }
    }
    public function guardarmedios(Request $request)
    {
        $permisos = Permisos::secciones(\Auth::user()->id_tipo,'agenda','index');
        $id_reserva =  $request->get('id_reserva');
        $medios =  $request->get('medios');
        
        $mediosjs= $medios;
        $reserva= Reserva::find($id_reserva);
        if($reserva->id){
            $reservahistorial = new Reservahistorial;
            $reservahistorial->id_reserva = $reserva->id;
            $reservahistorial->sala = $reserva->sala;
            $reservahistorial->id_usuario=$reserva->id_usuario;
            $reservahistorial->aux_telefono=$reserva->aux_telefono;
            $reservahistorial->id_nivel_suspenso=$reserva->id_nivel_suspenso;
            $reservahistorial->id_idioma=$reserva->id_idioma;
            $reservahistorial->nombre=$reserva->nombre;
            $reservahistorial->fecha=$reserva->fecha;
            $reservahistorial->hora_inicio=$reserva->hora_inicio;
            $reservahistorial->telefono=$reserva->telefono;
            $reservahistorial->cantidad=$reserva->cantidad;
            $reservahistorial->precio=$reserva->precio;
            $reservahistorial->cantidad_aux = $reserva->cantidad_aux;
            $reservahistorial->precio_aux  =  $reserva->precio_aux;
            $reservahistorial->ip=$reserva->ip;
            $reservahistorial->confirmada=$reserva->confirmada;
            $reservahistorial->bloqueada=$reserva->bloqueada;
            $reservahistorial->tipo_reserva=$reserva->tipo_reserva;
            $reservahistorial->observaciones=$reserva->observaciones; 
            $reservahistorial->ticket=$reserva->ticket; 
            $reservahistorial->cpago = $reserva->cpago;
            $reservahistorial->empleado = $reserva->empleado;
            $reservahistorial->sincobrar = $reserva->sincobrar;
            $reservahistorial->save();
            DB::beginTransaction();
            
            if(count($medios)>0){
                
                foreach($medios as $medio){
                    if($medio['factura']=="true"){
                        $factura=1;
                    }else{
                        $factura=0;
                    }
                   try {
                            //buscar los medios de reserva 
                            
                            
                                          $mediosdepagoreserva = Mediodepagoreserva::where('id_reserva', $id_reserva)
    ->where('id_medio_pago', $medio['id'])
    ->where('id_categoria_medio', $medio['id_categoria'])
    ->lockForUpdate()
    ->first();
$fecha = $medio['fecha'] ?? date('Y-m-d');
if ($mediosdepagoreserva) {
    // Actualizar si ya existe
    $mediosdepagoreserva->fill([
        'valor' => $medio['valor'],
        'factura' => $factura,
        'fecha' => $fecha,
        'ticket' => $medio['ticket'],
    ])->save();
} else {
    // Crear uno nuevo
    Mediodepagoreserva::create([
        'id_reserva' => $id_reserva,
        'id_medio_pago' => $medio['id'],
        'id_categoria_medio' => $medio['id_categoria'],
        'valor' => $medio['valor'],
        'factura' => $factura,
        'fecha' => $fecha,
        'ticket' => $medio['ticket'],
    ]);
}

/*
if ($mediosdepagoreserva) {
    // Si ya existe, actualizar
    $mediosdepagoreserva->valor = $medio['valor'];
    $mediosdepagoreserva->factura = $factura;
    $mediosdepagoreserva->fecha = ($medio['fecha'])?$medio['fecha']:date('Y-m-d');
    $mediosdepagoreserva->ticket = $medio['ticket'];
    $mediosdepagoreserva->save();
} else {
    // Si no existe, crear uno nuevo
    $mediosdepagoreserva = new Mediodepagoreserva();
    $mediosdepagoreserva->id_reserva = $id_reserva;
    $mediosdepagoreserva->id_medio_pago = $medio['id'];
    $mediosdepagoreserva->id_categoria_medio = $medio['id_categoria'];
    $mediosdepagoreserva->valor =$medio['valor'];
    $mediosdepagoreserva->factura = $factura;
    $mediosdepagoreserva->fecha =($medio['fecha'])?$medio['fecha']:date('Y-m-d');
    $mediosdepagoreserva->ticket = $medio['ticket'];
    $mediosdepagoreserva->save();
    
}*/
$historicomedio = Mediodepagoreserva::where('id_reserva',$reserva->id)->where('id_medio_pago',$medio['id'])->where('id_categoria_medio' ,$medio['id_categoria'])->get();
    foreach ($historicomedio as $historico) {
                                $historicomediodepago=new Historicomedios;
                                $historicomediodepago->id_reserva=$reservahistorial->id;
                                $historicomediodepago->id_medio_pago=$historico->id_medio_pago;
                                $historicomediodepago->id_categoria_medio=$historico->id_categoria_medio;
                                $historicomediodepago->valor=$historico->valor;
                                $historicomediodepago->factura=$historico->factura;
                                $historicomediodepago->fecha=$historico->fecha;
                                $historicomediodepago->ticket=$historico->ticket;
                                $historicomediodepago->save();
                                // code...
                            }
                   
                        
                        
                          /*  if((int)$medio['valor']>0){
                               $reserva->bloqueada=2;
                                $reserva->save();
                            }*/
                       // }    
                    } catch (\Throwable $th) {
                        return "error";
                    }
                }
                DB::commit();
                $medios =  $request->get('medios');
                foreach($medios as $medio){
                      $historicomedio = Mediodepagoreserva::where('id_reserva',$reserva->id)->where('id_medio_pago',$medio['id'])->where('id_categoria_medio' ,$medio['id_categoria'])->get();
               foreach ($historicomedio as $historico) {
                                $historicomediodepago=new Historicomedios;
                                $historicomediodepago->id_reserva=$reservahistorial->id;
                                $historicomediodepago->id_medio_pago=$historico->id_medio_pago;
                                $historicomediodepago->id_categoria_medio=$historico->id_categoria_medio;
                                $historicomediodepago->valor=$historico->valor;
                                $historicomediodepago->factura=$historico->factura;
                                $historicomediodepago->fecha=$historico->fecha;
                                $historicomediodepago->ticket=$historico->ticket;
                                $historicomediodepago->save();
                                // code...
                            }
                }
                return 1;
            }else{
                return 0;
            }
            
        }else{
            return 0;
           // return 0;
        }
    }
    public function cerrarcupon(Request $request)
    {
        // code...
        $error=array();
        if($this->actualizarreserva($request)){
            $error[]="se actualizo la reserva";
        }else{
            $error[]="no se actualizo la reserva";
        }
        if($this->guardarmedios($request)){
            $error[]="se guardaron los medios de pago".$this->guardarmedios($request);
        }else{
            $error[]="no se guardaron los medios de pago".$this->guardarmedios($request);
        }
        $id_reserva =  $request->get('id_reserva');
        $reserva= Reserva::find($id_reserva);
         $medios =  $request->get('medios');
        if($reserva->id){
            $reserva->cpago=$request->get('cpago');
            $reserva->confirmada=2;
            $reserva->tipo_reserva=10; //abonada
            $reserva->save();
            $error[]="se actualizo la reserva";
            $reservahistorial = new Reservahistorial;
            $reservahistorial->id_reserva = $reserva->id;
            $reservahistorial->sala = $reserva->sala;
            $reservahistorial->id_usuario=$reserva->id_usuario;
            $reservahistorial->aux_telefono=$reserva->aux_telefono;
            $reservahistorial->id_nivel_suspenso=$reserva->id_nivel_suspenso;
            $reservahistorial->id_idioma=$reserva->id_idioma;
            $reservahistorial->nombre=$reserva->nombre;
            $reservahistorial->fecha=$reserva->fecha;
            $reservahistorial->hora_inicio=$reserva->hora_inicio;
            $reservahistorial->telefono=$reserva->telefono;
            $reservahistorial->cantidad=$reserva->cantidad;
            $reservahistorial->precio=$reserva->precio;
            $reservahistorial->cantidad_aux = $reserva->cantidad_aux;
            $reservahistorial->precio_aux  =  $reserva->precio_aux;
            $reservahistorial->ip=$reserva->ip;
            $reservahistorial->confirmada=2;
            $reservahistorial->bloqueada=$reserva->bloqueada;
            $reservahistorial->tipo_reserva=10;
            $reservahistorial->observaciones=$reserva->observaciones; 
            $reservahistorial->ticket=$reserva->ticket; 
            $reservahistorial->cpago = $reserva->cpago;
            $reservahistorial->empleado = $reserva->empleado;
            $reservahistorial->sincobrar = $reserva->sincobrar;
            $reservahistorial->save();
            foreach($medios as $medio){
            $historicomedio = Mediodepagoreserva::where('id_reserva',$reserva->id)->where('id_medio_pago',$medio['id'])->where('id_categoria_medio' ,$medio['id_categoria'])->get();
                            foreach ($historicomedio as $historico) {
                                $historicomediodepago=new Historicomedios;
                                $historicomediodepago->id_reserva=$reservahistorial->id;
                                $historicomediodepago->id_medio_pago=$historico->id_medio_pago;
                                $historicomediodepago->id_categoria_medio=$historico->id_categoria_medio;
                                $historicomediodepago->valor=$historico->valor;
                                $historicomediodepago->factura=$historico->factura;
                                $historicomediodepago->fecha=$historico->fecha;
                                $historicomediodepago->ticket=$historico->ticket;
                                $historicomediodepago->save();
                                // code...
                            }
            }
            return $error;
        }else{
            $error[]="no se actualizo la reserva";
            return $error;
        }

    }
    public function agregarnota(Request $request)
    {
        $fecha =  $request->get('fecha');
        $fechaaguardar =$fecha;//." ".date('H:i:s');
        $nota =  $request->get('nota');
        $otas=Nota::updateOrCreate(
                                                                    ['fecha' => $fecha],['nota' =>$nota]);
      /*  $notaaguardar = new Nota();
        $notaaguardar->nota =$nota;
        $notaaguardar->fecha =$fechaaguardar;
        $notaaguardar->save();*/
        return redirect('/agenda?fecha='.$fecha)->with('success', 'Nota guardada!');
    }
    public function agregarturno(Request $request)
    {
        $idssala = $request->get('id_sala');
        $fecha = $request->get('fecha');
        $cantidad = $request->get('pax');
        $precio = $request->get('precio');
        $nombre = $request->get('nombre');
        $telefono = $request->get('telefono');
        $email = $request->get('email');
        $hora_inicio = $request->get('hora_inicio');
        $cpago = $request->get('cpago');
        $tipo_reserva= ($request->get('tipo_reserva'))?(int)$request->get('tipo_reserva'):1;
        $hora_fin = $request->get('hora_fin');
        if(!$hora_fin){
            $hora_fin =$hora_inicio;
        }
        $cantidad_=0;
        foreach($idssala as $idsala){
            $sala = Sala::find($idsala);
            //agregar opcion de no repetir
            if(preg_match('/evento/i',$sala->nombre)){
                $existereserva = Reserva::where('fecha','=',$fecha)->where('hora_inicio','=',$hora_inicio)->where('sala','=',$sala->nombre)->get();
                foreach($existereserva as $existe){
                    return redirect('/agenda?fecha='.$fecha)->with('error', 'No se pudo guardar el evento!');
                }       
            }
            if(is_object($sala)){

                $fechaaguardar =$fecha." ".date('H:i:s');
                if($cantidad_==0){
                    $reserva= new Reserva();
                    $reserva->fecha=$fecha;
                    $reserva->hora_inicio=$hora_inicio;
                    $reserva->hora_fin=$hora_fin;
                    $reserva->sala=$sala->nombre;
                    $reserva->ncorto=$sala->ncorto;
                    $reserva->nombre=$nombre;
                    $reserva->cantidad=$cantidad;
                    $reserva->precio=$precio;
                    $reserva->telefono=$telefono;
                    $reserva->email=$email;
                    $reserva->id_usuario=22;
                    $reserva->cpago=$cpago;
                    $reserva->tipo_reserva=$tipo_reserva;
                }else{
                    $reserva= new Reserva();
                    $reserva->fecha=$fecha;
                    $reserva->hora_inicio=$hora_inicio;
                    $reserva->hora_fin=$hora_fin;
                    $reserva->sala=$sala->nombre;
                    $reserva->ncorto=$sala->ncorto;
                    $reserva->nombre=$nombre;
                    $reserva->cantidad=0;
                    $reserva->precio=0;
                    $reserva->telefono="";
                    $reserva->email="";
                    $reserva->id_usuario=22;
                    $reserva->cpago=$cpago;
                    $reserva->tipo_reserva=$tipo_reserva;
                }
                if($reserva->save()){
                    $guardar=1;
                    
                }else{
                    $guardar=0;
                    
                }
              
            }else{
                 
            }
            $cantidad_++;
        }
        if($guardar==1){
             return redirect('/agenda?fecha='.$fecha)->with('success', 'Registro guardado!');
         }else{
            return redirect('/agenda?fecha='.$fecha)->with('error', 'No se pudo guardar el registro!');
         }
    }
    public function agregarlog($reserva,$cantidadmodificada)
    {
        // code..
        //necesita dia/hora del momento del cambio,, + ticket + de la reserva sala, fecha y hora, gamemaster, valor anterior de la cantidad, valor nuevo de la cantidad.
        $nombrearchivo=getcwd().'/'."log444.txt";
        $email="ulises4@gmail.com";
        $fp= fopen($nombrearchivo, 'a+');
        $texto=date('d-m-Y')."\t".date('H:i:s')."\t".$reserva->ticket."\t".$reserva->sala."\t".date('d-m-Y',strtotime($reserva->fecha))."\t".$reserva->hora_inicio."\t".$reserva->empleado."\t".$reserva->empleado."\t".$reserva->cantidad_aux."\t".$cantidadmodificada."\n";
        fwrite($fp,$texto);
        fclose($fp);
        $titulo=$this->franquicia.", cambio cantidad.";
       // $this->email($email,$titulo,"Cambio en cantidad",$nombrearchivo);
       // emailcc($arrayto,$titulo,$mensaje,$tipo="confirmacion",$archivo)
$this->emailcc($this->config_email,$titulo,"Cambio en cantidad","cambio_cantidad",$nombrearchivo);
        
    }
    public function email($to,$titulo,$mensaje,$archivo,$copia=0)
    {
        $subject = 'Nuevo mensaje del sistema';
        $url_sistema = url('/mensajes');
                // Message
        $message = "<html>
                    <head>
                      <title>$titulo</title>
                    </head>
                    <body>
                        $mensaje
                    </body>
                    </html>";
            // To send HTML mail, the Content-type header must be set
        //$headers[] = 'Cc: birthdayarchive@example.com';
        //$headers[] = 'Bcc: birthdaycheck@example.com';
        $mail = new PHPMailer(true);
        try {
        //Server settings
            $mail->SMTPDebug = false;//SMTP::DEBUG_SERVER;                      //Enable verbose debug output
            $mail->CharSet = 'UTF-8';
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = 'mail.escaperoomargentina.com';                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = 'reservas@escaperoomargentina.com';                     //SMTP username
            $mail->Password   = 'c9sFWKDLR9ay';                               //SMTP password
            $mail->SMTPSecure ='ssl';// Mail::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
            $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`
            //Recipients
            $franquicia_nombre="Sistema";
            $franquicia_email="reservas@escaperoomargentina.com";
            $mail->setFrom($franquicia_email, $franquicia_nombre);
            $mail->addAddress($to);     //Add a recipient
            // $mail->addAddress('ellen@example.com');               //Name is optional
            // $mail->addReplyTo('info@example.com', 'Information');
            //    $mail->addCC("escaperoomargentinaadm@gmail.com");
               // $mail->addCC("cejaslauty@gmail.com");
            // $mail->addCC(\Auth::user()->email);
            //  $mail->addBCC('bcc@example.com');
            //Attachments
            if($archivo)
            {
                $mail->addAttachment($archivo); 
            }
            //   $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
            //  $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name
            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $titulo;
            $mail->Body    =  $message;
            $mail->AltBody = $titulo;
            $mail->send();
                            return true;
            } catch (Exception $e) {
                return false;
            } 

    }
}