
      declare   p_form_id INT =9;
       declare  p_academic_year VARCHAR(20)='1404-1405';
      

        SELECT
            e.id AS entry_id,

            MAX(CASE WHEN m.meta_key = '8'
                THEN TRIM(m.meta_value)
            END) AS student_name,

            sid.student_id,

            MAX(CASE WHEN m.meta_key = '11'
                THEN TRIM(m.meta_value)
            END) AS class_name,

            MAX(CASE WHEN m.meta_key = '12'
                THEN TRIM(m.meta_value)
            END) AS class_id,

            f.forms

        FROM wp_gf_entry e
        JOIN wp_gf_entry_meta m
            ON m.entry_id = e.id

        /* student_id معتبر */
        JOIN (
            SELECT
                entry_id,
                TRIM(meta_value) AS student_id
            FROM wp_gf_entry_meta
            WHERE meta_key = '10'
              AND meta_value REGEXP '^[0-9]{10}$'
        ) sid ON sid.entry_id = e.id

        /* فرم‌هایی که دانش‌آموز در آن‌ها بوده */
        LEFT JOIN (
            SELECT
                meta_value COLLATE utf8mb4_unicode_520_ci AS student_id,
                GROUP_CONCAT(DISTINCT form_id ORDER BY form_id) AS forms
            FROM wp_gf_entry_meta
            WHERE meta_value REGEXP '^[0-9]{10}$'
            GROUP BY meta_value COLLATE utf8mb4_unicode_520_ci
        ) f
            ON f.student_id = sid.student_id COLLATE utf8mb4_unicode_520_ci

        WHERE e.form_id = p_form_id

        /* سال تحصیلی */
        AND EXISTS (
            SELECT 1
            FROM wp_gf_entry_meta y
            WHERE y.entry_id = e.id
              AND y.meta_key = '7'
              AND TRIM(y.meta_value) COLLATE utf8mb4_unicode_520_ci
                  LIKE CONCAT(
                      '%',
                      TRIM(p_academic_year) COLLATE utf8mb4_unicode_520_ci,
                      '%'
                  )
        )

      


        /* فیلتر فرم‌ها (LIKE امن) */
        AND (
            p_forms IS NULL
            OR f.forms COLLATE utf8mb4_unicode_520_ci
                LIKE CONCAT(
                    '%',
                    TRIM(p_forms) COLLATE utf8mb4_unicode_520_ci,
                    '%'
                )
        )

        GROUP BY e.id, sid.student_id, f.forms
        ORDER BY student_name ASC;
    END;