<?php
$page_title='مشاركة الطابعات بين النسخ';$UA_FORCE_DESIGN_V2=true;$UA_PAGE_CSS=['assets/css/output_fleet.css'];
require_once __DIR__.'/auth.php';require_once __DIR__.'/db_bootstrap.php';require_once __DIR__.'/output_fleet_lib.php';require_login();if(function_exists('require_perm'))require_perm('can_settings');$conn=$GLOBALS['conn']??ensure_db(true);ua_output_fleet_migrate($conn);$err='';$msg='';$actor=(int)($_SESSION['admin_id']??0);$scopes=ua_output_fleet_consumer_scopes($conn);
if($_SERVER['REQUEST_METHOD']==='POST'){
 if(function_exists('ua_csrf_verify')&&!ua_csrf_verify())$err='انتهت صلاحية الطلب.';else{$action=(string)($_POST['action']??'');
  if($action==='save_printers'){foreach((array)($_POST['printer']??[]) as $id=>$row){$id=(int)$id;if($id<=0)continue;$status=!empty($row['approved'])?'APPROVED':'PENDING';$mode=(string)($row['share_mode']??'NONE');if(!in_array($mode,['NONE','ALL','SELECTED'],true))$mode='NONE';$stmt=$conn->prepare("UPDATE ua_output_fleet_printers SET approval_status=?,share_mode=?,approved_by=IF(?='APPROVED',?,NULL),approved_at=IF(?='APPROVED',COALESCE(approved_at,NOW()),NULL) WHERE id=?");$stmt->bind_param('sssisi',$status,$mode,$status,$actor,$status,$id);$stmt->execute();$stmt->close();$conn->query("DELETE FROM ua_output_fleet_access WHERE printer_id={$id}");if($mode==='SELECTED')foreach((array)($row['access']??[]) as $consumer=>$allowed){if(!isset($scopes[$consumer])||$consumer==='ALL')continue;$stmt=$conn->prepare("INSERT INTO ua_output_fleet_access(printer_id,consumer_scope,is_allowed,created_by) VALUES(?,?,1,?)");$stmt->bind_param('isi',$id,$consumer,$actor);$stmt->execute();$stmt->close();}}header('Location: output_fleet.php?saved=1');exit;}
  if($action==='save_nodes'){foreach((array)($_POST['node']??[]) as $id=>$row){$id=substr((string)$id,0,100);$status=!empty($row['approved'])?'APPROVED':'PENDING';$enabled=!empty($row['enabled'])?1:0;$stmt=$conn->prepare("UPDATE ua_output_nodes SET approval_status=?,is_enabled=? WHERE node_id=?");$stmt->bind_param('sis',$status,$enabled,$id);$stmt->execute();$stmt->close();}header('Location: output_fleet.php?nodes=1');exit;}
  if($action==='save_routes'){$scope=trim((string)($_POST['consumer_scope']??'ALL'))?:'ALL';foreach((array)($_POST['routes']??[]) as $command=>$row){if(!isset(ua_output_command_registry()[$command]))continue;$pid=(int)($row['printer_id']??0);$enabled=!empty($row['is_enabled'])?1:0;$paper=substr((string)($row['paper_size']??''),0,30);$copies=max(1,min(99,(int)($row['copies']??1)));if($pid<=0){$stmt=$conn->prepare("DELETE FROM ua_output_fleet_routes WHERE consumer_scope=? AND command_key=?");$stmt->bind_param('ss',$scope,$command);$stmt->execute();$stmt->close();continue;}$stmt=$conn->prepare("INSERT INTO ua_output_fleet_routes(consumer_scope,command_key,printer_id,paper_size,copies,is_enabled,updated_by) VALUES(?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE printer_id=VALUES(printer_id),paper_size=VALUES(paper_size),copies=VALUES(copies),is_enabled=VALUES(is_enabled),updated_by=VALUES(updated_by)");$stmt->bind_param('ssisiii',$scope,$command,$pid,$paper,$copies,$enabled,$actor);$stmt->execute();$stmt->close();}header('Location: output_fleet.php?routes=1&scope='.urlencode($scope));exit;}
 }}
if(isset($_GET['saved']))$msg='تم اعتماد صلاحيات مشاركة الطابعات.';if(isset($_GET['nodes']))$msg='تم اعتماد عقد الطباعة.';if(isset($_GET['routes']))$msg='تم حفظ التوجيه المركزي؛ أصبح نافذًا على النسخ المسموح لها.';
$nodes=[];$rs=$conn->query("SELECT n.*,(SELECT COUNT(*) FROM ua_output_fleet_printers p WHERE p.node_id=n.node_id AND p.is_online=1) printer_count FROM ua_output_nodes n ORDER BY n.last_seen_at DESC");while($rs&&($r=$rs->fetch_assoc()))$nodes[]=$r;$printers=ua_output_fleet_printers($conn,false);$approved=array_values(array_filter($printers,fn($p)=>$p['approval_status']==='APPROVED'&&$p['share_mode']!=='NONE'));
$scope=(string)($_GET['scope']??'ALL');if(!isset($scopes[$scope]))$scope='ALL';$savedRoutes=[];$esc=$conn->real_escape_string($scope);$rs=$conn->query("SELECT * FROM ua_output_fleet_routes WHERE consumer_scope='{$esc}'");while($rs&&($r=$rs->fetch_assoc()))$savedRoutes[$r['command_key']]=$r;$registry=array_filter(ua_output_command_registry(),fn($c)=>$c['type']==='printer');$accessMap=[];$rs=$conn->query("SELECT printer_id,consumer_scope FROM ua_output_fleet_access WHERE is_allowed=1");while($rs&&($r=$rs->fetch_assoc()))$accessMap[(int)$r['printer_id']][(string)$r['consumer_scope']]=true;
$fleetJobs=[];$rs=$conn->query("SELECT j.id,j.command_key,j.consumer_scope,j.title,j.job_status,j.attempts,j.status_message,j.created_at,j.completed_at,p.printer_name,n.instance_name FROM ua_output_fleet_jobs j JOIN ua_output_fleet_printers p ON p.id=j.printer_id JOIN ua_output_nodes n ON n.node_id=j.node_id ORDER BY j.id DESC LIMIT 50");while($rs&&($r=$rs->fetch_assoc()))$fleetJobs[]=$r;
include __DIR__.'/header.php';include __DIR__.'/sidebar.php';?>
<div class="content-wrapper of-page" dir="rtl"><section class="content"><div class="container-fluid"><header class="of-hero"><div><small>Distributed Print Fleet</small><h1>مشاركة الطابعات بين جميع النسخ</h1><p>كل نسخة ويندوز تسجّل طابعاتها تلقائيًا. تعتمد الرئيسية الجهاز والطابعة مرة واحدة، ثم تطبع النسخ وأندرويد عبرها بلا عنوان IP أو مفتاح يدوي أو مربع حوار.</p></div><a href="output_devices.php"><i class="fa fa-random"></i> المسارات المحلية القديمة</a></header><?php if($err):?><div class="alert alert-danger"><?=h($err)?></div><?php endif;?><?php if($msg):?><div class="alert alert-success"><?=h($msg)?></div><?php endif;?>
<nav class="of-steps"><span><b>1</b> النسخ تسجل نفسها</span><i class="fa fa-angle-left"></i><span><b>2</b> الرئيسية تعتمد الطابعة</span><i class="fa fa-angle-left"></i><span><b>3</b> تعيين العمليات</span><i class="fa fa-angle-left"></i><span><b>4</b> طباعة صامتة من أي نسخة</span></nav>
<section class="of-card"><header><div><small>Print Nodes</small><h2>الأجهزة التي تحمل نسخة البرنامج</h2></div><b><?=count($nodes)?></b></header><form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field();?><input type="hidden" name="action" value="save_nodes"><div class="table-responsive"><table><thead><tr><th>الجهاز</th><th>نوع النسخة</th><th>عنوان التنفيذ</th><th>الطابعات</th><th>آخر اتصال</th><th>الاعتماد</th><th>التشغيل</th></tr></thead><tbody><?php foreach($nodes as $n):$online=strtotime($n['last_seen_at'])>=time()-180;?><tr><td><strong><?=h($n['instance_name'])?></strong><small><?=h($n['machine_name'])?></small></td><td><?=h($n['instance_type'])?></td><td dir="ltr"><?=h($n['agent_url'])?></td><td><?= (int)$n['printer_count']?></td><td><span class="of-state <?=$online?'online':'offline'?>"><?=$online?'متصل':'غير متصل'?></span><small dir="ltr"><?=h($n['last_seen_at'])?></small></td><td><input type="checkbox" name="node[<?=h($n['node_id'])?>][approved]" <?=$n['approval_status']==='APPROVED'?'checked':''?>></td><td><input type="checkbox" name="node[<?=h($n['node_id'])?>][enabled]" <?=(int)$n['is_enabled']?'checked':''?>></td></tr><?php endforeach;?><?php if(!$nodes):?><tr><td colspan="7" class="empty">ستظهر الأجهزة تلقائيًا بعد تشغيل النسخة المحدثة عليها.</td></tr><?php endif;?></tbody></table></div><footer><button><i class="fa fa-shield"></i> حفظ اعتماد الأجهزة</button></footer></form></section>
<section class="of-card"><header><div><small>Shared Printers</small><h2>الطابعات المكتشفة وصلاحية مشاركتها</h2></div><b><?=count($printers)?></b></header><form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field();?><input type="hidden" name="action" value="save_printers"><div class="table-responsive"><table><thead><tr><th>الطابعة</th><th>الجهاز المضيف</th><th>المنفذ/التعريف</th><th>الحالة</th><th>اعتماد</th><th>نطاق المشاركة</th><th>النسخ المحددة</th></tr></thead><tbody><?php foreach($printers as $p):?><tr><td><strong><?=h($p['printer_name'])?></strong><?=$p['is_default']?'<small>الافتراضية</small>':''?></td><td><?=h($p['instance_name'])?><small><?=h($p['machine_name'])?></small></td><td><?=h($p['port_name']?:'—')?><small><?=h($p['driver_name']?:'—')?></small></td><td><span class="of-state <?=(int)$p['is_online']?'online':'offline'?>"><?=(int)$p['is_online']?'متاحة':'غير متاحة'?></span></td><td><input type="checkbox" name="printer[<?=(int)$p['id']?>][approved]" <?=$p['approval_status']==='APPROVED'?'checked':''?>></td><td><select name="printer[<?=(int)$p['id']?>][share_mode]"><option value="NONE" <?=$p['share_mode']==='NONE'?'selected':''?>>غير مشتركة</option><option value="ALL" <?=$p['share_mode']==='ALL'?'selected':''?>>كل النسخ المرتبطة</option><option value="SELECTED" <?=$p['share_mode']==='SELECTED'?'selected':''?>>نسخ محددة</option></select></td><td><div class="of-access"><?php foreach($scopes as $consumer=>$label):if($consumer==='ALL')continue;?><label><input type="checkbox" name="printer[<?=(int)$p['id']?>][access][<?=h($consumer)?>]" <?=!empty($accessMap[(int)$p['id']][$consumer])?'checked':''?>> <?=h($label)?></label><?php endforeach;?></div></td></tr><?php endforeach;?><?php if(!$printers):?><tr><td colspan="7" class="empty">لا توجد طابعات مسجلة بعد.</td></tr><?php endif;?></tbody></table></div><footer><button><i class="fa fa-check"></i> حفظ صلاحيات الطابعات</button></footer></form></section>
<section class="of-card"><header><div><small>Central Routing</small><h2>تعيين الطابعة لكل عملية</h2></div><form method="get"><select name="scope" onchange="this.form.submit()"><?php foreach($scopes as $k=>$label):?><option value="<?=h($k)?>" <?=$scope===$k?'selected':''?>><?=h($label)?></option><?php endforeach;?></select></form></header><form method="post"><?php if(function_exists('ua_csrf_field'))ua_csrf_field();?><input type="hidden" name="action" value="save_routes"><input type="hidden" name="consumer_scope" value="<?=h($scope)?>"><div class="table-responsive"><table><thead><tr><th>العملية</th><th>الطابعة المشتركة</th><th>الورق</th><th>النسخ</th><th>تفعيل</th></tr></thead><tbody><?php foreach($registry as $key=>$cmd):$route=$savedRoutes[$key]??[];?><tr><td><strong><?=h($cmd['label'])?></strong><small><?=h($cmd['group'])?></small></td><td><select name="routes[<?=h($key)?>][printer_id]"><option value="0">دون تعيين مركزي</option><?php foreach($approved as $p):?><option value="<?=(int)$p['id']?>" <?=(int)($route['printer_id']??0)===(int)$p['id']?'selected':''?>><?=h($p['printer_name'].' — '.$p['instance_name'])?></option><?php endforeach;?></select></td><td><select name="routes[<?=h($key)?>][paper_size]"><?php foreach(['A4','A5','Letter','80mm','58mm'] as $paper):?><option value="<?=$paper?>" <?=($route['paper_size']??$cmd['paper'])===$paper?'selected':''?>><?=$paper?></option><?php endforeach;?></select></td><td><input type="number" min="1" max="99" name="routes[<?=h($key)?>][copies]" value="<?=max(1,(int)($route['copies']??1))?>"></td><td><input type="checkbox" name="routes[<?=h($key)?>][is_enabled]" <?=!isset($route['is_enabled'])||(int)$route['is_enabled']?'checked':''?>></td></tr><?php endforeach;?></tbody></table></div><footer><p>المسار الخاص بنسخة محددة يتقدم على مسار «جميع النسخ».</p><button><i class="fa fa-floppy-o"></i> حفظ التوجيه المركزي</button></footer></form></section>
<section class="of-card"><header><div><small>Fleet Audit</small><h2>سجل مهام الطباعة المشتركة</h2></div><b><?=count($fleetJobs)?></b></header><div class="table-responsive"><table><thead><tr><th>#</th><th>الوقت</th><th>العملية</th><th>الطابعة والجهاز</th><th>النسخة الطالبة</th><th>الحالة</th><th>التفاصيل</th></tr></thead><tbody><?php foreach($fleetJobs as $job):?><tr><td><?=(int)$job['id']?></td><td dir="ltr"><?=h($job['created_at'])?></td><td><?=h($registry[$job['command_key']]['label']??$job['command_key'])?><small><?=h($job['title']??'')?></small></td><td><?=h($job['printer_name'])?><small><?=h($job['instance_name'])?></small></td><td dir="ltr"><?=h($job['consumer_scope'])?></td><td><span class="of-state <?=in_array($job['job_status'],['COMPLETED'],true)?'online':'offline'?>"><?=h($job['job_status'])?></span></td><td><?=h($job['status_message']?:'—')?></td></tr><?php endforeach;?><?php if(!$fleetJobs):?><tr><td colspan="7" class="empty">لا توجد مهام طباعة مشتركة بعد.</td></tr><?php endif;?></tbody></table></div></section>
</div></section></div><?php include __DIR__.'/footer.php';?>
