package handlers

import (
	"net/http"
	"time"

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


func VolunteerAppointmentHandler(w http.ResponseWriter, r *http.Request) {
    // Fetch appointments joined with address info

    currentUserID := models.GetCurrentUserID(w,r)
    username,_ := models.GetCurrentUserName(r)

    rows, err := models.DB.Query(`
        SELECT 
            a.sched_id, 
            a.user_id, 
            ad.address, 
            ad.latitude, 
            ad.longitude, 
            a.appointment_date, 
            a.appointment_time
        FROM appointment a
        JOIN address_database ad ON a.address_id = ad.address_id
        WHERE a.user_id = $1
    `, currentUserID)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer rows.Close()

    // Struct to hold appointment + address info
    type AppointmentWithAddress struct {
        SchedID        int
        UserID         int
        Address        string
        Latitude       float64
        Longitude      float64
        AppointmentDate time.Time
        AppointmentTime time.Time
    }

    var appointments []AppointmentWithAddress
    for rows.Next() {
        var a AppointmentWithAddress
        if err := rows.Scan(&a.SchedID, &a.UserID, &a.Address, &a.Latitude, &a.Longitude, &a.AppointmentDate, &a.AppointmentTime); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        appointments = append(appointments, a)
    }
		
	role := r.Context().Value("user_role").(int)
	adminnav := false
	volunteernav := false

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

    // Render template
    utils.Render(w, "/appointment.html", map[string]interface{}{
        "Title":             "My Profile",
        "IsAuthenticated":   true,
        "ShowAdminNav":      adminnav,      // your existing variable
        "ShowVolunteerNav":  volunteernav,  // your existing variable
        "ActiveSection":     "address",
        "UserName": 	username,
        "Appointments":      appointments,  // pass the fetched appointments
    })
}
