<?php

namespace App\Models;

/**
 * See CreateRolePermissionsTable's doc comment for exactly what this
 * does and doesn't control (nav visibility within a role's already
 * server-permitted set of modules — not a second access-control layer).
 */
class RolePermissionModel extends TenantModel
{
    protected $table            = 'role_permissions';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = ['role', 'module_key', 'allowed'];

    /**
     * @return array<string, bool> module_key => allowed, for every row
     *                              explicitly stored for this role
     */
    public function forRole(string $role): array
    {
        $rows = $this->where('role', $role)->findAll();
        $out  = [];

        foreach ($rows as $row) {
            $out[$row->module_key] = (bool) $row->allowed;
        }

        return $out;
    }

    /**
     * No stored row = visible (the default before this table existed —
     * see the migration's doc comment for why absence isn't "denied").
     */
    public function isAllowed(string $role, string $moduleKey): bool
    {
        $row = $this->where('role', $role)->where('module_key', $moduleKey)->first();

        return $row === null ? true : (bool) $row->allowed;
    }

    /**
     * Replaces every row for this role in one go — simpler and just as
     * correct as diffing against what's already stored, since the
     * settings form always submits the full set of checkboxes for the
     * role being edited.
     */
    public function saveForRole(string $role, array $moduleAllowed): void
    {
        $this->db->table('role_permissions')->where('role', $role)->delete();

        $rows = [];

        foreach ($moduleAllowed as $moduleKey => $allowed) {
            $rows[] = [
                'role'       => $role,
                'module_key' => $moduleKey,
                'allowed'    => $allowed ? 1 : 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
        }

        if ($rows !== []) {
            $this->insertBatch($rows);
        }
    }
}
