<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;

class PermissionSeeder extends Seeder
{
    /**
     * module => [actions...]. Extend this array as each new module ships.
     */
    protected array $map = [
        'dashboard'   => ['view'],
        'users'       => ['view', 'create', 'edit', 'delete', 'export', 'print'],
        'roles'       => ['view', 'create', 'edit', 'delete'],
        'permissions' => ['view', 'create', 'delete'],
        'company'     => ['view', 'edit'],
        'departments' => ['view', 'create', 'edit', 'delete', 'export', 'print'],
        'employees'   => ['view', 'create', 'edit', 'delete', 'export', 'print'],
        'leave_types'     => ['view', 'create', 'edit', 'delete'],
        'leave_balances'  => ['view', 'edit'],
        'leave_requests'  => ['view', 'create', 'edit', 'delete', 'approve'],
        'leave_calendar'  => ['view'],
        'holidays'        => ['view', 'create', 'edit', 'delete'],
        'attendance'              => ['view', 'clock', 'manual', 'edit', 'delete', 'auto_punch'],
        'attendance_corrections'  => ['view', 'create', 'approve'],
        'attendance_shifts'       => ['view', 'create', 'edit', 'delete'],
        'payroll_settings'        => ['view', 'edit'],
        'payroll_salary'          => ['view', 'create', 'edit'],
        'payroll_runs'            => ['view', 'create', 'edit', 'delete', 'approve'],
        'payroll_payslips'        => ['view', 'export', 'print'],
        'payroll_reports'         => ['view'],
        'payroll_settlements'     => ['view', 'create', 'approve'],
        'document_types'          => ['view', 'create', 'edit', 'delete'],
        'employee_documents'      => ['view', 'create', 'edit', 'delete', 'download'],
        'sale'                    => ['view'],
        'sale_reports'            => ['view'],
        'contracts'               => ['view', 'create', 'edit', 'delete'],
        'scheduling'              => ['view', 'create', 'edit', 'delete'],
        'messages'                => ['view', 'send', 'manage_groups'],
        'tpin'                    => ['assign', 'clear'],
    ];

    public function run(): void
    {
        foreach ($this->map as $group => $actions) {
            foreach ($actions as $action) {
                $slug = "{$group}.{$action}";

                $existing = $this->db->table('permissions')->where('slug', $slug)->get()->getRow();
                if ($existing) {
                    continue;
                }

                $this->db->table('permissions')->insert([
                    'group'      => $group,
                    'slug'       => $slug,
                    'label'      => ucfirst($action) . ' ' . ucfirst($group),
                    'is_system'  => 1,
                    'created_at' => date('Y-m-d H:i:s'),
                ]);
            }
        }
    }
}
