================================================================================
  PRIMARY GRADES (G4-G7) - COMPLETE SOLUTION
================================================================================

REQUIREMENT:
------------
"On configure_subjects.php I only see Form 1 to Form 5, no Grade 4 to 7.
Fix this. Admin should choose if primary subjects will be available or not."

SOLUTION:
---------
✓ Added Grade 4-7 to database
✓ Added toggle switch for admins to enable/disable primary grades
✓ Visual distinction between primary and secondary grades
✓ Filter subjects by grade appropriately

================================================================================
WHAT WAS IMPLEMENTED:
================================================================================

1. DATABASE: Added Primary Grades
   - Grade 4, Grade 5, Grade 6, Grade 7
   - File: database/seeds/add_primary_grades.sql

2. DATABASE: Added Primary Subjects (48 subjects)
   - Grade 4: 11 subjects
   - Grade 5: 12 subjects
   - Grade 6: 13 subjects
   - Grade 7: 12 subjects
   - File: database/seeds/primary_school_subjects_g4_g7.sql

3. ADMIN INTERFACE: Toggle Switch
   - Shows at top of configure_subjects.php
   - Admin can enable/disable primary grades
   - Setting saved per school in tenant_settings table

4. VISUAL DISTINCTION:
   - Primary grades (G4-G7): Green header, book icon, "Primary" badge
   - Secondary grades (F1-F5): Blue header, mortarboard icon, "Secondary" badge

================================================================================
HOW IT WORKS:
================================================================================

DEFAULT STATE:
--------------
- Primary grades: DISABLED (hidden)
- Only shows: Form 1, Form 2, Form 3, Form 4, Form 5
- Same as before

WHEN ADMIN ENABLES PRIMARY:
----------------------------
1. Admin clicks toggle switch
2. Setting saved to database (show_primary_grades = 1)
3. Page reloads
4. Now shows: Grade 4, Grade 5, Grade 6, Grade 7, Form 1-5
5. Admin can configure subjects for all grades

WHEN ADMIN DISABLES PRIMARY:
-----------------------------
1. Admin clicks toggle switch OFF
2. Setting saved to database (show_primary_grades = 0)
3. Page reloads
4. Only shows: Form 1, Form 2, Form 3, Form 4, Form 5
5. Primary grades hidden (but still exist in database)

================================================================================
VISUAL DESIGN:
================================================================================

TOGGLE SWITCH (At Top):
┌─────────────────────────────────────────────────────┐
│ 🎚️ Primary School Grades (Grade 4-7)                │
│                                                      │
│ Enable this to show and configure subjects for      │
│ Grade 4, 5, 6, and 7. If your school only offers   │
│ secondary education (Forms), keep this disabled.    │
│                                        [✓ Enabled]  │
└─────────────────────────────────────────────────────┘

GRADE CARDS:
┌──────────────────────┐  ┌──────────────────────┐
│ 📖 Grade 4 [Primary] │  │ 🎓 Form 1 [Secondary]│
│──────────────────────│  │──────────────────────│
│ Green header         │  │ Blue header          │
│ Select subjects...   │  │ Select subjects...   │
└──────────────────────┘  └──────────────────────┘

================================================================================
SETUP STEPS:
================================================================================

STEP 1: RUN SQL TO ADD GRADES
------------------------------

In phpMyAdmin SQL tab, run:

File: database/seeds/add_primary_grades.sql

INSERT IGNORE INTO grades (name) VALUES
('Grade 4'),
('Grade 5'),
('Grade 6'),
('Grade 7');

Result: 4 new grades added


STEP 2: RUN SQL TO ADD SUBJECTS
--------------------------------

In phpMyAdmin SQL tab, run:

File: database/seeds/primary_school_subjects_g4_g7.sql

Result: 48 new subjects added and linked to grades


STEP 3: UPLOAD UPDATED FILES TO cPANEL
---------------------------------------

Upload these files:
1. admin/configure_subjects.php (UPDATED - has toggle)
2. admin/moodle/configure_mapping.php (for mapping to Moodle)
3. admin/moodle/test_mappings.php (for testing)

Location: public_html/test.melanegroup.com/Multi-Tanent/admin/


STEP 4: TEST THE TOGGLE
------------------------

1. Login as admin
2. Go to: admin/configure_subjects.php
3. Look for toggle at top: "Primary School Grades (Grade 4-7)"
4. Toggle is OFF by default (shows Form 1-5 only)
5. Click toggle to ON
6. Page reloads showing Grade 4, 5, 6, 7, Form 1-5
7. Configure subjects for each grade


STEP 5: MAP TO MOODLE (Optional)
---------------------------------

1. Go to: admin/moodle/configure_mapping.php
2. Map each subject to its Moodle course
3. Test: admin/moodle/test_mappings.php
4. Verify all mappings are valid

================================================================================
CODE CHANGES IN configure_subjects.php:
================================================================================

CHANGE 1: Added School Context
-------------------------------
require_once '../includes/school_context.php';
$academy_reference = getCurrentSchoolReference();

WHY: To save setting per school


CHANGE 2: Added Toggle Handler
-------------------------------
if ($_POST['action'] === 'toggle_primary') {
    $show_primary = isset($_POST['show_primary_grades']) ? 1 : 0;
    
    // Save to tenant_settings
    $stmt = $pdo->prepare("
        INSERT INTO tenant_settings (academy_reference, setting_key, setting_value, updated_at)
        VALUES (?, 'show_primary_grades', ?, NOW())
        ON DUPLICATE KEY UPDATE setting_value = ?, updated_at = NOW()
    ");
    $stmt->execute([$academy_reference, $show_primary, $show_primary]);
}

WHY: Saves admin's choice to database


CHANGE 3: Load Setting
-----------------------
$stmt = $pdo->prepare("
    SELECT setting_value FROM tenant_settings 
    WHERE academy_reference = ? AND setting_key = 'show_primary_grades'
");
$stmt->execute([$academy_reference]);
$show_primary_grades = $stmt->fetchColumn() == '1';

WHY: Retrieves admin's preference


CHANGE 4: Filter Grades
------------------------
$grades = array_filter($all_grades, function($grade) use ($show_primary_grades) {
    $is_primary = preg_match('/^Grade [4-7]$/i', $grade['name']);
    
    if ($is_primary) {
        return $show_primary_grades; // Only show if enabled
    } else {
        return true; // Always show Form 1-5
    }
});

WHY: Shows/hides primary grades based on setting


CHANGE 5: Added Toggle UI
--------------------------
<!-- Primary Grades Toggle -->
<div class="card mb-4 shadow-sm">
    <form method="POST">
        <input type="hidden" name="action" value="toggle_primary">
        <div class="form-check form-switch">
            <input type="checkbox" name="show_primary_grades" 
                   <?= $show_primary_grades ? 'checked' : '' ?>
                   onchange="this.form.submit()">
            <label>Enabled/Disabled</label>
        </div>
    </form>
</div>

WHY: Provides visual toggle for admin


CHANGE 6: Visual Distinction
-----------------------------
- Primary grades: Green header, book icon, "Primary" badge
- Secondary grades: Blue header, mortarboard icon, "Secondary" badge

WHY: Easy to distinguish at a glance

================================================================================
FILES TO UPLOAD:
================================================================================

REQUIRED:
---------
1. admin/configure_subjects.php (UPDATED - has toggle and filtering)

OPTIONAL (for Moodle):
----------------------
2. admin/moodle/configure_mapping.php
3. admin/moodle/test_mappings.php
4. includes/moodle_enrollment_handler.php

SQL SCRIPTS (run in phpMyAdmin):
---------------------------------
5. database/seeds/add_primary_grades.sql
6. database/seeds/primary_school_subjects_g4_g7.sql

================================================================================
TESTING AFTER UPLOAD:
================================================================================

TEST 1: Toggle OFF (Default)
-----------------------------
1. Go to: https://test.melanegroup.com/Multi-Tanent/admin/configure_subjects.php
2. Should see:
   ✓ Toggle switch at top (OFF)
   ✓ Form 1, Form 2, Form 3, Form 4, Form 5 cards (blue)
   ✗ No Grade 4-7 visible

TEST 2: Toggle ON
-----------------
1. Click toggle switch to ON
2. Page reloads automatically
3. Should see:
   ✓ Toggle switch (ON)
   ✓ Grade 4, Grade 5, Grade 6, Grade 7 cards (green, marked "Primary")
   ✓ Form 1, Form 2, Form 3, Form 4, Form 5 cards (blue, marked "Secondary")
4. Can configure subjects for all 9 grades

TEST 3: Configure Subjects
---------------------------
1. With toggle ON, open a Grade 4 card
2. Select subjects (English, Math, Science, etc.)
3. Click "Update Subjects"
4. Should see: "Subject mappings updated successfully"
5. Grade 4 now has subjects assigned

TEST 4: Setting Persists
-------------------------
1. Enable primary grades (toggle ON)
2. Navigate away
3. Come back to configure_subjects.php
4. Toggle should still be ON
5. Grade 4-7 still visible

================================================================================
BENEFITS:
================================================================================

✓ FLEXIBLE: Schools choose primary or secondary only
✓ CLEAN UI: No clutter for secondary-only schools
✓ VISUAL: Easy to distinguish grade levels
✓ PERSISTENT: Setting saved per school
✓ MULTI-TENANT: Each school can have different setting

================================================================================
USE CASES:
================================================================================

CASE 1: Primary & Secondary School
-----------------------------------
Example: St. Mary's offers Grade 4 through Form 5

Setting: Primary grades ENABLED
Shows: All 9 grades (Grade 4-7, Form 1-5)
Benefit: Can configure all grade levels


CASE 2: Secondary School Only
------------------------------
Example: City High School offers only Form 1-5

Setting: Primary grades DISABLED (default)
Shows: Only Form 1-5
Benefit: Clean interface, no unnecessary grades


CASE 3: Primary School Only
----------------------------
Example: Junior School offers only Grade 4-7

Setting: Primary grades ENABLED
Shows: Grade 4-7, Form 1-5
Note: Admin can simply not configure Form 1-5
Better: Could add "Hide Secondary" option (future enhancement)

================================================================================
DATABASE STRUCTURE:
================================================================================

TABLE: tenant_settings
----------------------
academy_reference | setting_key          | setting_value
------------------|----------------------|--------------
KINE              | show_primary_grades  | 1 (enabled)
SCHOOL2           | show_primary_grades  | 0 (disabled)

Each school has independent setting!

================================================================================
VERIFICATION QUERIES:
================================================================================

After running SQL scripts:

1. CHECK GRADES EXIST:
   
   SELECT * FROM grades ORDER BY name;
   
   Expected: Grade 4, Grade 5, Grade 6, Grade 7, Form 1-5

2. CHECK SUBJECTS EXIST:
   
   SELECT COUNT(*) FROM subjects WHERE code LIKE 'G4-%';  -- Grade 4: 11
   SELECT COUNT(*) FROM subjects WHERE code LIKE 'G5-%';  -- Grade 5: 12
   SELECT COUNT(*) FROM subjects WHERE code LIKE 'G6-%';  -- Grade 6: 13
   SELECT COUNT(*) FROM subjects WHERE code LIKE 'G7-%';  -- Grade 7: 12

3. CHECK GRADE-SUBJECT LINKS:
   
   SELECT g.name, COUNT(gs.subject_id) as subjects
   FROM grades g
   LEFT JOIN grade_subject gs ON g.id = gs.grade_id
   WHERE g.name LIKE 'Grade%'
   GROUP BY g.name;

================================================================================
TROUBLESHOOTING:
================================================================================

ISSUE: Toggle doesn't work

SOLUTION:
- Check tenant_settings table exists
- Check academy_reference is set correctly
- Check JavaScript not disabled
- Try manual reload after toggling

ISSUE: Grade 4-7 still not showing after enabling

SOLUTION:
- Verify grades exist in database:
  SELECT * FROM grades WHERE name LIKE 'Grade%';
- If empty, run add_primary_grades.sql
- Clear browser cache
- Try incognito mode

ISSUE: Subjects not showing for Grade 4-7

SOLUTION:
- Run primary_school_subjects_g4_g7.sql
- Check grade_subject table:
  SELECT * FROM grade_subject WHERE grade_id IN 
  (SELECT id FROM grades WHERE name LIKE 'Grade%');
- If empty, re-run the linking section of SQL

================================================================================
FILES READY:
================================================================================

SQL Scripts:
1. database/seeds/add_primary_grades.sql
2. database/seeds/primary_school_subjects_g4_g7.sql

PHP Files:
3. admin/configure_subjects.php (UPDATED)
4. admin/moodle/configure_mapping.php
5. admin/moodle/test_mappings.php

Documentation:
6. PRIMARY_GRADES_TOGGLE_COMPLETE.txt (this file)
7. PRIMARY_SCHOOL_MOODLE_SETUP.md
8. MOODLE_QUICK_START.txt

================================================================================
DEPLOYMENT CHECKLIST:
================================================================================

[ ] Run SQL: add_primary_grades.sql (creates Grade 4-7)
[ ] Run SQL: primary_school_subjects_g4_g7.sql (48 subjects)
[ ] Upload: admin/configure_subjects.php
[ ] Upload: admin/moodle/ folder (if using Moodle)
[ ] Test: Login and go to configure_subjects.php
[ ] Verify: Toggle switch visible at top
[ ] Test: Toggle ON → See Grade 4-7
[ ] Test: Toggle OFF → See Form 1-5 only
[ ] Test: Configure subjects for a grade
[ ] Test: Map to Moodle (if enabled)
[ ] Test: Verify in test_mappings.php

================================================================================
EXPECTED USER EXPERIENCE:
================================================================================

ADMIN AT SECONDARY-ONLY SCHOOL:
--------------------------------
1. Logs in
2. Goes to Configure Subjects
3. Sees: Form 1, 2, 3, 4, 5 (default view)
4. Toggle is OFF
5. Configures subjects for Forms
6. Done! (No clutter from primary grades)

ADMIN AT PRIMARY & SECONDARY SCHOOL:
-------------------------------------
1. Logs in
2. Goes to Configure Subjects
3. Sees: Form 1-5 only (default)
4. Clicks toggle to ON
5. Page reloads
6. Sees: Grade 4, 5, 6, 7 (green), Form 1-5 (blue)
7. Configures subjects for all grades
8. Done!

================================================================================
SAMPLE WORKFLOW:
================================================================================

SCENARIO: Setting up new school with Primary & Secondary

STEP 1: Run SQL Scripts
------------------------
- add_primary_grades.sql → 4 grades added
- primary_school_subjects_g4_g7.sql → 48 subjects added

STEP 2: Enable Primary Grades
------------------------------
- Go to: admin/configure_subjects.php
- Toggle: Primary School Grades → ON
- Page shows all 9 grades

STEP 3: Configure Grade 7 (Example)
------------------------------------
- Click on "Grade 7" card (green)
- Select subjects:
  ☑ English Language (Grade 7)
  ☑ SiSwati Language (Grade 7)
  ☑ Mathematics (Grade 7)
  ☑ Integrated Science (Grade 7)
  ☑ Social Studies (Grade 7)
  ☑ ICT / Computer Studies (Grade 7)
- Click "Update Subjects"
- Success! Grade 7 configured

STEP 4: Map to Moodle (Optional)
---------------------------------
- Go to: admin/moodle/configure_mapping.php
- Map "English Language (Grade 7)" → Moodle "G7-ENG"
- Map "Mathematics (Grade 7)" → Moodle "G7-MATH"
- Etc.

STEP 5: Test Mappings
----------------------
- Go to: admin/moodle/test_mappings.php
- Verify all mappings show "Valid" status
- Check Moodle courses found

STEP 6: Test with Student
--------------------------
- Assign Grade 7 Math to a student
- Check student_subject table
- Check Moodle - student should be enrolled
- Success!

================================================================================
MULTI-SCHOOL SUPPORT:
================================================================================

School A (Primary & Secondary):
- Setting: show_primary_grades = 1
- Shows: Grade 4-7, Form 1-5
- 9 grades total

School B (Secondary Only):
- Setting: show_primary_grades = 0
- Shows: Form 1-5 only
- 5 grades

Each school has independent setting! ✓

================================================================================
SUMMARY:
================================================================================

BEFORE:
-------
- Only Form 1-5 visible
- No way to add primary grades
- All schools see same grades

AFTER:
------
✓ Admin can enable primary grades (Grade 4-7)
✓ Visual distinction (green vs blue)
✓ Setting saved per school
✓ 48 primary subjects available
✓ Moodle mapping support
✓ Testing interface included

READY TO DEPLOY!

1. Run 2 SQL scripts (grades + subjects)
2. Upload configure_subjects.php
3. Toggle ON to see Grade 4-7
4. Configure and enjoy!

================================================================================

Your admin can now choose to enable primary grades! 🎉

================================================================================

