<?php
/**
 * EduTrack Module Definitions
 * Single source of truth for all module access control.
 *
 * ORDERING RULE: core modules MUST all appear before growth modules,
 * which must all appear before premium-only modules. buildSidebar()
 * and upgrade.php both rely on sequential section ordering to insert
 * section dividers correctly.
 *
 * Plan breakdown:
 *   Starter  (GHS 150/mo, 200 students)   — 13 core modules
 *   Growth   (GHS 250/mo, 500 students)   — Starter + 5 addon modules
 *   Premium  (GHS 400/mo, unlimited)      — Growth + 2 AI modules
 */
if (defined('EDUTRACK_MODULES')) return;

// ── Role-Based Access Control ─────────────────────────────────────────────
// 'all' = full access. Array = whitelist of module keys.
if (!defined('ROLE_ACCESS')) {
    define('ROLE_ACCESS', [
        'admin'       => 'all',
        'headteacher' => ['dashboard','students','classes','attendance','subjects',
                          'fees','expenses','finance_suite','reports','terminal_reports','progress_analytics','exams',
                          'timetable','staff','alerts','communication','whatsapp_comms','student_activities','health_records','payroll','biometric_attendance',
                          'parent_accounts','user_management','ai_agent','ai_analytics'],
        'supervisor'  => ['dashboard','students','classes','attendance','subjects',
                          'fees','expenses','finance_suite','reports','terminal_reports','progress_analytics','exams',
                          'timetable','staff','alerts','communication','whatsapp_comms','student_activities','health_records','payroll','biometric_attendance',
                          'parent_accounts','user_management','ai_agent','ai_analytics'],
        'director'    => ['dashboard','students','classes','attendance','subjects',
                          'fees','expenses','finance_suite','reports','terminal_reports','progress_analytics','exams',
                          'timetable','staff','alerts','communication','whatsapp_comms','student_activities','health_records','payroll','biometric_attendance',
                          'parent_accounts','user_management','ai_agent','ai_analytics'],
        'accountant'  => ['dashboard','fees','expenses','finance_suite','payroll','reports','online_payments','ai_agent','ai_analytics'],
        'cashier'     => ['dashboard','fees','expenses','finance_suite','reports','online_payments','ai_agent','ai_analytics'],
        'registrar'   => ['dashboard','students','staff','parent_accounts','student_activities','health_records'],
        'tutor'       => ['dashboard','attendance','terminal_reports','progress_analytics','exams','timetable','student_activities'],
        'nurse'       => ['dashboard','students','health_records'],
    ]);
}

// ── Sidebar grouping ──────────────────────────────────────────────────────
// Collapsible sidebar sections, in display order. buildSidebar() renders each
// group as an expandable block; 'overview' is special-cased to render flat.
if (!defined('SIDEBAR_GROUPS')) {
    define('SIDEBAR_GROUPS', [
        'overview'   => ['label' => 'Overview',           'icon' => 'fa-gauge-high'],
        'academics'  => ['label' => 'Academics',          'icon' => 'fa-graduation-cap'],
        'attendance' => ['label' => 'Attendance',         'icon' => 'fa-user-clock'],
        'finance'    => ['label' => 'Finance',            'icon' => 'fa-sack-dollar'],
        'welfare'    => ['label' => 'Students & Welfare',  'icon' => 'fa-hand-holding-heart'],
        'operations' => ['label' => 'Operations',         'icon' => 'fa-gears'],
        'comms'      => ['label' => 'Communication',       'icon' => 'fa-comments'],
        'ai'         => ['label' => 'AI Suite',            'icon' => 'fa-robot'],
        'admin'      => ['label' => 'Administration',      'icon' => 'fa-user-shield'],
    ]);
}

// Maps each module key to a sidebar group. Modules not listed fall back to 'admin'.
if (!defined('MODULE_GROUPS')) {
    define('MODULE_GROUPS', [
        'dashboard'            => 'overview',
        // Academics
        'students'             => 'academics',
        'classes'              => 'academics',
        'subjects'             => 'academics',
        'terminal_reports'     => 'academics',
        'progress_analytics'   => 'academics',
        'exams'                => 'academics',
        'timetable'            => 'academics',
        // Attendance
        'attendance'           => 'attendance',
        'biometric_attendance' => 'attendance',
        // Finance
        'fees'                 => 'finance',
        'online_payments'      => 'finance',
        'expenses'             => 'finance',
        'reports'              => 'finance',
        'finance_suite'        => 'finance',
        'payroll'              => 'finance',
        // Students & Welfare
        'health_records'       => 'welfare',
        'student_activities'   => 'welfare',
        'parent_portal'        => 'welfare',
        // Operations
        'canteen_module'       => 'operations',
        'staff'                => 'operations',
        // Communication
        'alerts'               => 'comms',
        'communication'        => 'comms',
        'whatsapp_comms'       => 'comms',
        // AI Suite
        'ai_agent'             => 'ai',
        'ai_analytics'         => 'ai',
        // Administration
        'user_management'      => 'admin',
        'settings'             => 'admin',
    ]);
}

define('EDUTRACK_MODULES', [

  // ══════════════════════════════════════════════════════════════════════
  // SECTION 1 — CORE  (Starter · Growth · Premium — all plans)
  // 13 modules included in every plan at no extra cost
  // ══════════════════════════════════════════════════════════════════════

  // 1. Dashboard
  'dashboard' => [
    'label'    => 'Dashboard',
    'icon'     => 'fa-tachometer-alt',
    'path'     => 'dashboard.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> [],
  ],

  // 2. Students
  'students' => [
    'label'    => 'Students',
    'icon'     => 'fa-user-graduate',
    'path'     => 'students.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/students.php'],
  ],

  // 3. Classes
  'classes' => [
    'label'    => 'Classes',
    'icon'     => 'fa-chalkboard',
    'path'     => 'classes.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/classes.php'],
  ],

  // 4. Attendance
  'attendance' => [
    'label'    => 'Attendance',
    'icon'     => 'fa-clipboard-check',
    'path'     => 'attendance.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/attendance.php'],
  ],

  // 5. Subjects
  'subjects' => [
    'label'    => 'Subjects',
    'icon'     => 'fa-book',
    'path'     => 'subjects.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/subjects.php'],
  ],

  // 6. Fees & Payments
  'fees' => [
    'label'    => 'Fees & Payments',
    'icon'     => 'fa-money-bill-wave',
    'path'     => 'fees.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/fees.php','ajax/get_payment_details.php','ajax/get_student_payments.php'],
  ],
  
   // 6.5, Canteen
  'canteen_module' => [
    'label'    => 'Canteen Management',
    'icon'     => 'fa-bowl-food',
    'path'     => 'canteen/',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> 'canteen_module', 'addon_price' => 80,
    'core'     => false,
    'ajax_paths'=> ['ajax/canteen_confirm_by_student.php','ajax/canteen_dashboard_stats.php','ajax/canteen_express_pay.php','ajax/canteen_facial_confirm.php','ajax/canteen_prefetch.php','ajax/canteen_scanner_logout.php','ajax/canteen_settings_save.php','ajax/canteen_facial_enroll.php','ajax/canteen_identity_validate.php','ajax/canteen_manual_override.php','ajax/canteen_setup_save.php','ajax/canteen_sync.php','ajax/canteen_validate.php','ajax/canteen_student_search.php','ajax/canteen_webauthn_challenge.php','ajax/canteen_webauthn_enroll.php','ajax/canteen_webauthn_verify.php'],
  ],

  // 7. Expenses
  'expenses' => [
    'label'    => 'Expenses',
    'icon'     => 'fa-receipt',
    'path'     => 'expenses.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/expenses.php'],
  ],

  // 8. Reports
  'reports' => [
    'label'    => 'Reports',
    'icon'     => 'fa-chart-bar',
    'path'     => 'reports.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/get_online_payments.php'],
  ],

  // 9. Staff
  'staff' => [
    'label'    => 'Staff',
    'icon'     => 'fa-chalkboard-teacher',
    'path'     => 'staff.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/staff.php'],
  ],

  // 10. Alerts & SMS
  'alerts' => [
    'label'    => 'Alerts & SMS',
    'icon'     => 'fa-bell',
    'path'     => 'alerts.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/alerts.php','ajax/sms.php'],
  ],

  // 11. Communication
  'communication' => [
    'label'          => 'Communication',
    'icon'           => 'fa-comments',
    'path'           => 'communication.php',
    'plans'          => ['starter','growth','premium'],
    'addon_key'      => null, 'addon_price' => null,
    'core'           => true,
    'ajax_paths'     => ['ajax/communication.php'],
    'badge_callback' => 'getCommUnreadCount',   // sidebar live unread badge
  ],

  // 12. User Management
  'user_management' => [
    'label'    => 'User Management',
    'icon'     => 'fa-user-cog',
    'path'     => 'user_management.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> ['ajax/users.php'],
  ],

  // 13. Settings
  'settings' => [
    'label'    => 'Settings',
    'icon'     => 'fa-cog',
    'path'     => 'settings.php',
    'plans'    => ['starter','growth','premium'],
    'addon_key'=> null, 'addon_price' => null,
    'core'     => true,
    'ajax_paths'=> [],
  ],

  // ══════════════════════════════════════════════════════════════════════
  // SECTION 2 — GROWTH ADD-ONS  (Growth · Premium)
  // Available as individual add-ons (addon_price GHS/mo) or via Growth plan
  // ══════════════════════════════════════════════════════════════════════

  // 14. Terminal Reports
  'terminal_reports' => [
    'label'    => 'Terminal Reports',
    'icon'     => 'fa-file-alt',
    'path'     => 'modules/reports/index.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'terminal_reports', 'addon_price' => 100,
    'core'     => false,
    'ajax_paths'=> ['modules/reports/ajax/'],
  ],

  // 15. Progress Analytics — graphical academic-progress dashboards.
  // Pairs with Terminal Reports (same score data) hence placed next to it.
  'progress_analytics' => [
    'label'    => 'Progress Analytics',
    'icon'     => 'fa-chart-line',
    'path'     => 'analytics/progress.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'progress_analytics', 'addon_price' => 100,
    'core'     => false,
    'ajax_paths'=> ['analytics/ajax/'],
  ],

  // 16. Exams
  'exams' => [
    'label'    => 'Exams',
    'icon'     => 'fa-pencil-alt',
    'path'     => 'exams_generator/index.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'exams', 'addon_price' => 100,
    'core'     => false,
    'ajax_paths'=> ['exams_generator/ajax/'],
  ],

  // 16. Timetable
  'timetable' => [
    'label'    => 'Timetable',
    'icon'     => 'fa-calendar-alt',
    'path'     => 'modules/timetable/index.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'timetable', 'addon_price' => 100,
    'core'     => false,
    'ajax_paths'=> ['modules/timetable/ajax/'],
  ],

  // 17. Parent Accounts
  'parent_portal' => [
    'label'    => 'Parent Accounts',
    'icon'     => 'fa-users',
    'path'     => 'parent_accounts.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'parent_portal', 'addon_price' => 100,
    'core'     => false,
    'ajax_paths'=> ['parent-portal/ajax/'],
  ],

  // 18. Online Payments
  'online_payments' => [
    'label'    => 'Online Payments',
    'icon'     => 'fa-mobile-alt',
    'path'     => 'payment_checkout.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'online_payments', 'addon_price' => 100,
    'core'     => false,
    'ajax_paths'=> ['ajax/check_payment_status.php','ajax/get_online_payments.php'],
  ],

  // 19. Finance & Procurement Suite
  //     Expenditure approval workflow + receipt attachments + event/excursion accounts.
  //     Layered on core Expenses; unlocks the finance/ module.
  'finance_suite' => [
    'label'    => 'Finance & Procurement',
    'icon'     => 'fa-sack-dollar',
    'path'     => 'finance/index.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'finance_suite', 'addon_price' => 80,
    'core'     => false,
    'ajax_paths'=> ['finance/ajax/'],
  ],

  // 20. Multi-Level Academic Calendar
  //     Per-level (SHS/JHS/Primary) term dates. Configured inside Settings,
  //     so it carries hidden_nav (no separate sidebar link).
  'multi_calendar' => [
    'label'    => 'Academic Calendar (Multi-Level)',
    'icon'     => 'fa-calendar-days',
    'path'     => 'settings.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'multi_calendar', 'addon_price' => 40,
    'core'     => false,
    'hidden_nav'=> true,
    'ajax_paths'=> ['ajax/school_calendar_ajax.php'],
  ],

  // 21. WhatsApp Communications (Meta Cloud API)
  //     Parent messaging + report delivery over WhatsApp, wired into the RBC AI Agent.
  'whatsapp_comms' => [
    'label'    => 'WhatsApp',
    'icon'     => 'fa-comment-dots',
    'path'     => 'whatsapp.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'whatsapp_comms', 'addon_price' => 70,
    'core'     => false,
    'ajax_paths'=> ['ajax/whatsapp.php'],
  ],

  // 22. Student Leadership & Extracurricular History
  'student_activities' => [
    'label'    => 'Leadership & Activities',
    'icon'     => 'fa-medal',
    'path'     => 'student_activities.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'student_activities', 'addon_price' => 40,
    'core'     => false,
    'ajax_paths'=> ['ajax/student_activities.php'],
  ],

  // 23. Student Health & Medical Records (+ nurse role)
  'health_records' => [
    'label'    => 'Health Records',
    'icon'     => 'fa-heart-pulse',
    'path'     => 'health/index.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'health_records', 'addon_price' => 60,
    'core'     => false,
    'ajax_paths'=> ['ajax/health_records.php'],
  ],

  // 24. Integrated Payroll (Ghana SSNIT + PAYE)
  'payroll' => [
    'label'    => 'Payroll',
    'icon'     => 'fa-money-check-dollar',
    'path'     => 'payroll/index.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'payroll', 'addon_price' => 80,
    'core'     => false,
    'ajax_paths'=> ['payroll/ajax/'],
  ],

  // 25. Biometric Attendance (fingerprint + facial; ZKTeco push + browser kiosk)
  'biometric_attendance' => [
    'label'    => 'Biometric Attendance',
    'icon'     => 'fa-fingerprint',
    'path'     => 'biometric/index.php',
    'plans'    => ['growth','premium'],
    'addon_key'=> 'biometric_attendance', 'addon_price' => 80,
    'core'     => false,
    'ajax_paths'=> ['biometric/ajax/'],
  ],

  // ══════════════════════════════════════════════════════════════════════
  // SECTION 3 — AI & PREMIUM  (Premium only)
  // ══════════════════════════════════════════════════════════════════════

  // 19. RBC AI Agent
  'ai_agent' => [
    'label'    => 'RBC AI Agent',
    'icon'     => 'fa-brain',
    'path'     => 'ai_dashboard.php',
    'plans'    => ['premium'],
    'addon_key'=> 'ai_agent', 'addon_price' => 200,
    'core'     => false,
    'ajax_paths'=> ['ajax/ai_chat.php'],
  ],

  // 20. AI Analytics
  'ai_analytics' => [
    'label'    => 'AI Analytics',
    'icon'     => 'fa-robot',
    'path'     => 'ai_analytics.php',
    'plans'    => ['premium'],
    'addon_key'=> 'ai_analytics', 'addon_price' => 200,
    'core'     => false,
    'ajax_paths'=> ['ajax/ai_chatbot.php'],
  ],

]);

function getPlanModules(string $plan): array {
  $modules = [];
  foreach (EDUTRACK_MODULES as $key => $def) {
    if (in_array($plan, $def['plans'])) $modules[] = $key;
  }
  return $modules;
}

function getSchoolModules(string $plan, array $addons): array {
  $modules = getPlanModules($plan);
  foreach ($addons as $addon_key) {
    foreach (EDUTRACK_MODULES as $key => $def) {
      if ($def['addon_key'] === $addon_key && !in_array($key, $modules)) $modules[] = $key;
    }
  }
  return array_unique($modules);
}
