<?php session_start();require_once'../config/database.php';require_once'../includes/sidebar_layout.php';require_once'../includes/site_settings.php';
if(!isset($_SESSION['user_id'])||$_SESSION['user_role']!=='admin'){header("Location: ../login.php");exit;}
$sn=get_system_name($pdo);$ur=$_SESSION['user_role'];$un=$_SESSION['user_name'];$sm='';$em='';
if($_SERVER['REQUEST_METHOD']==='POST'&&!isset($_POST['action'])){
try{$mt=$_POST['message_type'];$ti=trim($_POST['title']);$msg=trim($_POST['message']);$ia=isset($_POST['is_active'])?1:0;$do=(int)$_POST['display_order'];$ph=null;
if(isset($_FILES['photo'])&&$_FILES['photo']['error']===UPLOAD_ERR_OK){$ud='../uploads/messages/';if(!is_dir($ud))mkdir($ud,0755,true);$ex=strtolower(pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION));
if(in_array($ex,['jpg','jpeg','png','gif'])){$fn='message_'.$mt.'_'.time().'.'.$ex;if(move_uploaded_file($_FILES['photo']['tmp_name'],$ud.$fn))$ph='uploads/messages/'.$fn;else throw new Exception('ফাইল আপলোড ব্যর্থ');}else throw new Exception('শুধুমাত্র JPG, PNG, GIF');
}
if(isset($_POST['edit_id'])){$id=(int)$_POST['edit_id'];$q="UPDATE messages SET title=?,message=?,is_active=?,display_order=?";$p=[$ti,$msg,$ia,$do];if($ph){$q.=",photo=?";$p[]=$ph;}$q.=" WHERE id=?";$p[]=$id;$pdo->prepare($q)->execute($p);$sm='বার্তা আপডেট হয়েছে';}
else{$pdo->prepare("INSERT INTO messages(message_type,title,message,photo,is_active,display_order)VALUES(?,?,?,?,?,?)")->execute([$mt,$ti,$msg,$ph,$ia,$do]);$sm='বার্তা যোগ হয়েছে';}
}catch(Exception$e){$em=$e->getMessage();}}
if(isset($_GET['delete'])){try{$pdo->prepare("DELETE FROM messages WHERE id=?")->execute([(int)$_GET['delete']]);$sm='বার্তা মুছে ফেলা হয়েছে';}catch(Exception$e){$em=$e->getMessage();}}
if($_SERVER['REQUEST_METHOD']==='POST'&&isset($_POST['action'])&&$_POST['action']==='reorder'){try{$od=json_decode($_POST['order_data'],true);if($od){foreach($od as$it)$pdo->prepare("UPDATE messages SET display_order=? WHERE id=?")->execute([$it['order'],$it['id']]);}echo json_encode(['success'=>true,'message'=>'ক্রম আপডেট হয়েছে']);exit;}catch(Exception$e){echo json_encode(['success'=>false,'message'=>$e->getMessage()]);exit;}}
$msg_list=$pdo->query("SELECT * FROM messages ORDER BY message_type,display_order,id")->fetchAll(PDO::FETCH_ASSOC);
$edit_msg=null;if(isset($_GET['edit'])){$s=$pdo->prepare("SELECT * FROM messages WHERE id=?");$s->execute([(int)$_GET['edit']]);$edit_msg=$s->fetch(PDO::FETCH_ASSOC);}
function h($s){return htmlspecialchars((string)$s,ENT_QUOTES,'UTF-8');}
$mt_opts=['principal'=>'প্রধান শিক্ষক','headmaster'=>'অধ্যক্ষ','super'=>'সুপার','chairman'=>'সভাপতি'];
$mt_badges=['principal'=>'primary','headmaster'=>'warning','super'=>'info','chairman'=>'success'];
?><!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><title>বার্তা ব্যবস্থাপনা - <?=h($sn)?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"><link href="../assets/css/jessoreboard-theme.css" rel="stylesheet"><link href="../assets/css/sidebar.css" rel="stylesheet"><link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
<style>:root{--p:#0ea5e9;--s:#6366f1;--g:#10b981;--d:#1e293b}*{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility}body{font-family:'Hind Siliguri',sans-serif;background:linear-gradient(135deg,#0f172a,#1e293b,#0f172a);min-height:100vh;color:#fff}
.mc{background:rgba(15,23,42,.85);border-radius:14px;box-shadow:0 8px 32px rgba(0,0,0,.3);border:1px solid rgba(255,255,255,.08);overflow:hidden;margin-bottom:16px}
.mc .ch{background:linear-gradient(135deg,rgba(14,165,233,.5),rgba(99,102,241,.4));padding:8px 14px;font-weight:700;font-size:.9rem}.mc .cb{padding:12px 14px}
.fl{font-weight:600;margin-bottom:2px;font-size:.82rem;color:#e2e8f0!important}
.fi{background:rgba(30,41,59,.85);border:1px solid rgba(255,255,255,.12);border-radius:8px;padding:6px 10px;font-size:.82rem;transition:.3s;width:100%;color:#fff!important}
.fi:focus{background:rgba(30,41,59,.95)!important;color:#fff!important;border-color:var(--p);box-shadow:0 0 0 3px rgba(14,165,233,.2);outline:none}
.fi:-webkit-autofill,.fi:-webkit-autofill:focus{background:rgba(30,41,59,.95)!important;-webkit-text-fill-color:#fff!important;box-shadow:0 0 0 30px #1e293b inset!important;border-color:var(--p)}
.fi option{background:var(--d)}textarea.fi{min-height:100px}
.btn-p,.btn-s,.btn-o,.btn-d{color:#fff!important}.btn-p{background:linear-gradient(135deg,var(--p),var(--s));border:none;border-radius:8px;padding:6px 18px;font-weight:700;font-size:.82rem;box-shadow:0 4px 14px rgba(14,165,233,.3)}.btn-p:hover{transform:translateY(-1px);box-shadow:0 6px 20px rgba(14,165,233,.4);color:#fff!important}
.btn-o{background:rgba(14,165,233,.15);border:1px solid rgba(14,165,233,.3);border-radius:8px;padding:4px 10px;font-size:.72rem}.btn-o:hover{background:rgba(14,165,233,.25);color:#fff!important}
.btn-d{background:rgba(239,68,68,.15);border:1px solid rgba(239,68,68,.3);border-radius:8px;padding:4px 10px;font-size:.72rem}.btn-d:hover{background:rgba(239,68,68,.25);color:#fff!important}
.cph{width:70px;height:70px;object-fit:cover;border-radius:10px;border:1px solid rgba(255,255,255,.1)}
.tb{width:100%;border-collapse:collapse;font-size:.82rem}.tb th{background:rgba(14,165,233,.15);padding:7px 8px;font-weight:700;font-size:.78rem;border-bottom:1px solid rgba(255,255,255,.08)}.tb td{padding:6px 8px;border-bottom:1px solid rgba(255,255,255,.04);vertical-align:middle}.tb tr:hover{background:rgba(255,255,255,.04)}
.dh{cursor:grab;color:rgba(255,255,255,.4)!important}.dh:hover{color:var(--p)!important}.dh:active{cursor:grabbing}
.ui-sortable-helper{background:rgba(15,23,42,.95)!important;backdrop-filter:blur(16px);box-shadow:0 8px 32px rgba(0,0,0,.4)!important;border-radius:8px;transform:rotate(1deg)}.ui-sortable-placeholder{background:rgba(14,165,233,.1)!important;border:2px dashed var(--p)!important;visibility:visible!important;height:50px!important;border-radius:8px}
.form-check-input{background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.2)}.form-check-input:checked{background:var(--p);border-color:var(--p)}
.alert{backdrop-filter:blur(8px);border:none;border-radius:8px;padding:8px 12px;font-size:.8rem}.alert-success{background:rgba(16,185,129,.18)}.alert-danger{background:rgba(239,68,68,.18)}.alert-info{background:rgba(14,165,233,.18)}
.badge{color:#fff!important}.btn-close{filter:brightness(0)invert(1)}.badge.bg-warning,.badge.bg-info,.badge.bg-success,.badge.bg-primary{color:#fff!important}
.main-content{background:transparent!important}.content-header{background:rgba(15,23,42,.9)!important;border-bottom:1px solid rgba(255,255,255,.08)!important}.content-title,.content-breadcrumb{color:#fff!important}.sidebar-container,.sidebar-container *{color:#fff!important}.sidebar-container .nav-link{color:rgba(255,255,255,.75)!important}.sidebar-container .nav-link:hover{color:#fff!important}
@media(max-width:768px){.fi{font-size:.75rem}.tb{font-size:.75rem}.cph{width:50px;height:50px}}
</style></head><body>
<div class="sidebar-container"><?=renderSidebar('index_with_sidebar.php',$ur,$un)?>
<div class="main-content"><div class="content-header"><h1 class="content-title"><i class="fas fa-comment-dots me-2"></i>বার্তা ব্যবস্থাপনা</h1><p class="content-breadcrumb"><i class="fas fa-home me-1"></i>হোম / অ্যাডমিন / বার্তা</p></div>
<div class="content-body">
<?php if($sm):?><div class="alert alert-success alert-dismissible fade show"><?=$sm?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif;?>
<?php if($em):?><div class="alert alert-danger alert-dismissible fade show"><?=$em?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif;?>
<div class="mc"><div class="ch"><i class="fas fa-<?=$edit_msg?'edit':'plus'?> me-1"></i><?=$edit_msg?'বার্তা সম্পাদনা':'নতুন বার্তা'?></div><div class="cb">
<form method="POST" enctype="multipart/form-data"><?php if($edit_msg):?><input type="hidden" name="edit_id" value="<?=$edit_msg['id']?>"><?php endif;?>
<div class="row g-2"><div class="col-md-4"><label class="fl">বার্তার ধরন</label><select class="form-select fi" name="message_type" required><option value="">নির্বাচন</option><?php foreach($mt_opts as$k=>$v):?><option value="<?=$k?>" <?=$edit_msg&&$edit_msg['message_type']===$k?'selected':''?>><?=$v?></option><?php endforeach;?></select></div>
<div class="col-md-4"><label class="fl">শিরোনাম</label><input class="form-control fi" name="title" value="<?=$edit_msg?h($edit_msg['title']):''?>" required></div>
<div class="col-md-2"><label class="fl">প্রদর্শন ক্রম</label><input type="number" class="form-control fi" name="display_order" value="<?=$edit_msg?$edit_msg['display_order']:'0'?>" min="0"></div>
<div class="col-md-2 d-flex align-items-end pb-1"><div class="form-check mb-0"><input class="form-check-input" type="checkbox" name="is_active" id="ia" <?=$edit_msg&&$edit_msg['is_active']?'checked':''?>><label class="form-check-label" for="ia" style="font-size:.78rem">সক্রিয়</label></div></div></div>
<div class="mb-2 mt-1"><label class="fl">বার্তা</label><textarea class="form-control fi" name="message" rows="4" required><?=$edit_msg?h($edit_msg['message']):''?></textarea></div>
<div class="mb-2"><label class="fl">ছবি</label><input type="file" class="form-control fi" name="photo" accept="image/*"><?php if($edit_msg&&$edit_msg['photo']):?><div class="mt-2"><img src="../<?=h($edit_msg['photo'])?>" class="cph" alt="Photo"><small class="d-block mt-1" style="opacity:.6;font-size:.72rem">বর্তমান ছবি</small></div><?php endif;?></div>
<div class="d-flex gap-2"><button type="submit" class="btn btn-p btn-sm"><i class="fas fa-save me-1"></i><?=$edit_msg?'আপডেট':'যোগ করুন'?></button><?php if($edit_msg):?><a href="messages.php" class="btn btn-s btn-outline-secondary"><i class="fas fa-times me-1"></i>বাতিল</a><?php endif;?></div></form></div></div>
<div class="mc"><div class="ch"><i class="fas fa-list me-1"></i>বার্তা তালিকা</div><div class="cb p-0">
<div class="d-flex gap-2 p-2 pb-0 flex-wrap align-items-center">
<select class="form-select fi" id="sb" style="width:auto;max-width:200px;padding:4px 8px;font-size:.75rem"><option value="do">ক্রম</option><option value="mt">ধরন</option><option value="ti">শিরোনাম</option></select>
<button class="btn btn-o" id="tsd" title="ক্রম দিক"><i class="fas fa-sort-amount-up"></i></button>
<button class="btn btn-o" id="tdm" title="ড্রাগ মোড"><i class="fas fa-grip-vertical"></i></button>
<button class="btn btn-o" id="rst" title="রিসেট"><i class="fas fa-undo"></i></button></div>
<?php if(empty($msg_list)):?><div class="text-center py-4" style="opacity:.5"><i class="fas fa-inbox fa-3x mb-2"></i><p>কোন বার্তা নেই</p></div>
<?php else:?><div style="overflow-x:auto"><table class="tb" id="mt"><thead><tr><th style="width:40px"><i class="fas fa-grip-vertical" id="dig" style="display:none;opacity:.5"></i></th><th style="width:50px">ক্রম</th><th style="width:110px">ধরন</th><th>শিরোনাম</th><th style="width:90px">ছবি</th><th style="width:80px">অবস্থা</th><th style="width:90px">কার্যক্রম</th></tr></thead>
<tbody id="sm"><?php foreach($msg_list as$m):?><tr data-id="<?=$m['id']?>" data-order="<?=$m['display_order']?>"><td class="dh" style="display:none"><i class="fas fa-grip-vertical" style="opacity:.5"></i></td>
<td><?=$m['display_order']?></td>
<td><span class="badge bg-<?=$mt_badges[$m['message_type']]??'secondary'?>" style="font-size:.7rem;padding:3px 8px"><?=$mt_opts[$m['message_type']]??$m['message_type']?></span></td>
<td style="font-size:.8rem"><?=h($m['title'])?></td>
<td><?php if($m['photo']):?><img src="../<?=h($m['photo'])?>" class="cph" style="width:50px;height:50px" alt="Photo"><?php else:?><span style="opacity:.4;font-size:.72rem">ছবি নেই</span><?php endif;?></td>
<td><span class="badge bg-<?=$m['is_active']?'success':'secondary'?>" style="font-size:.68rem;padding:3px 7px"><?=$m['is_active']?'সক্রিয়':'নিষ্ক্রিয়'?></span></td>
<td><div class="btn-group btn-group-sm"><a href="messages.php?edit=<?=$m['id']?>" class="btn btn-o btn-sm" title="সম্পাদনা"><i class="fas fa-edit"></i></a><a href="messages.php?delete=<?=$m['id']?>" class="btn btn-d btn-sm" title="মুছুন" onclick="return confirm('মুছে ফেলবেন?')"><i class="fas fa-trash"></i></a></div></td></tr><?php endforeach;?></tbody></table></div><?php endif;?></div></div>
</div></div></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script>let dm=false,sd='asc';
$('#sm').sortable({handle:'.dh',placeholder:'ui-sortable-placeholder',helper:function(e,u){u.children().each(function(){$(this).width($(this).width())});return u},update:function(){if(dm)sdO()}});
$('#tdm').click(function(){dm=!dm;if(dm){$('#mt').addClass('drag-mode-active');$(this).html('<i class="fas fa-check"></i> ড্রাগ');$('#dig').show();$('.dh').show()}else{$('#mt').removeClass('drag-mode-active');$(this).html('<i class="fas fa-grip-vertical"></i>');$('#dig').hide();$('.dh').hide()}});
$('#sb').change(function(){sT($(this).val())});
$('#tsd').click(function(){sd=sd==='asc'?'desc':'asc';$(this).find('i').toggleClass('fa-sort-amount-up fa-sort-amount-down');sT($('#sb').val())});
$('#rst').click(function(){location.reload()});
function sT(s){const t=$('#sm'),r=t.find('tr').toArray();r.sort(function(a,b){let av,bv;switch(s){case'do':av=parseInt($(a).data('order'));bv=parseInt($(b).data('order'));break;case'mt':const to={'প্রধান শিক্ষক':0,'অধ্যক্ষ':1,'সুপার':2,'সভাপতি':3};av=to[$(a).find('td:nth-child(3) .badge').text().trim()]??999;bv=to[$(b).find('td:nth-child(3) .badge').text().trim()]??999;break;case'ti':av=$(a).find('td:nth-child(4)').text().trim();bv=$(b).find('td:nth-child(4)').text().trim();break}return sd==='asc'?av>bv?1:-1:av<bv?1:-1});t.empty().append(r);uON()}
function uON(){$('#sm tr').each(function(i){$(this).find('td:nth-child(2)').text(i+1)})}
function sdO(){const d=[];$('#sm tr').each(function(i){d.push({id:$(this).data('id'),order:i+1})});$('#mt tbody').css('opacity','.5');$.ajax({url:'messages.php',method:'POST',data:{action:'reorder',order_data:JSON.stringify(d)},dataType:'json',success:function(r){$('#mt tbody').css('opacity','1');if(r.success)uON();else alert(r.message)}})}</script>
</body></html>
