package handlers

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"furry-sos-backend/config"
)

// ======================================================
// HELPER : GET USER ID
// ======================================================

func getUserIDFromRequest(r *http.Request) (int, error) {

	userIDStr := r.Header.Get("X-User-ID")

	if userIDStr == "" {
		return 0, fmt.Errorf("missing X-User-ID")
	}

	userID, err := strconv.Atoi(userIDStr)

	if err != nil {
		return 0, err
	}

	if userID <= 0 {
		return 0, fmt.Errorf("invalid user id")
	}

	return userID, nil
}

// ======================================================
// HELPER : GET USER ROLE
// ======================================================

func getUserRole(userID int) (string, error) {

	var role string

	err := config.DB.QueryRow(
		`
		SELECT COALESCE(role, 'user')
		FROM users
		WHERE user_id = ?
		`,
		userID,
	).Scan(&role)

	if err != nil {
		return "", err
	}

	return role, nil
}

// ======================================================
// 🧑‍⚕️ REGISTER VOLUNTEER
// POST /api/volunteer/register
//
// เฉพาะ account ที่สมัครมาเป็น volunteer เท่านั้น
// ผู้ใช้ทั่วไป role=user สมัครเป็น volunteer ภายหลังไม่ได้
// ======================================================

func RegisterVolunteer(
	w http.ResponseWriter,
	r *http.Request,
) {

	if r.Method != http.MethodPost {

		http.Error(
			w,
			"Method not allowed",
			http.StatusMethodNotAllowed,
		)

		return
	}

	// --------------------------------------------------
	// USER ID
	// --------------------------------------------------

	userID, err := getUserIDFromRequest(r)

	if err != nil {

		http.Error(
			w,
			"ไม่พบ User ID",
			http.StatusUnauthorized,
		)

		return
	}

	// --------------------------------------------------
	// ตรวจ ROLE
	// --------------------------------------------------

	role, err := getUserRole(userID)

	if err != nil {

		http.Error(
			w,
			"ไม่พบข้อมูลผู้ใช้งาน",
			http.StatusNotFound,
		)

		return
	}

	if role != "volunteer" {

		http.Error(
			w,
			"บัญชีผู้ใช้งานทั่วไปไม่สามารถสมัครเป็นอาสาสมัครได้ กรุณาสร้างบัญชีอาสาสมัครใหม่",
			http.StatusForbidden,
		)

		return
	}

	// --------------------------------------------------
	// REQUEST DATA
	// รองรับทั้ง JSON เดิม และ Multipart + KYC
	// --------------------------------------------------

	var data struct {
		IDCardImage      string `json:"id_card_image"`
		WorkingArea      string `json:"working_area"`
		ExperienceYears  int    `json:"experience_years"`
		ExperienceDetail string `json:"experience_detail"`
		CanEmergency     bool   `json:"can_emergency"`
		CanBodyRetrieval bool   `json:"can_body_retrieval"`
		AvailableDays    string `json:"available_days"`
		AvailableTime    string `json:"available_time"`
	}

	contentType :=
		r.Header.Get("Content-Type")

	if strings.HasPrefix(
		contentType,
		"multipart/form-data",
	) {

		// จำกัดขนาด request ไม่เกิน 10 MB
		r.Body =
			http.MaxBytesReader(
				w,
				r.Body,
				10<<20,
			)

		if err := r.ParseMultipartForm(
			10 << 20,
		); err != nil {

			http.Error(
				w,
				"ไม่สามารถอ่านข้อมูลแบบ Multipart ได้: "+err.Error(),
				http.StatusBadRequest,
			)

			return
		}

		form := r.MultipartForm

		data.WorkingArea =
			r.FormValue(
				"working_area",
			)

		data.ExperienceYears,
			_ = strconv.Atoi(
			r.FormValue(
				"experience_years",
			),
		)

		data.ExperienceDetail =
			r.FormValue(
				"experience_detail",
			)

		data.CanEmergency =
			r.FormValue(
				"can_emergency",
			) == "true"

		data.CanBodyRetrieval =
			r.FormValue(
				"can_body_retrieval",
			) == "true"

		data.AvailableDays =
			r.FormValue(
				"available_days",
			)

		data.AvailableTime =
			r.FormValue(
				"available_time",
			)

		// --------------------------------------------------
		// SAVE KYC FILE
		// --------------------------------------------------

		files :=
			form.File["id_card_file"]

		if len(files) == 0 {

			http.Error(
				w,
				"กรุณาแนบเอกสารยืนยันตัวตน (KYC)",
				http.StatusBadRequest,
			)

			return
		}

		header :=
			files[0]

		extension :=
			filepath.Ext(
				header.Filename,
			)

		extension =
			strings.ToLower(
				extension,
			)

		allowedExtensions :=
			map[string]bool{
				".jpg":  true,
				".jpeg": true,
				".png":  true,
				".webp": true,
			}

		if !allowedExtensions[extension] {

			http.Error(
				w,
				"รองรับเอกสารรูปภาพ JPG, JPEG, PNG และ WEBP เท่านั้น",
				http.StatusBadRequest,
			)

			return
		}

		if header.Size <= 0 {

			http.Error(
				w,
				"ไฟล์ KYC ว่าง",
				http.StatusBadRequest,
			)

			return
		}

		if header.Size >
			5*1024*1024 {

			http.Error(
				w,
				"ไฟล์ KYC ต้องมีขนาดไม่เกิน 5 MB",
				http.StatusBadRequest,
			)

			return
		}

		if err := os.MkdirAll(
			"./uploads",
			0755,
		); err != nil {

			http.Error(
				w,
				"ไม่สามารถเตรียมโฟลเดอร์อัปโหลดได้: "+err.Error(),
				http.StatusInternalServerError,
			)

			return
		}

		srcFile, err :=
			header.Open()

		if err != nil {

			http.Error(
				w,
				"ไม่สามารถเปิดไฟล์ KYC ได้: "+err.Error(),
				http.StatusInternalServerError,
			)

			return
		}

		defer srcFile.Close()

		fileName := fmt.Sprintf(
			"volunteer_kyc_%d_%d%s",
			userID,
			time.Now().UnixNano(),
			extension,
		)

		destinationPath :=
			filepath.Join(
				"./uploads",
				fileName,
			)

		dstFile, err :=
			os.Create(
				destinationPath,
			)

		if err != nil {

			http.Error(
				w,
				"ไม่สามารถบันทึกไฟล์ KYC ได้: "+err.Error(),
				http.StatusInternalServerError,
			)

			return
		}

		_, copyErr :=
			io.Copy(
				dstFile,
				srcFile,
			)

		closeErr :=
			dstFile.Close()

		if copyErr != nil ||
			closeErr != nil {

			_ = os.Remove(
				destinationPath,
			)

			http.Error(
				w,
				"ไม่สามารถบันทึกไฟล์ KYC ได้",
				http.StatusInternalServerError,
			)

			return
		}

		data.IDCardImage =
			"/uploads/" +
				fileName

	} else {

		// --------------------------------------------------
		// JSON API เดิม
		// --------------------------------------------------

		if err := json.NewDecoder(
			r.Body,
		).Decode(&data); err != nil {

			http.Error(
				w,
				"ข้อมูลไม่ถูกต้อง",
				http.StatusBadRequest,
			)

			return
		}
	}

	// --------------------------------------------------
	// ต้องมี KYC
	// --------------------------------------------------

	if strings.TrimSpace(
		data.IDCardImage,
	) == "" {

		http.Error(
			w,
			"กรุณาแนบเอกสารยืนยันตัวตน (KYC)",
			http.StatusBadRequest,
		)

		return
	}

	// --------------------------------------------------
	// ตรวจว่ามีข้อมูล volunteer แล้วหรือยัง
	// --------------------------------------------------

	var count int

	err = config.DB.QueryRow(
		`
		SELECT COUNT(*)
		FROM volunteers
		WHERE user_id = ?
		`,
		userID,
	).Scan(&count)

	if err != nil {

		http.Error(
			w,
			"ตรวจสอบข้อมูลอาสาสมัครไม่สำเร็จ: "+err.Error(),
			http.StatusInternalServerError,
		)

		return
	}

	if count > 0 {

		http.Error(
			w,
			"บัญชีนี้มีข้อมูลอาสาสมัครอยู่แล้ว",
			http.StatusConflict,
		)

		return
	}

	// --------------------------------------------------
	// INSERT VOLUNTEER
	// --------------------------------------------------

	query := `
		INSERT INTO volunteers
		(
			user_id,
			id_card_image,
			tier_level,
			is_approved,
			application_status,
			is_online,
			working_area,
			experience_years,
			experience_detail,
			can_emergency,
			can_body_retrieval,
			available_days,
			available_time,
			total_missions,
			avg_rating,
			created_at
		)
		VALUES
		(
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?,
			?
		)
	`

	result, err := config.DB.Exec(
		query,
		userID,
		data.IDCardImage,
		"basic",
		false,
		"pending",
		false,
		data.WorkingArea,
		data.ExperienceYears,
		data.ExperienceDetail,
		data.CanEmergency,
		data.CanBodyRetrieval,
		data.AvailableDays,
		data.AvailableTime,
		0,
		0,
		time.Now(),
	)

	if err != nil {

		http.Error(
			w,
			"ไม่สามารถสร้างข้อมูลอาสาสมัครได้: "+err.Error(),
			http.StatusInternalServerError,
		)

		return
	}

	volunteerID, err :=
		result.LastInsertId()

	if err != nil {

		http.Error(
			w,
			"สร้าง Volunteer สำเร็จแต่ไม่สามารถอ่าน ID ได้",
			http.StatusInternalServerError,
		)

		return
	}

	// --------------------------------------------------
	// RESPONSE
	// --------------------------------------------------

	w.Header().Set(
		"Content-Type",
		"application/json; charset=utf-8",
	)

	json.NewEncoder(w).Encode(
		map[string]interface{}{
			"success":            true,
			"message":            "ส่งใบสมัครอาสาสมัครเรียบร้อยแล้ว",
			"user_id":            userID,
			"role":               "volunteer",
			"volunteer_id":       volunteerID,
			"id_card_image":      data.IDCardImage,
			"status":             "pending",
			"application_status": "pending",
			"is_approved":        false,
			"is_online":          false,
			"next_step":          "admin_review",
		},
	)
}

// ======================================================
// 🏆 CALCULATE VOLUNTEER LEVEL
// ======================================================
//
// ผ่าน 0 หลักสูตร  = ยังไม่ผ่านการอบรม
// ผ่าน 1 หลักสูตร  = Bronze
// ผ่าน 2 หลักสูตร  = Silver
// ผ่าน 3+ หลักสูตร = Gold
//
// tier_level ใช้เก็บค่าภายในระบบ
// volunteer_level ใช้แสดงผลบนหน้า App
// ======================================================

// ======================================================
// 🏆 CALCULATE VOLUNTEER LEVEL
// ======================================================
//
// ผ่าน 0 หลักสูตร  = ยังไม่ผ่านการอบรม
// ผ่าน 1 หลักสูตร  = Bronze
// ผ่าน 2 หลักสูตร  = Silver
// ผ่าน 3+ หลักสูตร = Gold
//
// tier_level ใช้เก็บค่าภายในระบบ
// volunteer_level ใช้แสดงผลบนหน้า App
// ======================================================

func getVolunteerLevel(passedCourses int) (string, string) {

	switch {
	case passedCourses >= 3:
		return "expert", "Gold"

	case passedCourses == 2:
		return "operational", "Silver"

	case passedCourses == 1:
		return "basic", "Bronze"

	default:
		return "basic", "ยังไม่ผ่านการอบรม"
	}
}

// ======================================================
// 🧑‍⚕️ GET VOLUNTEER STATUS
// GET /api/volunteer/status
// ======================================================

func GetVolunteerStatus(
	w http.ResponseWriter,
	r *http.Request,
) {

	if r.Method != http.MethodGet {

		http.Error(
			w,
			"Method not allowed",
			http.StatusMethodNotAllowed,
		)

		return
	}

	userID, err := getUserIDFromRequest(r)

	if err != nil {

		http.Error(
			w,
			"Unauthorized",
			http.StatusUnauthorized,
		)

		return
	}

	// --------------------------------------------------
	// ตรวจ ROLE
	// --------------------------------------------------

	role, err := getUserRole(userID)

	if err != nil {

		http.Error(
			w,
			"ไม่พบข้อมูลผู้ใช้งาน",
			http.StatusNotFound,
		)

		return
	}

	if role != "volunteer" {

		http.Error(
			w,
			"บัญชีนี้ไม่ใช่บัญชีอาสาสมัคร",
			http.StatusForbidden,
		)

		return
	}

	// --------------------------------------------------
	// VOLUNTEER DATA
	// ✅ เพิ่ม FullName + ProfileImage
	// --------------------------------------------------

	var volunteer struct {
		VolunteerID       int
		TierLevel         string
		VolunteerLevel    string
		IsApproved        bool
		ApplicationStatus string
		RejectionReason   string
		IsOnline          bool
		WorkingArea       string
		ExperienceYears   int
		CanEmergency      bool
		CanBodyRetrieval  bool
		TotalMissions     int
		AvgRating         float64
		FullName          string // ✅ เพิ่ม
		ProfileImage      string // ✅ เพิ่ม
		PassedCourses     int
		TotalCourses      int
	}

	// ✅ JOIN กับ users เพื่อดึง full_name และ profile_image
	query := `
		SELECT
			v.volunteer_id,
			v.tier_level,
			v.is_approved,
			v.application_status,
			COALESCE(v.rejection_reason, ''),
			v.is_online,
			COALESCE(v.working_area, ''),
			COALESCE(v.experience_years, 0),
			COALESCE(v.can_emergency, 0),
			COALESCE(v.can_body_retrieval, 0),
			COALESCE(v.total_missions, 0),

			(
				SELECT COALESCE(AVG(vr.rating), 0)
				FROM volunteer_reviews vr
				WHERE vr.volunteer_id = v.volunteer_id
				AND vr.rating IS NOT NULL
				AND vr.rating > 0
			) AS avg_rating,
			COALESCE(u.full_name, '')     AS full_name,
			COALESCE(u.profile_image, '') AS profile_image

		FROM volunteers v

		INNER JOIN users u
			ON v.user_id = u.user_id

		WHERE v.user_id = ?
	`

	err = config.DB.QueryRow(
		query,
		userID,
	).Scan(
		&volunteer.VolunteerID,
		&volunteer.TierLevel,
		&volunteer.IsApproved,
		&volunteer.ApplicationStatus,
		&volunteer.RejectionReason,
		&volunteer.IsOnline,
		&volunteer.WorkingArea,
		&volunteer.ExperienceYears,
		&volunteer.CanEmergency,
		&volunteer.CanBodyRetrieval,
		&volunteer.TotalMissions,
		&volunteer.AvgRating,
		&volunteer.FullName,     // ✅ เพิ่ม
		&volunteer.ProfileImage, // ✅ เพิ่ม
	)

	if err != nil {

		http.Error(
			w,
			"ยังไม่ได้สมัครเป็นอาสาสมัคร",
			http.StatusNotFound,
		)

		return
	}

	// --------------------------------------------------
	// 🏆 นับจำนวนหลักสูตรที่สอบผ่าน
	// --------------------------------------------------

	var passedCourses int

	err = config.DB.QueryRow(
		`
		SELECT COUNT(DISTINCT training_id)
		FROM volunteer_quiz_results
		WHERE volunteer_id = ?
		  AND is_passed = 1
		`,
		volunteer.VolunteerID,
	).Scan(&passedCourses)

	if err != nil {
		http.Error(
			w,
			"ไม่สามารถตรวจสอบผลการอบรมได้: "+err.Error(),
			http.StatusInternalServerError,
		)
		return
	}

	// --------------------------------------------------
	// 📚 นับจำนวนหลักสูตรทั้งหมด
	// --------------------------------------------------

	var totalCourses int

	err = config.DB.QueryRow(
		`
		SELECT COUNT(DISTINCT title)
		FROM volunteer_training
		WHERE is_active = 1
		`,
	).Scan(&totalCourses)

	if err != nil {
		http.Error(
			w,
			"ไม่สามารถตรวจสอบจำนวนหลักสูตรได้: "+err.Error(),
			http.StatusInternalServerError,
		)
		return
	}

	// --------------------------------------------------
	// 🏆 คำนวณระดับจากจำนวนหลักสูตรที่ผ่าน
	// --------------------------------------------------

	tierLevel, volunteerLevel := getVolunteerLevel(passedCourses)

	volunteer.TierLevel = tierLevel
	volunteer.VolunteerLevel = volunteerLevel
	volunteer.PassedCourses = passedCourses
	volunteer.TotalCourses = totalCourses

	// --------------------------------------------------
	// 💾 อัปเดตระดับล่าสุดลง Database
	// --------------------------------------------------

	_, err = config.DB.Exec(
		`
		UPDATE volunteers
		SET tier_level = ?
		WHERE volunteer_id = ?
		`,
		tierLevel,
		volunteer.VolunteerID,
	)

	if err != nil {
		http.Error(
			w,
			"ไม่สามารถอัปเดตระดับอาสาสมัครได้: "+err.Error(),
			http.StatusInternalServerError,
		)
		return
	}

	// --------------------------------------------------
	// RESPONSE
	// ✅ เพิ่ม full_name + profile_image
	// --------------------------------------------------

	w.Header().Set(
		"Content-Type",
		"application/json; charset=utf-8",
	)

	json.NewEncoder(w).Encode(
		map[string]interface{}{
			"success": true,

			"volunteer": map[string]interface{}{
				"volunteer_id":       volunteer.VolunteerID,
				"tier_level":         volunteer.TierLevel,
				"volunteer_level":    volunteer.VolunteerLevel,
				"full_name":          volunteer.FullName,     // ✅ เพิ่ม
				"profile_image":      volunteer.ProfileImage, // ✅ เพิ่ม
				"passed_courses":     volunteer.PassedCourses,
				"total_courses":      volunteer.TotalCourses,
				"is_approved":        volunteer.IsApproved,
				"application_status": volunteer.ApplicationStatus,
				"rejection_reason":   volunteer.RejectionReason,
				"is_online":          volunteer.IsOnline,
				"working_area":       volunteer.WorkingArea,
				"experience_years":   volunteer.ExperienceYears,
				"can_emergency":      volunteer.CanEmergency,
				"can_body_retrieval": volunteer.CanBodyRetrieval,
				"total_missions":     volunteer.TotalMissions,
				"avg_rating":         volunteer.AvgRating,
			},
		},
	)
}

// ======================================================
// 🟢 TOGGLE VOLUNTEER ONLINE
// POST /api/volunteer/toggle-online
//
// เฉพาะอาสาที่ Admin อนุมัติแล้ว
// ======================================================

func ToggleOnlineStatus(
	w http.ResponseWriter,
	r *http.Request,
) {

	if r.Method != http.MethodPost {

		http.Error(
			w,
			"Method not allowed",
			http.StatusMethodNotAllowed,
		)

		return
	}

	userID, err := getUserIDFromRequest(r)

	if err != nil {

		http.Error(
			w,
			"Unauthorized",
			http.StatusUnauthorized,
		)

		return
	}

	// --------------------------------------------------
	// ROLE
	// --------------------------------------------------

	role, err := getUserRole(userID)

	if err != nil {

		http.Error(
			w,
			"ไม่พบข้อมูลผู้ใช้งาน",
			http.StatusNotFound,
		)

		return
	}

	if role != "volunteer" {

		http.Error(
			w,
			"บัญชีนี้ไม่ใช่บัญชีอาสาสมัคร",
			http.StatusForbidden,
		)

		return
	}

	// --------------------------------------------------
	// อ่านสถานะ
	// --------------------------------------------------

	var currentStatus bool
	var isApproved bool
	var applicationStatus string

	err = config.DB.QueryRow(
		`
		SELECT
			is_online,
			is_approved,
			application_status
		FROM volunteers
		WHERE user_id = ?
		`,
		userID,
	).Scan(
		&currentStatus,
		&isApproved,
		&applicationStatus,
	)

	if err != nil {

		http.Error(
			w,
			"ไม่พบข้อมูลอาสาสมัคร",
			http.StatusNotFound,
		)

		return
	}

	// --------------------------------------------------
	// ต้องผ่าน Admin ก่อน
	// --------------------------------------------------

	if !isApproved || applicationStatus != "approved" {

		http.Error(
			w,
			"บัญชีอาสาสมัครยังไม่ได้รับการอนุมัติจาก Admin",
			http.StatusForbidden,
		)

		return
	}

	// --------------------------------------------------
	// TOGGLE
	// --------------------------------------------------

	newStatus := !currentStatus

	_, err = config.DB.Exec(
		`
		UPDATE volunteers
		SET is_online = ?
		WHERE user_id = ?
		`,
		newStatus,
		userID,
	)

	if err != nil {

		http.Error(
			w,
			"ไม่สามารถเปลี่ยนสถานะได้: "+err.Error(),
			http.StatusInternalServerError,
		)

		return
	}

	// --------------------------------------------------
	// RESPONSE
	// --------------------------------------------------

	w.Header().Set(
		"Content-Type",
		"application/json; charset=utf-8",
	)

	json.NewEncoder(w).Encode(
		map[string]interface{}{
			"success":   true,
			"is_online": newStatus,
			"message":   getOnlineStatusMessage(newStatus),
		},
	)
}

// ======================================================
// ONLINE MESSAGE
// ======================================================

func getOnlineStatusMessage(
	isOnline bool,
) string {

	if isOnline {
		return "เปิดสถานะพร้อมรับงานแล้ว"
	}

	return "ปิดสถานะพร้อมรับงานแล้ว"
}

// ======================================================
// 🛡️ ADMIN
// GET /api/admin/volunteers
// ======================================================

func GetPendingVolunteers(
	w http.ResponseWriter,
	r *http.Request,
) {

	if r.Method != http.MethodGet {
		http.Error(
			w,
			"Method not allowed",
			http.StatusMethodNotAllowed,
		)
		return
	}

	query := `
		SELECT
			v.volunteer_id,
			v.user_id,

			COALESCE(u.username, ''),
			COALESCE(u.full_name, ''),
			COALESCE(u.email, ''),
			COALESCE(u.phone, ''),

			COALESCE(v.id_card_image, ''),
			COALESCE(v.working_area, ''),
			COALESCE(v.experience_years, 0),
			COALESCE(v.experience_detail, ''),

			COALESCE(v.can_emergency, 0),
			COALESCE(v.can_body_retrieval, 0),

			COALESCE(v.available_days, ''),
			COALESCE(v.available_time, ''),

			COALESCE(v.tier_level, ''),
			COALESCE(v.application_status, ''),
			v.created_at

		FROM volunteers v

		INNER JOIN users u
			ON v.user_id = u.user_id

		ORDER BY v.created_at DESC
	`

	rows, err := config.DB.Query(query)

	if err != nil {
		http.Error(
			w,
			"ไม่สามารถดึงข้อมูลใบสมัครอาสาสมัครได้: "+err.Error(),
			http.StatusInternalServerError,
		)
		return
	}

	defer rows.Close()

	type VolunteerApplication struct {
		VolunteerID       int       `json:"volunteer_id"`
		UserID            int       `json:"user_id"`
		Username          string    `json:"username"`
		FullName          string    `json:"full_name"`
		Email             string    `json:"email"`
		Phone             string    `json:"phone"`
		IDCardImage       string    `json:"id_card_image"`
		WorkingArea       string    `json:"working_area"`
		ExperienceYears   int       `json:"experience_years"`
		ExperienceDetail  string    `json:"experience_detail"`
		CanEmergency      bool      `json:"can_emergency"`
		CanBodyRetrieval  bool      `json:"can_body_retrieval"`
		AvailableDays     string    `json:"available_days"`
		AvailableTime     string    `json:"available_time"`
		TierLevel         string    `json:"tier_level"`
		ApplicationStatus string    `json:"application_status"`
		CreatedAt         time.Time `json:"created_at"`
	}

	volunteers := []VolunteerApplication{}

	for rows.Next() {

		var v VolunteerApplication

		err := rows.Scan(
			&v.VolunteerID,
			&v.UserID,
			&v.Username,
			&v.FullName,
			&v.Email,
			&v.Phone,
			&v.IDCardImage,
			&v.WorkingArea,
			&v.ExperienceYears,
			&v.ExperienceDetail,
			&v.CanEmergency,
			&v.CanBodyRetrieval,
			&v.AvailableDays,
			&v.AvailableTime,
			&v.TierLevel,
			&v.ApplicationStatus,
			&v.CreatedAt,
		)

		if err != nil {

			http.Error(
				w,
				"อ่านข้อมูลใบสมัครไม่สำเร็จ: "+err.Error(),
				http.StatusInternalServerError,
			)

			return
		}

		volunteers = append(
			volunteers,
			v,
		)
	}

	if err := rows.Err(); err != nil {

		http.Error(
			w,
			"อ่านข้อมูลไม่สำเร็จ: "+err.Error(),
			http.StatusInternalServerError,
		)

		return
	}

	w.Header().Set(
		"Content-Type",
		"application/json; charset=utf-8",
	)

	json.NewEncoder(w).Encode(
		map[string]interface{}{
			"success":    true,
			"count":      len(volunteers),
			"volunteers": volunteers,
		},
	)
}

// ======================================================
// 🟢 ADMIN APPROVE VOLUNTEER
// POST /api/admin/volunteers/approve
//
// อนุมัติแล้วเข้าสู่ขั้นตอนอบรม
// ======================================================

func ApproveVolunteer(
	w http.ResponseWriter,
	r *http.Request,
) {

	if r.Method != http.MethodPost {

		http.Error(
			w,
			"Method not allowed",
			http.StatusMethodNotAllowed,
		)

		return
	}

	var data struct {
		VolunteerID int `json:"volunteer_id"`
	}

	if err := json.NewDecoder(r.Body).Decode(&data); err != nil {

		http.Error(
			w,
			"ข้อมูลไม่ถูกต้อง",
			http.StatusBadRequest,
		)

		return
	}

	if data.VolunteerID <= 0 {

		http.Error(
			w,
			"ไม่พบ Volunteer ID",
			http.StatusBadRequest,
		)

		return
	}

	// --------------------------------------------------
	// ตรวจข้อมูล
	// --------------------------------------------------

	var userID int
	var applicationStatus string

	err := config.DB.QueryRow(
		`
		SELECT
			user_id,
			application_status
		FROM volunteers
		WHERE volunteer_id = ?
		`,
		data.VolunteerID,
	).Scan(
		&userID,
		&applicationStatus,
	)

	if err != nil {

		http.Error(
			w,
			"ไม่พบข้อมูลอาสาสมัคร",
			http.StatusNotFound,
		)

		return
	}

	if applicationStatus == "approved" {

		http.Error(
			w,
			"อาสาสมัครรายนี้ได้รับการอนุมัติแล้ว",
			http.StatusConflict,
		)

		return
	}

	// --------------------------------------------------
	// APPROVE
	// --------------------------------------------------

	_, err = config.DB.Exec(
		`
		UPDATE volunteers
		SET
			is_approved = true,
			application_status = 'approved',
			tier_level = 'basic',
			is_online = false
		WHERE volunteer_id = ?
		`,
		data.VolunteerID,
	)

	if err != nil {

		http.Error(
			w,
			"ไม่สามารถอนุมัติอาสาสมัครได้: "+err.Error(),
			http.StatusInternalServerError,
		)

		return
	}

	// --------------------------------------------------
	// RESPONSE
	// --------------------------------------------------

	w.Header().Set(
		"Content-Type",
		"application/json; charset=utf-8",
	)

	json.NewEncoder(w).Encode(
		map[string]interface{}{
			"success":            true,
			"message":            "อนุมัติอาสาสมัครเรียบร้อยแล้ว",
			"user_id":            userID,
			"volunteer_id":       data.VolunteerID,
			"is_approved":        true,
			"application_status": "approved",
			"tier_level":         "basic",

			// ขั้นตอนต่อไป
			"next_step": "training",
		},
	)
}

// ======================================================
// 🔴 ADMIN REJECT VOLUNTEER
// POST /api/admin/volunteers/reject
// ======================================================

func RejectVolunteer(
	w http.ResponseWriter,
	r *http.Request,
) {

	if r.Method != http.MethodPost {

		http.Error(
			w,
			"Method not allowed",
			http.StatusMethodNotAllowed,
		)

		return
	}

	var data struct {
		VolunteerID     int    `json:"volunteer_id"`
		Reason          string `json:"reason"`
		RejectionReason string `json:"rejection_reason"`
	}

	if err := json.NewDecoder(r.Body).Decode(&data); err != nil {

		http.Error(
			w,
			"ข้อมูลไม่ถูกต้อง",
			http.StatusBadRequest,
		)

		return
	}

	if data.VolunteerID <= 0 {

		http.Error(
			w,
			"ไม่พบ Volunteer ID",
			http.StatusBadRequest,
		)

		return
	}

	// --------------------------------------------------
	// เหตุผลการปฏิเสธ
	// --------------------------------------------------

	reason := data.Reason

	if reason == "" {
		reason = data.RejectionReason
	}

	if reason == "" {
		reason = "ไม่ผ่านการพิจารณาคุณสมบัติ"
	}

	// --------------------------------------------------
	// ตรวจข้อมูล
	// --------------------------------------------------

	var userID int

	err := config.DB.QueryRow(
		`
		SELECT user_id
		FROM volunteers
		WHERE volunteer_id = ?
		`,
		data.VolunteerID,
	).Scan(&userID)

	if err != nil {

		http.Error(
			w,
			"ไม่พบข้อมูลอาสาสมัคร",
			http.StatusNotFound,
		)

		return
	}

	// --------------------------------------------------
	// REJECT
	// --------------------------------------------------

	_, err = config.DB.Exec(
		`
		UPDATE volunteers
		SET
			is_approved = false,
			application_status = 'rejected',
			rejection_reason = ?,
			is_online = false
		WHERE volunteer_id = ?
		`,
		reason,
		data.VolunteerID,
	)

	if err != nil {

		http.Error(
			w,
			"ไม่สามารถปฏิเสธใบสมัครได้: "+err.Error(),
			http.StatusInternalServerError,
		)

		return
	}

	// --------------------------------------------------
	// RESPONSE
	// --------------------------------------------------

	w.Header().Set(
		"Content-Type",
		"application/json; charset=utf-8",
	)

	json.NewEncoder(w).Encode(
		map[string]interface{}{
			"success":            true,
			"message":            "ปฏิเสธใบสมัครอาสาสมัครแล้ว",
			"user_id":            userID,
			"volunteer_id":       data.VolunteerID,
			"is_approved":        false,
			"application_status": "rejected",
			"reason":             reason,
		},
	)
}
