public function uniqueEmail()
 {
     $email = Input::get('email');
     $buscar_email = UserNeighbors::where('email', '=', $email)->first();
     if ($buscar_email) {
         return Response::json(array("response" => 1));
     } else {
         return Response::json(array("response" => 0));
     }
 }
 public function confirm($code)
 {
     $confirm = InvitedNeighbors::where('Confirmation_code', '=', $code)->first();
     if (!$confirm->confirmed) {
         //$confirm->confirmed = true;
         //$confirm->update(['id']);
         $email = $confirm->email;
         $urbanism_id = $confirm->urbanism_id;
         $colony = Urbanism::where('id', '=', $urbanism_id)->pluck('colony_id');
         $expiration = Expiration::where('colony_id', '=', $colony)->first();
         $datetime2 = new DateTime($expiration->expiration);
         $datetime1 = new DateTime(date('Y-m-d'));
         $interval = $datetime1->diff($datetime2);
         $days_expiration = $interval->format('%a');
         Session::put('days_expiration', $days_expiration);
         $usuario = UserNeighbors::where('email', '=', $email)->first();
         if ($usuario) {
             $rol_vecino = AssigmentRole::where('colony_id', '=', $colony)->where('user_id', '=', $usuario->id)->where('role_id', '=', 6)->first();
             if ($rol_vecino) {
                 $notice_msg = 'Ya se encuentra como vecino en la Colonia, acceda ahora a Habitaria';
                 return Redirect::action('UsersController@login')->with('notice', $notice_msg);
             } else {
                 $neighbor = Neighbors::where('user_id', '=', $usuario->id)->first();
                 if ($neighbor) {
                     $neighborP = NeighborProperty::where('neighbors_id', '=', $neighbor->id)->where('urbanism_id', '=', $urbanism_id)->first();
                     if (!$neighborP) {
                         return Redirect::action('NeighborController@register_properties', array('neighbor' => $neighbor->id, 'urbanism_id' => $urbanism_id));
                     }
                 } else {
                     return Redirect::action('NeighborController@register_neighbors', array('user' => $usuario->id, 'urbanism_id' => $urbanism_id));
                 }
             }
         } else {
             $urbanism = Urbanism::findOrFail($urbanism_id);
             $urbanism_name = $urbanism->name;
             $urbanism_type = $urbanism->urbanism_type_id;
             if ($urbanism_type == 3) {
                 $catalog = BuildingCatalog::where('urbanism_id', '=', $urbanism_id)->orderBy('id', 'ASC')->lists('description', 'id');
                 $select = '¿Piso donde vive?';
                 $select_name = 'name_floor';
             } else {
                 $catalog = StreetCatalog::where('urbanism_id', '=', $urbanism_id)->orderBy('id', 'ASC')->lists('name', 'id');
                 $select = '¿Calle donde vive?';
                 $select_name = 'name_street';
             }
             $notice_msg = Lang::get('confide::confide.alerts.confirmation_invitation');
             return View::make('dashboard.neighbors.create', ['email' => $email, 'urbanism' => $urbanism_name, 'urbanism_id' => $urbanism_id, 'urbanism_type' => $urbanism_type, 'catalog' => $catalog, 'code' => $code, 'select_name' => $select_name, 'select' => ['' => $select], 'notice' => $notice_msg]);
         }
     } else {
         $notice_msg = 'Acceda a Habitaria con su usuario creado';
         return Redirect::action('UsersController@login')->with('notice', $notice_msg);
     }
 }
 public function store_familiar()
 {
     $colonia = Session::get("colonia");
     $urbanism = Urbanism::where('colony_id', '=', $colonia)->first();
     $post = Input::All();
     $invited_id = md5(uniqid(mt_rand(), true));
     $encrypted = Crypt::encrypt(md5(uniqid(mt_rand(), true)));
     $user_id = Auth::user()->id;
     $user_admin = Neighbors::where('user_id', '=', $user_id)->first();
     $invited = new InvitedNeighbors();
     $invited->neighbor_id = $user_admin->id;
     $invited->invited_id = $invited_id;
     $invited->urbanism_id = Input::get('urbanism');
     $invited->email = Input::get('email');
     $invited->confirmed = 0;
     $invited->confirmation_code = $encrypted;
     $invited->save();
     $user = new UserNeighbors();
     $user->email = Input::get('email');
     $user->status_id = '1';
     $user->confirmed = '1';
     $user->confirmation_code = md5(uniqid(mt_rand(), true));
     $user->save();
     $last_user_add = $user->id;
     $role = Role::where('name', '=', 'vecino')->first();
     $rol = new AssigmentRole();
     $rol->user_id = $last_user_add;
     $rol->role_id = $role->id;
     $rol->colony_id = $colonia;
     $rol->save();
     $neighbor = new Neighbors();
     $neighbor->user_id = $last_user_add;
     $neighbor->name = Input::get('firstname');
     $neighbor->last_name = Input::get('lastname');
     $neighbor->phone = Input::get('phone');
     $neighbor->save();
     $last_neighbor_add = $neighbor->id;
     $urbanism_type = Input::get('urbanism_type');
     $neighbor_properties = new NeighborProperty();
     $neighbor_properties->neighbors_id = $last_neighbor_add;
     $neighbor_properties->urbanism_id = Input::get('urbanism');
     $num_floor_id = null;
     $num_street_id = null;
     if ($urbanism_type == 3) {
         $num_floor_id = Input::get('piso');
         $neighbor_properties->num_floor_id = $num_floor_id;
     } else {
         $num_street_id = Input::get('calle');
         $neighbor_properties->num_street_id = $num_street_id;
     }
     $house = Input::get('casa');
     $neighbor_properties->num_house_or_apartment = $house;
     $buscardomicilio = NeighborProperty::select('neighbors_properties.id')->where('neighbors_properties.urbanism_id', '=', $urbanism->id)->where('neighbors_properties.num_floor_id', '=', $num_floor_id)->where('neighbors_properties.num_street_id', '=', $num_street_id)->where('neighbors_properties.num_house_or_apartment', '=', $house)->first();
     if ($buscardomicilio) {
         $status = 0;
     } else {
         $status = 1;
     }
     $neighbor_properties->status = $status;
     $neighbor_properties->save();
     $neighbor_reg = InvitedNeighbors::where('invited_id', '=', $invited_id)->first();
     $urbanism = Urbanism::where('id', '=', $neighbor_reg->urbanism_id)->first();
     $email = $neighbor_reg->email;
     $data = array('email' => $email, 'link' => 'ConfirmationController@confirm_data_fam', 'code' => $neighbor_reg->confirmation_code, 'name_inv' => $user_admin->name, 'lname_inv' => $user_admin->last_name, 'urbanism' => $urbanism->name);
     Mail::send('emails.confirm_neighbors', $data, function ($message) use($email) {
         $message->subject('Invitación HABITARIA');
         $message->to($email);
     });
     $notice_msg = 'Datos guardados exitosamente';
     return Redirect::action('ColonyController@reg_familiar')->with('error', false)->with('msg', $notice_msg)->with('class', 'info');
 }
 public function charges_store()
 {
     $user_id = Auth::user()->id;
     $colonia = Session::get("colonia");
     $urbanism = Urbanism::where('colony_id', '=', $colonia)->first();
     $collector = Collector::where('user_id', '=', $user_id)->where('urbanism_id', '=', $urbanism->id)->first();
     $ano = date("Y");
     $neighbor = Input::get('valorid');
     $amount = Input::get('amount');
     $income_charge = new Payment();
     $income_charge->neighbor_property_id = $neighbor;
     $income_charge->collector_id = $collector->id;
     $income_charge->amount = $amount;
     $income_charge->sub_account_id = Input::get('sub_account_id');
     $income_charge->coments = Input::get('coments');
     $income_charge->deposit = null;
     $income_charge->debt = null;
     $income_charge->status_id = 1;
     $income_charge->updated_at = date('Y') . '-01-01 ' . date('H:i:s');
     if ($income_charge->save()) {
         $neighbor_payments = $income_charge;
         $payment_state = PaymentStates::where('neighbor_property_id', '=', $neighbor)->where('year', '=', $ano)->orderBy('created_at', 'desc')->first();
         $months = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
         $monthly_all = MonthlyFee::where('monthly_fee.urbanism_id', '=', $collector->urbanism_id)->where(DB::raw('DATE_FORMAT(monthly_fee.since,\'%Y\')'), '=', $ano)->get();
         $monthly_ini = MonthlyFee::where('monthly_fee.urbanism_id', '=', $collector->urbanism_id)->where(DB::raw('DATE_FORMAT(monthly_fee.since,\'%Y\')'), '=', $ano)->orderBy('monthly_fee.created_at', 'ASC')->pluck('since');
         $mes_ini = (int) date("m", strtotime($monthly_ini));
         $cuotas = array();
         foreach ($monthly_all as $cuota_mensual) {
             $ini = (int) date("m", strtotime($cuota_mensual->since));
             $fin = (int) date("m", strtotime($cuota_mensual->until));
             if ($cuota_mensual->until == NULL) {
                 $fin = (int) date("m");
             }
             for ($i = $ini; $i <= $fin; $i++) {
                 $cuotas[$months[$i - 1]] = $cuota_mensual->amount;
             }
         }
         $acumulado = $amount;
         //para guardar el monto
         $ValorInicial = $amount;
         //para guardar el valor inicial del monto ingresado
         $ValorResto = 0;
         //para comparar con el valor inicial
         $balance = Balance::where('neighbor_property_id', '=', $neighbor)->pluck('amount');
         $balance_saldo = Balance::where('neighbor_property_id', '=', $neighbor)->first();
         if ($balance) {
             $saldo = $balance;
             if ($saldo > $amount) {
                 $saldo = $saldo - $amount;
                 $amount = 0;
                 $balance_saldo->amount = $saldo;
                 $balance_saldo->update(['id']);
             } else {
                 if ($saldo < $amount) {
                     $saldo = $amount - $saldo;
                     $amount = $saldo;
                     $balance_saldo->delete(['id']);
                 } else {
                     $saldo = 0;
                     $amount = 0;
                     $balance_saldo->delete(['id']);
                 }
             }
         } else {
             $saldo = 0;
         }
         //Si el usuario no ha realizado ningún pago, se llena la tabla Payment_States por primera vez
         if (!$payment_state) {
             $TotalCuotas = 0;
             $payment_state_detail = new PaymentStates();
             $payment_state_detail->neighbor_property_id = $neighbor_payments->neighbor_property_id;
             $payment_state_detail->year = date('Y', strtotime($neighbor_payments->created_at));
             //Ciclo hasta el mes actual
             for ($i = $mes_ini - 1; $i < date('m'); $i++) {
                 if (date('m') != $i + 1) {
                     if ($amount > $cuotas[$months[$i]]) {
                         $payment_state_detail->{$months}[$i] = $cuotas[$months[$i]];
                         $amount = $amount - $cuotas[$months[$i]];
                     } else {
                         if ($amount < $cuotas[$months[$i]] && $amount != 0) {
                             $payment_state_detail->{$months}[$i] = $amount;
                             $amount = 0;
                         } else {
                             $payment_state_detail->{$months}[$i] = $cuotas[$months[$i]];
                             $amount = 0;
                         }
                     }
                 } else {
                     //si es el mes actual
                     // for: suma todas las cuotas de cada mes, las q se deben
                     for ($j = $mes_ini - 1; $j < date('m'); $j++) {
                         if ($payment_state_detail->{$months}[$j] == null) {
                             $TotalCuotas = $TotalCuotas + $cuotas[$months[$j]];
                         } elseif ($payment_state_detail->{$months}[$j] < $cuotas[$months[$j]] && $payment_state_detail->{$months}[$j] > 0) {
                             $resto_mes = $cuotas[$months[$j]] - $payment_state_detail->{$months}[$j];
                             $TotalCuotas = $TotalCuotas + $resto_mes;
                         }
                     }
                     if ($TotalCuotas > $amount) {
                         $TotalCuotas = $TotalCuotas - $amount;
                         $payment_state_detail->{$months}[$i] = "-" . $TotalCuotas;
                     } elseif ($TotalCuotas < $amount) {
                         $TotalCuotas = $amount - $TotalCuotas;
                         $payment_state_detail->{$months}[$i] = $cuotas[$months[$i]] + $TotalCuotas;
                         $amount = $TotalCuotas;
                     } elseif ($TotalCuotas == $amount) {
                         //si la cuota es igual al monto que esta pagando
                         $payment_state_detail->{$months}[$i] = $cuotas[$months[$i]];
                         $amount = 0;
                     }
                 }
             }
             //fin del ciclo
             $payment_state_detail->accumulated = $acumulado;
             //Se guardan los datos en Payment_States
             $payment_state_detail->save();
         } else {
             //si ya tiene registros en payment_state
             $fondo = $payment_state->accumulated + $amount;
             $valorResto = 0;
             $abono = 0;
             for ($i = $mes_ini - 1; $i < date('m'); $i++) {
                 if (date('m') != $i + 1) {
                     if ($payment_state->{$months}[$i]) {
                         if ($payment_state->{$months}[$i] != $cuotas[$months[$i]] && $payment_state->{$months}[$i] > 0) {
                             $valorResto = $ValorResto + $payment_state->{$months}[$i];
                             $amount = $amount + $valorResto;
                             if ($amount > $cuotas[$months[$i]]) {
                                 $payment_state->{$months}[$i] = $cuotas[$months[$i]];
                                 $amount = $amount - $cuotas[$months[$i]];
                             } else {
                                 $payment_state->{$months}[$i] = $amount;
                                 $amount = 0;
                             }
                         }
                     } else {
                         if ($amount > $cuotas[$months[$i]]) {
                             $payment_state->{$months}[$i] = $cuotas[$months[$i]];
                             $amount = $amount - $cuotas[$months[$i]];
                         } else {
                             if ($amount < $cuotas[$months[$i]]) {
                                 $payment_state->{$months}[$i] = $amount;
                                 $amount = 0;
                             } else {
                                 $payment_state->{$months}[$i] = $cuotas[$months[$i]];
                                 $amount = 0;
                             }
                         }
                     }
                 } else {
                     //si es el mes actual
                     if ($payment_state->{$months}[$i] < 0) {
                         $deuda = -1 * $payment_state->{$months}[$i];
                         $deuda = $amount - $deuda;
                         if ($deuda < 0) {
                             $payment_state->{$months}[$i] = $deuda;
                         } else {
                             if ($deuda == 0) {
                                 $payment_state->{$months}[$i] = $cuotas[$months[$i]];
                             } else {
                                 $payment_state->{$months}[$i] = $deuda + $cuotas[$months[$i]];
                             }
                         }
                     } else {
                         $abono = $payment_state->{$months}[$i] + $amount;
                         $payment_state->{$months}[$i] = $abono;
                     }
                 }
             }
             $payment_state->accumulated = $fondo;
             $payment_state->update(['id']);
         }
         //---envio por email de recibo al pagador---
         $mensaje = null;
         $monto = Input::get('amount');
         $infoCobrador = Neighbors::with('NeighborProperty')->where('user_id', '=', $user_id)->first();
         $infoPagador = NeighborProperty::where('id', '=', $neighbor)->first();
         $email = UserNeighbors::where('id', '=', $infoPagador->Neighbors->user_id)->pluck('email');
         $tipoUrb = $infoPagador->Urbanism->UrbanismType->id;
         if ($tipoUrb == 3) {
             $Domicilio = "Piso " . $infoPagador->Building->description . ' - Apartamento ' . $infoPagador->num_house_or_apartment;
         } else {
             $Domicilio = "Calle " . $infoPagador->Street->name . ' - Casa ' . $infoPagador->num_house_or_apartment;
         }
         $Colony = Urbanism::with('Colony.City')->where('id', '=', $infoPagador->Urbanism->id)->first();
         $state = DB::table('states')->where('id', $Colony->Colony->City->state_id)->first();
         $dias = array("Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado");
         $meses = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
         $fecha = $dias[date('w')] . " " . date('d') . " de " . $meses[date('n') - 1] . " del " . date('Y');
         $pay_states = PaymentStates::where('neighbor_property_id', '=', $neighbor)->where('year', '=', $ano)->get();
         $data = array('Cobrador' => $infoCobrador->name . " " . $infoCobrador->last_name, 'Nombre' => $infoPagador->Neighbors->name . " " . $infoPagador->Neighbors->last_name, 'Domicilio' => $Domicilio, 'monto' => $monto, 'Fecha' => $fecha, 'colonia' => $Colony->Colony->name, 'urbanismo' => $infoPagador->Urbanism->name, 'estado' => $state->name, 'ciudad' => $Colony->Colony->City->name, 'payments' => $pay_states, 'months' => $months, 'cuotas' => $cuotas, 'mes_ini' => $mes_ini);
         try {
             Mail::send('emails.Recibo', $data, function ($message) use($email) {
                 $message->to($email);
                 $message->subject('Recibo de pago');
             });
         } catch (Exception $exc) {
             Mail::send('emails.Recibo', $data, function ($message) use($email) {
                 $message->to($email);
                 $message->subject('Recibo de pago');
             });
         }
         // ---/fin de envio por email de recibo al pagador/----
         //se agrego el logs
         Event::fire('logs', 'hizo un Cobro al Domicilio ' . $Domicilio . ' de un Monto de' . $monto);
         //fin logs
         return Redirect::action('IncomesController@charges_index')->with('error', false)->with('msg', 'Cobro ingresado con éxito.')->with('class', 'info');
     } else {
         return Redirect::back()->with('error', true)->with('msg', '¡Algo salió mal! Contacte con administrador.')->with('class', 'danger');
     }
 }
 public function store_update_fam()
 {
     $post = Input::All();
     $email = Input::get('email');
     $user_id = User::where('email', '=', $email)->pluck('id');
     $neighbor_add = Neighbors::where('user_id', '=', $user_id)->first();
     $neighbor_pro = NeighborProperty::where('neighbors_id', '=', $neighbor_add->id)->first();
     $user = UserNeighbors::findOrFail($user_id);
     $user->password = Hash::make(Input::get('password'));
     $user->update(['id']);
     $last_user_add = $user->id;
     $neighbor = Neighbors::findOrFail($neighbor_add->id);
     $neighbor->name = Input::get('firstname');
     $neighbor->last_name = Input::get('lastname');
     $neighbor->phone = Input::get('phone');
     $neighbor->update(['id']);
     $confirm = InvitedNeighbors::where('Confirmation_code', '=', Input::get('code'))->first();
     $confirm->confirmed = true;
     $confirm->update(['id']);
     $urbanismNeigh = $neighbor_pro->urbanism_id;
     $colonies = Colony::select('colonies.id')->join('urbanisms', 'urbanisms.colony_id', '=', 'colonies.id')->join('neighbors_properties', 'urbanisms.id', '=', 'neighbors_properties.urbanism_id')->where('neighbors_properties.urbanism_id', '=', $urbanismNeigh)->first();
     $user_auth = User::where('id', '=', $last_user_add)->first();
     Auth::login($user_auth);
     if (Auth::check()) {
         Session::put('colonia', $colonies->id);
         return Redirect::action('HomeController@index');
     } else {
         return Redirect::action('UsersController@login');
     }
 }