/* ============================================================
   MASTERCLASS -> LEOTRIX RESULTS MIGRATION
   Source:
       easyyket_leotrixgreatstrides.mastercalss

   Destination:
       easyyket_leotrixgreatstrides

   SCORE MAPPING
       mastercalss.code       -> results.ca2
       mastercalss.weeklytest -> results.st1
       mastercalss.cod        -> results.st2
       mastercalss.ex         -> results.exam
       mastercalss.tot        -> results.total

   STUDENT MAPPING
       mastercalss.REGNO      -> students.id

   SESSION
       2025/2026 - 3rd Term = session_id 3
   ============================================================ */

USE `easyyket_leotrixgreatstrides`;

SET @session_id := 3;


/* ============================================================
   1. FIX GRADE 5 NAME
   GRADE5RED -> GRADE5JADE

   If GRADE5RED already exists, rename it.
   If neither exists, create GRADE5JADE.
   ============================================================ */

UPDATE `classes` AS red
LEFT JOIN `classes` AS jade
    ON UPPER(REPLACE(TRIM(jade.`class_name`), ' ', '')) = 'GRADE5JADE'
SET
    red.`class_name` = 'GRADE5JADE',
    red.`section_id` = 8,
    red.`section` = 'primary'
WHERE
    UPPER(REPLACE(TRIM(red.`class_name`), ' ', '')) = 'GRADE5RED'
    AND jade.`id` IS NULL;


/* Create Grade 5 Jade if it does not exist at all */
INSERT INTO `classes`
(
    `section_id`,
    `class_name`,
    `section`,
    `class_teacher_id`
)
SELECT
    8,
    'GRADE5JADE',
    'primary',
    NULL
FROM DUAL
WHERE NOT EXISTS
(
    SELECT 1
    FROM `classes`
    WHERE UPPER(REPLACE(TRIM(`class_name`), ' ', '')) = 'GRADE5JADE'
);


/* ============================================================
   2. PREFLIGHT CHECK
   RUN THIS AND LOOK AT THE RESULT BEFORE THE MAIN IMPORT.

   It shows:
       STUDENT MISSING
       CLASS MISSING
       CLASS MISMATCH

   Only correctly matched students will be imported later.
   ============================================================ */

SELECT DISTINCT
    mc.`REGNO` AS old_regno,
    NULLIF(TRIM(mc.`Name`), '') AS old_student_name,
    st.`full_name` AS new_student_name,

    TRIM(mc.`class`) AS old_class,
    c.`class_name` AS matched_class,

    st.`class_id` AS student_current_class_id,
    c.`id` AS source_class_id,

    CASE
        WHEN st.`id` IS NULL THEN 'STUDENT MISSING'
        WHEN c.`id` IS NULL THEN 'CLASS MISSING'
        WHEN st.`class_id` <> c.`id` THEN 'CLASS MISMATCH'
        ELSE 'OK'
    END AS match_status

FROM `easyyket_leotrixgreatstrides`.`mastercalss` mc

LEFT JOIN `students` st
    ON st.`id` = mc.`REGNO`

LEFT JOIN `classes` c
    ON UPPER(REPLACE(TRIM(c.`class_name`), ' ', ''))
     = UPPER(REPLACE(TRIM(mc.`class`), ' ', ''))

WHERE
    mc.`REGNO` <> 0

    AND
    (
        st.`id` IS NULL
        OR c.`id` IS NULL
        OR st.`class_id` <> c.`id`
    )

ORDER BY
    mc.`REGNO`;


/* ============================================================
   3. INSERT SUBJECTS

   Each distinct subject is created for its proper class
   and session.

   IMPORTANT:
   mastercalss.code IS A SCORE.
   IT IS NOT subject_code.

   Therefore subject_code is left NULL.
   ============================================================ */

INSERT INTO `subjects`
(
    `class`,
    `class_id`,
    `subject_name`,
    `subject_code`,
    `teacher`,
    `teacher_id`,
    `credit_hours`,
    `is_compulsory`,
    `description`,
    `academic_session_id`,
    `status`,
    `assoc_teacher`,
    `grade_type`,
    `play_class_category`
)

SELECT DISTINCT

    c.`class_name`,
    c.`id`,
    TRIM(mc.`Subjects`),

    NULL,                           /* subject_code */
    NULL,                           /* teacher */
    NULL,                           /* teacher_id */
    1.0,                            /* credit_hours */
    1,                              /* compulsory */

    'Migrated from mastercalss',

    @session_id,
    1,                              /* active */
    '',                             /* assoc_teacher */
    'letters',
    NULL

FROM `easyyket_leotrixgreatstrides`.`mastercalss` mc

INNER JOIN `classes` c
    ON UPPER(REPLACE(TRIM(c.`class_name`), ' ', ''))
     = UPPER(REPLACE(TRIM(mc.`class`), ' ', ''))

WHERE
    mc.`REGNO` <> 0

    AND TRIM(mc.`Subjects`) <> ''

    AND UPPER(TRIM(mc.`Subjects`)) <> 'SUBJECTS'

    /* Do not create the same subject again */
    AND NOT EXISTS
    (
        SELECT 1
        FROM `subjects` s

        WHERE
            s.`class_id` = c.`id`

            AND s.`academic_session_id` = @session_id

            AND UPPER(TRIM(s.`subject_name`))
              = UPPER(TRIM(mc.`Subjects`))
    );


/* ============================================================
   4. PREVIEW HOW MANY RESULT ROWS CAN ACTUALLY MATCH
   ============================================================ */

SELECT
    c.`class_name`,
    COUNT(*) AS result_rows_ready,
    COUNT(DISTINCT st.`id`) AS matched_students

FROM `easyyket_leotrixgreatstrides`.`mastercalss` mc

INNER JOIN `classes` c
    ON UPPER(REPLACE(TRIM(c.`class_name`), ' ', ''))
     = UPPER(REPLACE(TRIM(mc.`class`), ' ', ''))

INNER JOIN `students` st
    ON st.`id` = mc.`REGNO`
    AND st.`class_id` = c.`id`

WHERE
    mc.`REGNO` <> 0

    /* Only rows containing an actual mark */
    AND
    (
        TRIM(mc.`code`) REGEXP '^[0-9]+([.][0-9]+)?$'
        OR TRIM(mc.`weeklytest`) REGEXP '^[0-9]+([.][0-9]+)?$'
        OR TRIM(mc.`cod`) REGEXP '^[0-9]+([.][0-9]+)?$'
        OR TRIM(mc.`ex`) REGEXP '^[0-9]+([.][0-9]+)?$'
        OR mc.`tot` <> 0
    )

GROUP BY
    c.`id`,
    c.`class_name`

ORDER BY
    c.`id`;


/* ============================================================
   5. INSERT THE RESULTS
   ============================================================ */

INSERT INTO `results`
(
    `student_id`,
    `class_id`,
    `session_id`,
    `subject_id`,
    `subject_name`,

    `ca2`,
    `st1`,
    `st2`,
    `exam`,
    `total`
)

SELECT

    st.`id` AS student_id,
    c.`id` AS class_id,
    @session_id AS session_id,
    sub.`id` AS subject_id,
    sub.`subject_name`,

    /* -------------------------------
       code -> ca2
       ------------------------------- */
    CASE
        WHEN TRIM(mc.`code`)
             REGEXP '^[0-9]+([.][0-9]+)?$'
        THEN CAST(TRIM(mc.`code`) AS DECIMAL(5,2))
        ELSE 0
    END AS ca2,


    /* -------------------------------
       weeklytest -> st1
       ------------------------------- */
    CASE
        WHEN TRIM(mc.`weeklytest`)
             REGEXP '^[0-9]+([.][0-9]+)?$'
        THEN CAST(TRIM(mc.`weeklytest`) AS DECIMAL(5,2))
        ELSE 0
    END AS st1,


    /* -------------------------------
       cod -> st2
       Handles values such as '-'
       by converting them to 0.
       ------------------------------- */
    CASE
        WHEN TRIM(mc.`cod`)
             REGEXP '^[0-9]+([.][0-9]+)?$'
        THEN CAST(TRIM(mc.`cod`) AS DECIMAL(5,2))
        ELSE 0
    END AS st2,


    /* -------------------------------
       ex -> exam
       ------------------------------- */
    CASE
        WHEN TRIM(mc.`ex`)
             REGEXP '^[0-9]+([.][0-9]+)?$'
        THEN CAST(TRIM(mc.`ex`) AS DECIMAL(5,2))
        ELSE 0
    END AS exam,


    /* -------------------------------
       tot -> total
       ------------------------------- */
    CAST(mc.`tot` AS DECIMAL(5,2)) AS total


FROM `easyyket_leotrixgreatstrides`.`mastercalss` mc


/* Match OLD REGNO directly with NEW students.id */
INNER JOIN `students` st
    ON st.`id` = mc.`REGNO`


/* Match the student's old class */
INNER JOIN `classes` c
    ON UPPER(REPLACE(TRIM(c.`class_name`), ' ', ''))
     = UPPER(REPLACE(TRIM(mc.`class`), ' ', ''))

    /* Very important safety check:
       student must actually belong to that class */
    AND st.`class_id` = c.`id`


/* Match the subject we inserted above.

   MIN(id) protects against accidental duplicate subjects
   already existing in subjects table.
*/
INNER JOIN `subjects` sub
    ON sub.`id` =
    (
        SELECT MIN(s2.`id`)

        FROM `subjects` s2

        WHERE
            s2.`class_id` = c.`id`

            AND s2.`academic_session_id` = @session_id

            AND UPPER(TRIM(s2.`subject_name`))
              = UPPER(TRIM(mc.`Subjects`))
    )


WHERE
    mc.`REGNO` <> 0

    AND TRIM(mc.`Subjects`) <> ''

    /* Do not turn completely empty result rows into zero scores */
    AND
    (
        TRIM(mc.`code`) REGEXP '^[0-9]+([.][0-9]+)?$'
        OR TRIM(mc.`weeklytest`) REGEXP '^[0-9]+([.][0-9]+)?$'
        OR TRIM(mc.`cod`) REGEXP '^[0-9]+([.][0-9]+)?$'
        OR TRIM(mc.`ex`) REGEXP '^[0-9]+([.][0-9]+)?$'
        OR mc.`tot` <> 0
    )

    /* Make the import safe to run again.
       Don't insert an existing result twice.
    */
    AND NOT EXISTS
    (
        SELECT 1

        FROM `results` old_result

        WHERE
            old_result.`student_id` = st.`id`

            AND old_result.`class_id` = c.`id`

            AND old_result.`session_id` = @session_id

            AND old_result.`subject_id` = sub.`id`
    );


/* ============================================================
   6. VERIFY THE IMPORT
   ============================================================ */

SELECT
    c.`class_name`,
    COUNT(DISTINCT s.`id`) AS number_of_subjects

FROM `subjects` s

INNER JOIN `classes` c
    ON c.`id` = s.`class_id`

WHERE
    s.`academic_session_id` = @session_id

GROUP BY
    c.`id`,
    c.`class_name`

ORDER BY
    c.`id`;


/* Result totals per class */
SELECT
    c.`class_name`,
    COUNT(*) AS result_rows,
    COUNT(DISTINCT r.`student_id`) AS students_with_results,
    COUNT(DISTINCT r.`subject_id`) AS subjects_with_results

FROM `results` r

INNER JOIN `classes` c
    ON c.`id` = r.`class_id`

WHERE
    r.`session_id` = @session_id

GROUP BY
    c.`id`,
    c.`class_name`

ORDER BY
    c.`id`;


/* ============================================================
   7. CHECK A STUDENT'S RESULTS
   Example: student ID / old REGNO 114
   ============================================================ */

SELECT
    st.`id` AS student_id,
    st.`full_name`,
    c.`class_name`,
    sub.`subject_name`,
    r.`ca2`,
    r.`st1`,
    r.`st2`,
    r.`exam`,
    r.`total`

FROM `results` r

INNER JOIN `students` st
    ON st.`id` = r.`student_id`

INNER JOIN `classes` c
    ON c.`id` = r.`class_id`

INNER JOIN `subjects` sub
    ON sub.`id` = r.`subject_id`

WHERE
    r.`session_id` = @session_id

    AND st.`id` = 114

ORDER BY
    sub.`subject_name`;