package handlers

import (
	"encoding/json"
	"net/http"
	"strconv"
	"strings"

	"furry-sos-backend/config"
)

// ============================================================
// RESPONSE HELPERS
// ============================================================

func trainingJSON(
	w http.ResponseWriter,
	status int,
	data interface{},
) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(data)
}

// ============================================================
// GET VOLUNTEER ID
// user_id -> volunteer_id
// ============================================================

func getVolunteerIDByUserID(userID int) (int, error) {
	var volunteerID int

	err := config.DB.QueryRow(
		`
		SELECT volunteer_id
		FROM volunteers
		WHERE user_id = ?
		LIMIT 1
		`,
		userID,
	).Scan(&volunteerID)

	return volunteerID, err
}

// ============================================================
// GET TRAINING STATUS
//
// GET
// /api/volunteer/training?user_id=14
//
// IMPORTANT
// - ระบบมี 3 หลักสูตร: training_id 1,2,3
// - approved เท่านั้น = ผ่านจริง
// - pending = สอบผ่านแล้ว แต่รอ Admin
// - rejected = Admin ปฏิเสธ / สอบไม่ผ่าน
// - not_started = ยังไม่สอบ
//
// ============================================================

func GetVolunteerTraining(
	w http.ResponseWriter,
	r *http.Request,
) {
	if r.Method != http.MethodGet {
		trainingJSON(
			w,
			http.StatusMethodNotAllowed,
			map[string]interface{}{
				"success": false,
				"message": "Method not allowed",
			},
		)
		return
	}

	userIDString := r.URL.Query().Get("user_id")

	if userIDString == "" {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "Missing user_id",
			},
		)
		return
	}

	userID, err := strconv.Atoi(userIDString)

	if err != nil || userID <= 0 {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "Invalid user_id",
			},
		)
		return
	}

	// ==========================================================
	// FIND VOLUNTEER
	// ==========================================================

	volunteerID, err := getVolunteerIDByUserID(userID)

	if err != nil {
		trainingJSON(
			w,
			http.StatusNotFound,
			map[string]interface{}{
				"success": false,
				"message": "ไม่พบข้อมูลอาสาสมัคร",
			},
		)
		return
	}

	// ==========================================================
	// GET 3 TRAINING COURSES
	//
	// สำคัญ:
	// เลือกผลสอบล่าสุดของแต่ละหลักสูตรเพียง 1 รายการ
	// เพื่อไม่ให้ผลสอบเก่าทำให้ข้อมูลซ้ำ/นับผิด
	// ==========================================================

	rows, err := config.DB.Query(
		`
		SELECT
			t.training_id,
			t.title,
			COALESCE(t.description, ''),
			COALESCE(t.content, ''),
			COALESCE(t.video_url, ''),
			COALESCE(t.passing_score, 70),
			COALESCE(t.duration_minutes, 0),
			t.is_active,

			COALESCE(q.score, 0),
			COALESCE(q.total_questions, 0),
			COALESCE(q.is_passed, 0),
			COALESCE(q.approval_status, 'not_started'),
			COALESCE(q.attempt_number, 0),
			q.completed_at,
			q.approved_at,
			COALESCE(q.result_id, 0)

		FROM volunteer_training t

		LEFT JOIN volunteer_quiz_results q
			ON q.result_id = (
				SELECT q2.result_id
				FROM volunteer_quiz_results q2
				WHERE q2.volunteer_id = ?
				AND q2.training_id = t.training_id
				ORDER BY q2.attempt_number DESC, q2.result_id DESC
				LIMIT 1
			)

		WHERE t.is_active = 1
		AND t.training_id IN (1, 2, 3)

		ORDER BY t.training_id ASC
		`,
		volunteerID,
	)

	if err != nil {
		trainingJSON(
			w,
			http.StatusInternalServerError,
			map[string]interface{}{
				"success": false,
				"message": "โหลดข้อมูลหลักสูตรไม่สำเร็จ: " + err.Error(),
			},
		)
		return
	}

	defer rows.Close()

	courses := make([]map[string]interface{}, 0, 3)

	completedCount := 0
	pendingCount := 0

	for rows.Next() {
		var (
			trainingID     int
			title          string
			description    string
			content        string
			videoURL       string
			passingScore   int
			duration       int
			isActive       bool
			score          int
			totalQuestions int
			isPassed       bool
			status         string
			attemptNumber  int
			completedAt    interface{}
			approvedAt     interface{}
			resultID       int
		)

		err := rows.Scan(
			&trainingID,
			&title,
			&description,
			&content,
			&videoURL,
			&passingScore,
			&duration,
			&isActive,
			&score,
			&totalQuestions,
			&isPassed,
			&status,
			&attemptNumber,
			&completedAt,
			&approvedAt,
			&resultID,
		)

		if err != nil {
			trainingJSON(
				w,
				http.StatusInternalServerError,
				map[string]interface{}{
					"success": false,
					"message": "อ่านผลการอบรมไม่สำเร็จ: " + err.Error(),
				},
			)
			return
		}

		// ======================================================
		// APPROVED = ผ่านจริง
		// ======================================================

		if status == "approved" {
			completedCount++
		}

		// ======================================================
		// PENDING = สอบผ่าน แต่ยังรอ Admin
		// ======================================================

		if status == "pending" {
			pendingCount++
		}

		// ======================================================
		// CALCULATE PERCENT
		// ======================================================

		var scorePercent float64

		if totalQuestions > 0 {
			scorePercent =
				(float64(score) /
					float64(totalQuestions)) * 100
		}

		courses = append(
			courses,
			map[string]interface{}{
				"result_id": resultID,

				"training_id": trainingID,
				"course_id":   trainingID,

				"title":       title,
				"course_name": title,

				"description": description,
				"content":     content,

				"video_url": videoURL,

				"passing_score":    passingScore,
				"duration_minutes": duration,
				"is_active":        isActive,

				"score":           score,
				"total_questions": totalQuestions,
				"score_percent":   scorePercent,

				"is_passed": isPassed,

				"status": status,

				"attempt_number": attemptNumber,

				"completed_at": completedAt,
				"approved_at":  approvedAt,
			},
		)
	}

	if err := rows.Err(); err != nil {
		trainingJSON(
			w,
			http.StatusInternalServerError,
			map[string]interface{}{
				"success": false,
				"message": "อ่านข้อมูลหลักสูตรไม่สำเร็จ: " + err.Error(),
			},
		)
		return
	}

	// ==========================================================
	// LEVEL
	//
	// pending ไม่นับ
	// ต้อง approved เท่านั้น
	// ==========================================================

	level := "none"

	if completedCount >= 3 {
		level = "gold"
	} else if completedCount >= 2 {
		level = "silver"
	} else if completedCount >= 1 {
		level = "bronze"
	}

	// ==========================================================
	// CAN ENTER VOLUNTEER
	//
	// ต้อง approved อย่างน้อย 1 หลักสูตร
	// pending ยังไม่ถือว่าผ่าน
	// ==========================================================

	canEnterVolunteer := completedCount >= 1

	// ==========================================================
	// RESPONSE
	// ==========================================================

	trainingJSON(
		w,
		http.StatusOK,
		map[string]interface{}{
			"success": true,

			"user_id":      userID,
			"volunteer_id": volunteerID,

			// ระบบมี 3 หลักสูตรเท่านั้น
			"total_courses": 3,

			"completed_count": completedCount,
			"passed_courses":  completedCount,

			"pending_count":   pendingCount,
			"pending_courses": pendingCount,

			"level": level,

			"can_enter_volunteer": canEnterVolunteer,

			"courses": courses,
		},
	)
}

// ============================================================
// SUBMIT TRAINING RESULT
//
// POST
// /api/volunteer/training/submit
//
// รองรับ:
//
// {
//   "user_id": 14,
//   "course_id": 1,
//   "score": 3,
//   "total": 3
// }
//
// หรือ
//
// {
//   "user_id": 14,
//   "training_id": 1,
//   "score": 3,
//   "total_questions": 3
// }
//
// ============================================================

func SubmitVolunteerTraining(
	w http.ResponseWriter,
	r *http.Request,
) {
	if r.Method != http.MethodPost {
		trainingJSON(
			w,
			http.StatusMethodNotAllowed,
			map[string]interface{}{
				"success": false,
				"message": "Method not allowed",
			},
		)
		return
	}

	var body struct {
		UserID int `json:"user_id"`

		CourseID   int `json:"course_id"`
		TrainingID int `json:"training_id"`

		Score int `json:"score"`

		Total          int `json:"total"`
		TotalQuestions int `json:"total_questions"`
	}

	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "Invalid JSON",
			},
		)
		return
	}

	// ==========================================================
	// TOTAL QUESTIONS
	// ==========================================================

	totalQuestions := body.TotalQuestions

	if totalQuestions <= 0 {
		totalQuestions = body.Total
	}

	// ==========================================================
	// TRAINING ID
	// ==========================================================

	trainingID := body.TrainingID

	if trainingID <= 0 {
		trainingID = body.CourseID
	}

	// ==========================================================
	// VALIDATE
	// ==========================================================

	if body.UserID <= 0 {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "Invalid user_id",
			},
		)
		return
	}

	if trainingID < 1 || trainingID > 3 {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "หลักสูตรต้องอยู่ระหว่าง 1 ถึง 3",
			},
		)
		return
	}

	if totalQuestions <= 0 {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "Invalid total_questions",
			},
		)
		return
	}

	if body.Score < 0 || body.Score > totalQuestions {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "Invalid score",
			},
		)
		return
	}

	// ==========================================================
	// FIND VOLUNTEER
	// ==========================================================

	volunteerID, err := getVolunteerIDByUserID(body.UserID)

	if err != nil {
		trainingJSON(
			w,
			http.StatusNotFound,
			map[string]interface{}{
				"success": false,
				"message": "ไม่พบข้อมูลอาสาสมัคร",
			},
		)
		return
	}

	// ==========================================================
	// CHECK COURSE
	// ==========================================================

	var exists int

	err = config.DB.QueryRow(
		`
		SELECT COUNT(*)
		FROM volunteer_training
		WHERE training_id = ?
		AND is_active = 1
		AND training_id IN (1, 2, 3)
		`,
		trainingID,
	).Scan(&exists)

	if err != nil {
		trainingJSON(
			w,
			http.StatusInternalServerError,
			map[string]interface{}{
				"success": false,
				"message": "ตรวจสอบหลักสูตรไม่สำเร็จ: " + err.Error(),
			},
		)
		return
	}

	if exists == 0 {
		trainingJSON(
			w,
			http.StatusNotFound,
			map[string]interface{}{
				"success": false,
				"message": "ไม่พบหลักสูตร",
			},
		)
		return
	}

	// ==========================================================
	// CHECK CURRENT LATEST RESULT
	//
	// ถ้า approved แล้ว ห้ามส่งซ้ำ
	// ถ้า pending อยู่ ให้ใช้รายการเดิม
	// เพื่อป้องกันข้อมูลซ้ำ
	// ==========================================================

	var (
		latestResultID int
		latestStatus   string
		latestAttempt  int
	)

	err = config.DB.QueryRow(
		`
		SELECT
			result_id,
			approval_status,
			attempt_number
		FROM volunteer_quiz_results
		WHERE volunteer_id = ?
		AND training_id = ?
		ORDER BY attempt_number DESC, result_id DESC
		LIMIT 1
		`,
		volunteerID,
		trainingID,
	).Scan(
		&latestResultID,
		&latestStatus,
		&latestAttempt,
	)

	// ==========================================================
	// APPROVED ALREADY
	// ==========================================================

	if err == nil && latestStatus == "approved" {
		trainingJSON(
			w,
			http.StatusOK,
			map[string]interface{}{
				"success":      true,
				"passed":       true,
				"status":       "approved",
				"volunteer_id": volunteerID,
				"training_id":  trainingID,
				"result_id":    latestResultID,
				"message":      "หลักสูตรนี้ผ่านและได้รับการอนุมัติแล้ว",
			},
		)
		return
	}

	// ==========================================================
	// PENDING ALREADY
	//
	// ไม่สร้างแถวใหม่
	// ==========================================================

	if err == nil && latestStatus == "pending" {
		trainingJSON(
			w,
			http.StatusOK,
			map[string]interface{}{
				"success":      true,
				"passed":       true,
				"status":       "pending",
				"volunteer_id": volunteerID,
				"training_id":  trainingID,
				"result_id":    latestResultID,
				"message":      "หลักสูตรนี้สอบผ่านแล้ว และกำลังรอแอดมินอนุมัติ",
			},
		)
		return
	}

	// ==========================================================
	// CALCULATE PERCENT
	// ==========================================================

	percent :=
		(float64(body.Score) /
			float64(totalQuestions)) * 100

	passed := percent >= 70

	// ==========================================================
	// ATTEMPT NUMBER
	// ==========================================================

	attemptNumber := 1

	if err == nil {
		attemptNumber = latestAttempt + 1
	} else {
		var maxAttempt int

		maxErr := config.DB.QueryRow(
			`
			SELECT COALESCE(MAX(attempt_number), 0)
			FROM volunteer_quiz_results
			WHERE volunteer_id = ?
			AND training_id = ?
			`,
			volunteerID,
			trainingID,
		).Scan(&maxAttempt)

		if maxErr != nil {
			trainingJSON(
				w,
				http.StatusInternalServerError,
				map[string]interface{}{
					"success": false,
					"message": "ตรวจสอบจำนวนครั้งที่สอบไม่สำเร็จ: " + maxErr.Error(),
				},
			)
			return
		}

		attemptNumber = maxAttempt + 1
	}

	// ==========================================================
	// FAILED
	// ==========================================================

	if !passed {
		result, err := config.DB.Exec(
			`
			INSERT INTO volunteer_quiz_results
			(
				volunteer_id,
				training_id,
				score,
				total_questions,
				is_passed,
				approval_status,
				approved_at,
				approved_by,
				attempt_number,
				completed_at
			)
			VALUES
			(
				?,
				?,
				?,
				?,
				0,
				'rejected',
				NULL,
				NULL,
				?,
				NOW()
			)
			`,
			volunteerID,
			trainingID,
			body.Score,
			totalQuestions,
			attemptNumber,
		)

		if err != nil {
			trainingJSON(
				w,
				http.StatusInternalServerError,
				map[string]interface{}{
					"success": false,
					"message": "บันทึกผลสอบไม่สำเร็จ: " + err.Error(),
				},
			)
			return
		}

		resultID, _ := result.LastInsertId()

		trainingJSON(
			w,
			http.StatusOK,
			map[string]interface{}{
				"success":      true,
				"passed":       false,
				"status":       "rejected",
				"result_id":    resultID,
				"volunteer_id": volunteerID,
				"training_id":  trainingID,
				"score":        body.Score,
				"total":        totalQuestions,
				"percent":      percent,
				"message":      "ยังไม่ผ่านเกณฑ์ 70%",
			},
		)
		return
	}

	// ==========================================================
	// PASSED
	//
	// สอบผ่าน แต่ยังไม่ถือว่าผ่านหลักสูตร
	// จนกว่า Admin จะ approve
	// ==========================================================

	result, err := config.DB.Exec(
		`
		INSERT INTO volunteer_quiz_results
		(
			volunteer_id,
			training_id,
			score,
			total_questions,
			is_passed,
			approval_status,
			approved_at,
			approved_by,
			attempt_number,
			completed_at
		)
		VALUES
		(
			?,
			?,
			?,
			?,
			1,
			'pending',
			NULL,
			NULL,
			?,
			NOW()
		)
		`,
		volunteerID,
		trainingID,
		body.Score,
		totalQuestions,
		attemptNumber,
	)

	if err != nil {
		trainingJSON(
			w,
			http.StatusInternalServerError,
			map[string]interface{}{
				"success": false,
				"message": "บันทึกผลสอบไม่สำเร็จ: " + err.Error(),
			},
		)
		return
	}

	resultID, _ := result.LastInsertId()

	trainingJSON(
		w,
		http.StatusOK,
		map[string]interface{}{
			"success":      true,
			"passed":       true,
			"status":       "pending",
			"result_id":    resultID,
			"volunteer_id": volunteerID,
			"training_id":  trainingID,
			"score":        body.Score,
			"total":        totalQuestions,
			"percent":      percent,
			"message":      "สอบผ่านแล้ว รอแอดมินอนุมัติ",
		},
	)
}

// ============================================================
// ADMIN GET PENDING TRAINING
//
// GET
// /api/admin/volunteer-training/pending
//
// ============================================================

func AdminGetPendingVolunteerTraining(
	w http.ResponseWriter,
	r *http.Request,
) {
	if r.Method != http.MethodGet {
		trainingJSON(
			w,
			http.StatusMethodNotAllowed,
			map[string]interface{}{
				"success": false,
				"message": "Method not allowed",
			},
		)
		return
	}

	rows, err := config.DB.Query(
		`
		SELECT
			q.result_id,
			q.volunteer_id,
			q.training_id,

			t.title,

			q.score,
			q.total_questions,

			CASE
				WHEN q.total_questions > 0
				THEN (q.score / q.total_questions) * 100
				ELSE 0
			END AS score_percent,

			q.approval_status,
			q.completed_at

		FROM volunteer_quiz_results q

		INNER JOIN volunteer_training t
			ON q.training_id = t.training_id

		WHERE q.approval_status = 'pending'
		AND q.is_passed = 1
		AND t.is_active = 1
		AND t.training_id IN (1, 2, 3)

		ORDER BY q.completed_at ASC, q.result_id ASC
		`,
	)

	if err != nil {
		trainingJSON(
			w,
			http.StatusInternalServerError,
			map[string]interface{}{
				"success": false,
				"message": "โหลดรายการรออนุมัติไม่สำเร็จ: " + err.Error(),
			},
		)
		return
	}

	defer rows.Close()

	results := make([]map[string]interface{}, 0)

	for rows.Next() {
		var (
			resultID       int
			volunteerID    int
			trainingID     int
			title          string
			score          int
			totalQuestions int
			scorePercent   float64
			status         string
			completedAt    interface{}
		)

		err := rows.Scan(
			&resultID,
			&volunteerID,
			&trainingID,
			&title,
			&score,
			&totalQuestions,
			&scorePercent,
			&status,
			&completedAt,
		)

		if err != nil {
			trainingJSON(
				w,
				http.StatusInternalServerError,
				map[string]interface{}{
					"success": false,
					"message": "อ่านรายการรออนุมัติไม่สำเร็จ: " + err.Error(),
				},
			)
			return
		}

		results = append(
			results,
			map[string]interface{}{
				"result_id": resultID,

				"volunteer_id": volunteerID,

				"training_id": trainingID,
				"course_id":   trainingID,

				"course_name": title,
				"title":       title,

				"score":           score,
				"total_questions": totalQuestions,
				"score_percent":   scorePercent,

				"status": status,

				"submitted_at": completedAt,
				"completed_at": completedAt,
			},
		)
	}

	if err := rows.Err(); err != nil {
		trainingJSON(
			w,
			http.StatusInternalServerError,
			map[string]interface{}{
				"success": false,
				"message": err.Error(),
			},
		)
		return
	}

	trainingJSON(
		w,
		http.StatusOK,
		map[string]interface{}{
			"success": true,
			"count":   len(results),
			"items":   results,
		},
	)
}

// ============================================================
// ADMIN APPROVE TRAINING
//
// POST
// /api/admin/volunteer-training/approve
//
// รองรับ:
//
// {
//   "result_id": 1,
//   "admin_id": 1
// }
//
// หรือของระบบเก่า:
//
// {
//   "training_id": 1,
//   "admin_id": 1
// }
//
// ============================================================

func AdminApproveVolunteerTraining(
	w http.ResponseWriter,
	r *http.Request,
) {
	if r.Method != http.MethodPost {
		trainingJSON(
			w,
			http.StatusMethodNotAllowed,
			map[string]interface{}{
				"success": false,
				"message": "Method not allowed",
			},
		)
		return
	}

	var body struct {
		ResultID   int `json:"result_id"`
		TrainingID int `json:"training_id"`
		AdminID    int `json:"admin_id"`
	}

	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "Invalid JSON",
			},
		)
		return
	}

	// ==========================================================
	// ถ้ามี result_id ให้ใช้ result_id
	// ถ้าไม่มี ให้ใช้ training_id หา pending ล่าสุด
	// ==========================================================

	resultID := body.ResultID

	if resultID <= 0 && body.TrainingID > 0 {
		err := config.DB.QueryRow(
			`
			SELECT result_id
			FROM volunteer_quiz_results
			WHERE training_id = ?
			AND approval_status = 'pending'
			ORDER BY completed_at ASC, result_id ASC
			LIMIT 1
			`,
			body.TrainingID,
		).Scan(&resultID)

		if err != nil {
			trainingJSON(
				w,
				http.StatusNotFound,
				map[string]interface{}{
					"success": false,
					"message": "ไม่พบผลสอบที่รออนุมัติ",
				},
			)
			return
		}
	}

	if resultID <= 0 {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "กรุณาระบุ result_id หรือ training_id",
			},
		)
		return
	}

	// ==========================================================
	// APPROVE RESULT
	// ==========================================================

	result, err := config.DB.Exec(
		`
		UPDATE volunteer_quiz_results

		SET
			approval_status = 'approved',
			approved_at = NOW(),
			approved_by = ?,
			is_passed = 1

		WHERE result_id = ?
		AND approval_status = 'pending'
		`,
		body.AdminID,
		resultID,
	)

	if err != nil {
		trainingJSON(
			w,
			http.StatusInternalServerError,
			map[string]interface{}{
				"success": false,
				"message": "อนุมัติหลักสูตรไม่สำเร็จ: " + err.Error(),
			},
		)
		return
	}

	affected, _ := result.RowsAffected()

	if affected == 0 {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "ไม่พบรายการ หรือรายการถูกอนุมัติแล้ว",
			},
		)
		return
	}

	// ==========================================================
	// RESPONSE
	// ==========================================================

	trainingJSON(
		w,
		http.StatusOK,
		map[string]interface{}{
			"success":   true,
			"status":    "approved",
			"result_id": resultID,
			"message":   "อนุมัติหลักสูตรเรียบร้อยแล้ว",
		},
	)
}

// ============================================================
// ADMIN REJECT TRAINING
//
// POST
// /api/admin/volunteer-training/reject
//
// รองรับ result_id และ training_id
//
// ============================================================

func AdminRejectVolunteerTraining(
	w http.ResponseWriter,
	r *http.Request,
) {
	if r.Method != http.MethodPost {
		trainingJSON(
			w,
			http.StatusMethodNotAllowed,
			map[string]interface{}{
				"success": false,
				"message": "Method not allowed",
			},
		)
		return
	}

	var body struct {
		ResultID   int `json:"result_id"`
		TrainingID int `json:"training_id"`
	}

	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "Invalid JSON",
			},
		)
		return
	}

	resultID := body.ResultID

	if resultID <= 0 && body.TrainingID > 0 {
		err := config.DB.QueryRow(
			`
			SELECT result_id
			FROM volunteer_quiz_results
			WHERE training_id = ?
			AND approval_status = 'pending'
			ORDER BY completed_at ASC, result_id ASC
			LIMIT 1
			`,
			body.TrainingID,
		).Scan(&resultID)

		if err != nil {
			trainingJSON(
				w,
				http.StatusNotFound,
				map[string]interface{}{
					"success": false,
					"message": "ไม่พบผลสอบที่รออนุมัติ",
				},
			)
			return
		}
	}

	if resultID <= 0 {
		trainingJSON(
			w,
			http.StatusBadRequest,
			map[string]interface{}{
				"success": false,
				"message": "กรุณาระบุ result_id หรือ training_id",
			},
		)
		return
	}

	// ==========================================================
	// REJECT
	// ==========================================================

	result, err := config.DB.Exec(
		`
		UPDATE volunteer_quiz_results

		SET
			approval_status = 'rejected',
			approved_at = NULL,
			approved_by = NULL

		WHERE result_id = ?
		AND approval_status = 'pending'
		`,
		resultID,
	)

	if err != nil {
		trainingJSON(
			w,
			http.StatusInternalServerError,
			map[string]interface{}{
				"success": false,
				"message": "ปฏิเสธหลักสูตรไม่สำเร็จ: " + err.Error(),
			},
		)
		return
	}

	affected, _ := result.RowsAffected()

	if affected == 0 {
		trainingJSON(
			w,
			http.StatusNotFound,
			map[string]interface{}{
				"success": false,
				"message": "ไม่พบรายการ หรือรายการไม่ได้อยู่ในสถานะรออนุมัติ",
			},
		)
		return
	}

	trainingJSON(
		w,
		http.StatusOK,
		map[string]interface{}{
			"success":   true,
			"status":    "rejected",
			"result_id": resultID,
			"message":   "ปฏิเสธหลักสูตรแล้ว",
		},
	)
}

// ============================================================
// DEBUG ROUTE
// ============================================================

func VolunteerTrainingDebug(
	w http.ResponseWriter,
	r *http.Request,
) {
	path := strings.TrimSpace(r.URL.Path)

	trainingJSON(
		w,
		http.StatusOK,
		map[string]interface{}{
			"success": true,
			"path":    path,
		},
	)
}
