const express = require("express");
const Router = express.Router();
const homeSchema = require("../models/homeSchema");


Router.get('/', (err, res) => {
    res.render('register', { title: "Fill Form", password:" ", email:" "})
})


Router.post('/register', async (req, res) => {
    try {
        const{
            name,
            number,
            email,
            password,
            cpassword
          } = req.body;

          if(password === cpassword){
            
           const userData = new homeSchema({
            name,
            number,
            email,
            password
           })
          userData.save(err => {
            if(err){
              res.render('register', { title: "Already Resistered", password:" ", email:" "})
            }
            else{
              res.render('register', { title: "Done", password:" ", email:" "})
            }
          })
 


// 


        } 
          else{
            res.render('register', { title: " ", password:"Password not matching", email:" "})
          }

    } catch (error) {
        res.render('register', { title: "Error in code", password:"", email:""})
    }
})
 

// signin

Router.post('/login', (req, res)=>{
   const{
    email,
    password
   } = req.body;

   homeSchema.findOne({email:email}, (err, result) => {
      if(email === result.email && password === result.password){
        res.render('dashbord', {name: result.name})
      }
      else{
        res.render('register', { title: "Password Wrong!!! ", password:" ", email:" "})
      }
   })
 
   
})

module.exports = Router;