<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Controller;
use App\Core\Database;

final class AdminRbacOrgCrudController extends Controller
{
    public function index(): void
    {
        require_org_admin();
        require_org_context();

        $db=Database::getInstance();
        $orgId=(int)current_org_id();

        $st=$db->prepare("
          SELECT ou.id, ou.user_id, ou.role_code, ou.is_active, ou.created_at,
                 u.email, u.first_name, u.last_name
          FROM org_users ou
          JOIN users u ON u.id=ou.user_id
          WHERE ou.org_id=:o
          ORDER BY ou.role_code ASC, u.id DESC
          LIMIT 800
        ");
        $st->execute([':o'=>$orgId]);
        $rows=$st->fetchAll()?:[];

        $this->view('admin/rbac_crud/index',['rows'=>$rows]);
    }

    public function upsert(): void
    {
        require_org_admin();
        require_org_context();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); return; }

        $db=Database::getInstance();
        $orgId=(int)current_org_id();

        $email=trim((string)($_POST['email']??''));
        $role=trim((string)($_POST['role_code']??'author'));
        $active=(int)($_POST['is_active']??1);

        if($email===''){ header('Location: '.base_path('admin/rbac')); exit; }

        $st=$db->prepare("SELECT id FROM users WHERE email=:e LIMIT 1");
        $st->execute([':e'=>$email]);
        $uid=(int)($st->fetchColumn()?:0);

        if($uid<=0){
          if(function_exists('flash_set')) flash_set('danger','User not found');
          header('Location: '.base_path('admin/rbac')); exit;
        }

        $db->prepare("
          INSERT INTO org_users(org_id,user_id,role_code,is_active)
          VALUES(:o,:u,:r,:a)
          ON DUPLICATE KEY UPDATE role_code=VALUES(role_code), is_active=VALUES(is_active)
        ")->execute([':o'=>$orgId,':u'=>$uid,':r'=>$role,':a'=>$active]);

        if(function_exists('flash_set')) flash_set('success','Role updated');
        header('Location: '.base_path('admin/rbac')); exit;
    }

    public function deactivate(): void
    {
        require_org_admin();
        require_org_context();
        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        $id=(int)($_GET['id']??0);

        if($id>0){
          $db->prepare("UPDATE org_users SET is_active=0 WHERE id=:id AND org_id=:o")->execute([':id'=>$id,':o'=>$orgId]);
        }
        header('Location: '.base_path('admin/rbac')); exit;
    }
}
