<?php
require_once __DIR__ . '/../includes/db.php';

try {
    echo "Registering new system modules...\n";
    $modules = [
        ['attendance', 'Attendance', 'Employee clock-in, clock-out and tracking'],
        ['leaves', 'Leaves', 'Employee leave requests, approvals and quotas'],
        ['payroll', 'Payroll', 'Employee salary and payroll management']
    ];

    foreach ($modules as $m) {
        $exists = fetch("SELECT id FROM system_modules WHERE module_key = ?", [$m[0]]);
        if (!$exists) {
            query("INSERT INTO system_modules (module_key, name, description, is_active) VALUES (?, ?, ?, 1)", [$m[0], $m[1], $m[2]]);
            echo "Registered module: {$m[1]}\n";
        } else {
            echo "Module {$m[1]} already registered.\n";
        }
    }

    // Enable for Company 1
    $company = fetch("SELECT enabled_modules FROM companies WHERE id = 1");
    if ($company) {
        $enabled = json_decode($company['enabled_modules'], true) ?: [];
        $updated = false;
        foreach (['attendance', 'leaves', 'payroll'] as $key) {
            if (!in_array($key, $enabled)) {
                $enabled[] = $key;
                $updated = true;
            }
        }
        if ($updated) {
            query("UPDATE companies SET enabled_modules = ? WHERE id = 1", [json_encode($enabled)]);
            echo "Enabled modules for Company 1.\n";
        } else {
            echo "Modules already enabled for Company 1.\n";
        }
    }
    
    // Clear and reload session cache in CLI is not needed, but nice to know
    echo "Module registration complete.\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
