<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('system.roles.manage');require __DIR__.'/app/layout.php';
$pdo=db();$companyId=company_id();
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$roleId=(int)($_POST['role_id']??0);$valid=(int)scalar('SELECT COUNT(*) FROM roles WHERE id=? AND company_id=?',[$roleId,$companyId]);if(!$valid)throw new RuntimeException('الدور غير صالح.');$ids=array_values(array_unique(array_map('intval',$_POST['permission_ids']??[])));$pdo->beginTransaction();$pdo->prepare('DELETE FROM role_permissions WHERE role_id=?')->execute([$roleId]);$s=$pdo->prepare('INSERT INTO role_permissions(role_id,permission_id,created_at) VALUES (?,?,NOW())');foreach($ids as $id){if($id>0)$s->execute([$roleId,$id]);}$pdo->commit();audit('role.permissions.update','role',(string)$roleId,['count'=>count($ids)]);flash('success','تم تحديث صلاحيات الدور.');}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e->getMessage());}redirect('security.php?role_id='.(int)($_POST['role_id']??0));}
$roles=$pdo->prepare('SELECT * FROM roles WHERE company_id=? AND is_active=1 ORDER BY id');$roles->execute([$companyId]);$roles=$roles->fetchAll();$roleId=(int)($_GET['role_id']??($roles[0]['id']??0));$permissions=$pdo->query('SELECT * FROM permissions ORDER BY module_code,id')->fetchAll();$assigned=[];if($roleId){$s=$pdo->prepare('SELECT permission_id FROM role_permissions WHERE role_id=?');$s->execute([$roleId]);$assigned=array_map('intval',$s->fetchAll(PDO::FETCH_COLUMN));}
$search=trim((string)($_GET['q']??''));$params=[$companyId];$sql='SELECT al.*,u.full_name FROM audit_logs al LEFT JOIN users u ON u.id=al.user_id WHERE al.company_id=?';if($search!==''){$sql.=' AND (al.event_type LIKE ? OR al.object_type LIKE ? OR al.event_description LIKE ? OR u.full_name LIKE ?)';$like='%'.$search.'%';array_push($params,$like,$like,$like,$like);}$sql.=' ORDER BY al.id DESC LIMIT 200';$s=$pdo->prepare($sql);$s->execute($params);$logs=$s->fetchAll();
render_header('security','الصلاحيات وسجل التدقيق','توزيع صلاحيات الأدوار ومراجعة العمليات الحساسة.');?>
<section class="panel form-card"><header><h2>صلاحيات الأدوار</h2></header><form method="get"><label>اختر الدور<select name="role_id" onchange="this.form.submit()"><?php foreach($roles as $r):?><option value="<?= (int)$r['id'] ?>" <?= $roleId===(int)$r['id']?'selected':'' ?>><?= e($r['name_ar']) ?></option><?php endforeach;?></select></label></form><form method="post"><?= csrf_field() ?><input type="hidden" name="role_id" value="<?= $roleId ?>"><div class="permission-grid"><?php $group='';foreach($permissions as $p):if($group!==$p['module_code']):$group=$p['module_code'];?><h3><?= e($group) ?></h3><?php endif;?><label class="checks"><span><input type="checkbox" name="permission_ids[]" value="<?= (int)$p['id'] ?>" <?= in_array((int)$p['id'],$assigned,true)?'checked':'' ?>> <?= e($p['name_ar']) ?></span></label><?php endforeach;?></div><button class="primary-btn">حفظ الصلاحيات</button></form></section>
<section class="panel data-card"><header><div><h2>سجل التدقيق</h2><p>آخر 200 عملية</p></div><a class="secondary-btn" href="<?= e(app_url('backup.php')) ?>">تنزيل نسخة SQL</a></header><form method="get"><input type="hidden" name="role_id" value="<?= $roleId ?>"><label>بحث<input name="q" value="<?= e($search) ?>" placeholder="العملية، المستخدم، نوع السجل..."></label></form><div class="responsive-table"><table><thead><tr><th>التاريخ</th><th>المستخدم</th><th>العملية</th><th>الكائن</th><th>الوصف</th><th>IP</th></tr></thead><tbody><?php foreach($logs as $l):?><tr><td><?= e($l['created_at']) ?></td><td><?= e($l['full_name']?:'النظام') ?></td><td><?= e($l['event_type']) ?></td><td><?= e($l['object_type'].' #'.($l['object_id']??'')) ?></td><td><?= e($l['event_description']) ?></td><td><?= e($l['ip_address']) ?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php render_footer();
