package controllers

import (
	m "skripsi/skripsiBackend/models"

	"github.com/revel/revel"

	"database/sql"
)

type Login struct {
	*revel.Controller
}

func (c Login) Show() revel.Result {
	db, err := sql.Open("mysql", revel.Config.StringDefault("db.spec", ""))
	if err != nil {
		// revel.ERROR.Println("Koneksi database gagal:", err)
		return c.RenderText("Koneksi database gagal")
	}
	defer db.Close()

	rows, err := db.Query("SELECT * FROM admin LIMIT 1")

	if err != nil {
		// revel.ERROR.Println("Query gagal:", err)
		return c.RenderText("Query gagal")
	}
	defer rows.Close()

	admins := []m.Login{}
	for rows.Next() {
		admin := m.Login{}
		if err := rows.Scan(&admin.Username, &admin.Password); err != nil {
			// revel.ERROR.Println("Baca data gagal:", err)
			return c.RenderText("Baca data gagal")
		}
		admins = append(admins, admin)
	}

	c.ViewArgs["Admin"] = admins[0]

	return c.Render()

}

func (c Login) NewPassword(admin m.Login) revel.Result {

	db, err := sql.Open("mysql", revel.Config.StringDefault("db.spec", ""))
	if err != nil {
		return c.RenderText("Koneksi database gagal")
	}
	defer db.Close()

	_, err = db.Exec("UPDATE admin SET password=?", admin.Password)
	if err != nil {
		// Handle error here
		return c.RenderText("Update data gagal")
	}

	return c.RenderText("Password admin berhasil diupdate")
}
