package handlers

import (
	"log"
	"net/http"

	"github.com/patel-mann/poll-system/app/internal/models"
	"github.com/patel-mann/poll-system/app/internal/utils"
)

func ProfileHandler(w http.ResponseWriter, r *http.Request) {
	// Extract current user ID from session/jwt
	currentUserID := r.Context().Value("user_id").(int)
	username,_ := models.GetCurrentUserName(r)

	var user models.User
	err := models.DB.QueryRow(`
		SELECT user_id, first_name, last_name, email, phone, role_id, created_at, updated_at, admin_code
		FROM "users"
		WHERE user_id = $1
	`, currentUserID).Scan(
		&user.UserID,
		&user.FirstName,
		&user.LastName,
		&user.Email,
		&user.Phone,
		&user.RoleID,
		&user.CreatedAt,
		&user.UpdatedAt,
		&user.AdminCode,
	)
	if err != nil {
		log.Println("Profile query error:", err)
		http.Error(w, "Could not load profile", http.StatusInternalServerError)
		return
	}
	
	role := r.Context().Value("user_role").(int)
	adminnav := false
	volunteernav := false

	if role == 1{
		adminnav = true
		volunteernav = false
	}else{
		adminnav = false
		volunteernav = true
	}

	utils.Render(w, "profile/profile.html", map[string]interface{}{
		"Title":           "My Profile",
		"IsAuthenticated": true,
		"ShowAdminNav":    adminnav,
		"ShowVolunteerNav": volunteernav,
		"UserName": 	username,
		"User":            user,
		"ActiveSection":   "profile",
	})
}

// ProfileUpdateHandler handles profile form submissions
func ProfileUpdateHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Redirect(w, r, "/profile", http.StatusSeeOther)
		return
	}

	// Extract current user ID from session/jwt
	currentUserID := r.Context().Value("user_id").(int)

	// Parse form values
	err := r.ParseForm()
	if err != nil {
		log.Println("Form parse error:", err)
		http.Error(w, "Invalid form submission", http.StatusBadRequest)
		return
	}

	firstName := r.FormValue("first_name")
	lastName := r.FormValue("last_name")
	phone := r.FormValue("phone")

	// Update in DB
	_, err = models.DB.Exec(`
		UPDATE "users"
		SET first_name = $1,
			last_name = $2,
			phone = $3,
			updated_at = NOW()
		WHERE user_id = $4
	`, firstName, lastName, phone, currentUserID)

	if err != nil {
		log.Println("Profile update error:", err)
		http.Error(w, "Could not update profile", http.StatusInternalServerError)
		return
	}

	// Redirect back to profile with success
	http.Redirect(w, r, "/profile?success=1", http.StatusSeeOther)
}
