<?php

namespace Modules\MedOrganization\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Modules\MedOrganization\Entities\OrgAccessRule;
use Yajra\DataTables\Facades\DataTables;

/**
 * ABAC rule store admin (spec §4 abac). List + activate/deactivate only —
 * rule authoring stays seeder/config-driven for now (rules are predicates
 * evaluated by Services\MedAccess, not free-form user input).
 */
class AccessRuleController extends MedOrgBaseController
{
    public function index()
    {
        $this->guard('medorg.access_rules.manage');

        if (request()->ajax()) {
            $rows = DB::table('org_access_rules as ar')
                ->leftJoin('roles as r', 'r.id', '=', 'ar.role_id')
                ->where('ar.business_id', $this->businessId())
                ->select([
                    'ar.id', 'ar.role_key', 'ar.entity', 'ar.rule_key',
                    'ar.rule_value', 'ar.effect', 'ar.is_active',
                    'r.name as role_name',
                ]);

            return DataTables::of($rows)
                ->addColumn('applies_to', fn ($r) => $r->role_name ?: ($r->role_key ?: '—'))
                ->editColumn('rule_value', function ($r) {
                    if (empty($r->rule_value)) {
                        return '—';
                    }

                    return '<code>' . e($r->rule_value) . '</code>';
                })
                ->editColumn('effect', fn ($r) => $r->effect === 'allow'
                    ? '<span class="label label-success">' . __('medorganization::lang.effect_allow') . '</span>'
                    : '<span class="label label-danger">' . __('medorganization::lang.effect_deny') . '</span>')
                ->editColumn('is_active', fn ($r) => $r->is_active
                    ? '<span class="label label-success">' . __('medorganization::lang.active') . '</span>'
                    : '<span class="label label-default">' . __('medorganization::lang.inactive') . '</span>')
                ->addColumn('action', function ($r) {
                    $label = $r->is_active
                        ? __('medorganization::lang.deactivate')
                        : __('medorganization::lang.activate');
                    $class = $r->is_active ? 'btn-warning' : 'btn-success';

                    return '<button data-href="' . route('medorg.access-rules.toggle', $r->id) . '" class="btn btn-xs ' . $class . ' medorg-post-btn"><i class="fa fa-power-off"></i> ' . $label . '</button>';
                })
                ->rawColumns(['rule_value', 'effect', 'is_active', 'action'])
                ->make(true);
        }

        return view('medorganization::access_rules.index');
    }

    /** Flip is_active on a rule. */
    public function toggle($id)
    {
        $this->guard('medorg.access_rules.manage');

        try {
            $rule = OrgAccessRule::forBusiness($this->businessId())->findOrFail($id);
            $rule->update(['is_active' => ! $rule->is_active]);

            return $this->ok(__('medorganization::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }
}
