<?php
session_start();
require_once '../includes/access_control.php';
require_once '../config/database.php';
require_once '../includes/branch_helper.php';
require_once '../classes/VoIPNotificationService.php';
require_any_role(['admin','teacher'],'../login.php');
$ur=$_SESSION['user_role'];$uid=$_SESSION['user_id'];

// Ensure branch_id exists on timetable
ensure_school_branches_schema($pdo);
$col=$pdo->query("SHOW COLUMNS FROM timetable LIKE 'branch_id'")->fetch();
if(!$col){try{$pdo->exec("ALTER TABLE timetable ADD COLUMN branch_id INT NULL DEFAULT NULL AFTER class_id");}catch(Throwable$e){}}

if(isset($_GET['session_id'])&&isset($_GET['class_id'])&&isset($_GET['teacher_id'])){header("Location: ../trigger_class_voip.php?session_id={$_GET['session_id']}&class_id={$_GET['class_id']}&teacher_id={$_GET['teacher_id']}");exit;}
$tid=null;
if($ur=='teacher'){$s=$pdo->prepare("SELECT id FROM teachers WHERE user_id=?");$s->execute([$uid]);$t=$s->fetch();if($t)$tid=$t['id'];}
$voip=new VoIPNotificationService($pdo);
$classes=$pdo->query("SELECT id,name,section FROM classes WHERE status='active' ORDER BY name,section")->fetchAll();
$subjects=$pdo->query("SELECT id,name,code FROM subjects WHERE status='active' ORDER BY name")->fetchAll();
$teachers=$pdo->query("SELECT id,first_name,last_name,designation FROM teachers WHERE status='active' ORDER BY first_name,last_name")->fetchAll();
$sessions=$pdo->query("SELECT id,session_name FROM academic_sessions WHERE status='active' ORDER BY is_current DESC,start_date DESC")->fetchAll();
$branches=get_active_school_branches($pdo);
$branchCounts=[];
try{$rc=$pdo->query("SELECT branch_id,COUNT(*) as cnt FROM timetable WHERE branch_id IS NOT NULL GROUP BY branch_id")->fetchAll(PDO::FETCH_KEY_PAIR);foreach($rc as$bid=>$cnt)$branchCounts[$bid]=$cnt;}catch(Throwable$e){}
$sm='';$em='';
if($_SERVER['REQUEST_METHOD']==='POST'){
if(isset($_POST['create_routine'])||isset($_POST['edit_routine'])){
$cid=$_POST['class_id'];$sid=$_POST['subject_id'];$ti=$_POST['teacher_id'];$dw=$_POST['day_of_week'];$st=$_POST['start_time'];$et=$_POST['end_time'];$rn=trim($_POST['room_number']);$ay=trim($_POST['academic_year']);$bid=!empty($_POST['branch_id'])?$_POST['branch_id']:null;
if(empty($cid)||empty($sid)||empty($ti)||empty($dw)||empty($st)||empty($et)){$em='সব ক্ষেত্র পূরণ করুন';}
else{try{if(isset($_POST['edit_routine'])){$pdo->prepare("UPDATE timetable SET class_id=?,branch_id=?,subject_id=?,teacher_id=?,day_of_week=?,start_time=?,end_time=?,room_number=?,academic_year=? WHERE id=?")->execute([$cid,$bid,$sid,$ti,$dw,$st,$et,$rn,$ay,$_POST['routine_id']]);$sm='রুটিন আপডেট হয়েছে!';}else{$pdo->prepare("INSERT INTO timetable(class_id,branch_id,subject_id,teacher_id,day_of_week,start_time,end_time,room_number,academic_year)VALUES(?,?,?,?,?,?,?,?,?)")->execute([$cid,$bid,$sid,$ti,$dw,$st,$et,$rn,$ay]);$sm='রুটিন তৈরি হয়েছে!';}}catch(Exception$e){$em='ত্রুটি: '.$e->getMessage();}}}
if(isset($_POST['delete_routine'])){try{$pdo->prepare("DELETE FROM timetable WHERE id=?")->execute([$_POST['routine_id']]);$sm='রুটিন মুছে ফেলা হয়েছে!';}catch(Exception$e){$em=$e->getMessage();}}
if(isset($_POST['send_voip_notification'])){
$rid=$_POST['routine_id'];try{$s=$pdo->prepare("SELECT t.*,c.name as class_name,c.section as class_section,s.name as subject_name,te.first_name as tfn,te.last_name as tln,te.phone as tphone,COALESCE(sb.branch_name,'') as branch_name FROM timetable t JOIN classes c ON t.class_id=c.id JOIN subjects s ON t.subject_id=s.id JOIN teachers te ON t.teacher_id=te.id LEFT JOIN school_branches sb ON t.branch_id=sb.id WHERE t.id=?");$s->execute([$rid]);$r=$s->fetch();
if($r){$bn=!empty($r['branch_name'])?' ['.$r['branch_name'].']':'';$res=$voip->sendVoIPNotification($r['tphone'],"অধ্যাপক, আপনার ক্লাস: {$r['subject_name']} - {$r['class_name']} {$r['class_section']}{$bn}। সময়: {$r['start_time']} - {$r['end_time']}।");$sm=$res['success']?'VoIP পাঠানো হয়েছে!':$res['message'];}else{$em='রুটিন পাওয়া যায়নি';}}catch(Exception$e){$em=$e->getMessage();}}}
$er=null;
if(isset($_GET['edit_id'])&&$ur=='admin'){$s=$pdo->prepare("SELECT * FROM timetable WHERE id=?");$s->execute([$_GET['edit_id']]);$er=$s->fetch();}
$wc=[];$p=[];
if($ur=='teacher'){$wc[]="t.teacher_id=?";$p[]=$tid??-1;}
if(!empty($_GET['class_id'])){$wc[]="t.class_id=?";$p[]=$_GET['class_id'];}
if(!empty($_GET['teacher_id'])){$wc[]="t.teacher_id=?";$p[]=$_GET['teacher_id'];}
if(!empty($_GET['branch_id'])){$wc[]="t.branch_id=?";$p[]=$_GET['branch_id'];}
if(!empty($_GET['session_id'])){$s=$pdo->prepare("SELECT session_name FROM academic_sessions WHERE id=?");$s->execute([$_GET['session_id']]);$ss=$s->fetch();if($ss){$wc[]="t.academic_year=?";$p[]=$ss['session_name'];}}
$w=(!empty($wc)?'WHERE '.implode(' AND ',$wc):'');
$routines=$pdo->prepare("SELECT t.*,c.name as cname,c.section as csec,s.name as sname,s.code as scode,te.first_name as tfn,te.last_name as tln,te.designation,COALESCE(sb.branch_name,'') as bname FROM timetable t JOIN classes c ON t.class_id=c.id JOIN subjects s ON t.subject_id=s.id JOIN teachers te ON t.teacher_id=te.id LEFT JOIN school_branches sb ON t.branch_id=sb.id $w ORDER BY t.day_of_week,t.start_time");
$routines->execute($p);$routines=$routines->fetchAll();
$days=['sunday'=>'রবিবার','monday'=>'সোমবার','tuesday'=>'মঙ্গলবার','wednesday'=>'বুধবার','thursday'=>'বৃহস্পতিবার'];
$slots=[];foreach($routines as$r){if(in_array($r['day_of_week'],['saturday','friday']))continue;$k=$r['start_time'].'-'.$r['end_time'];if(!in_array($k,$slots))$slots[]=$k;}
$grid=[];foreach($days as$dk=>$dn){$grid[$dk]=[];foreach($slots as$sk)$grid[$dk][$sk]=[];}
foreach($routines as$r){if(in_array($r['day_of_week'],['saturday','friday']))continue;$sk=$r['start_time'].'-'.$r['end_time'];$dk=$r['day_of_week'];if(isset($grid[$dk][$sk]))$grid[$dk][$sk][]=$r;}
?><!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>শিক্ষকের রুটিন</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/sidebar.css" rel="stylesheet">
<style>
:root{--g:#006747;--r:#F42A41;--b:#1565c0}
body{background:#f0f4ff;font-size:.82rem}
.tc{border:none;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,.08);overflow:hidden}
.tc .ch{background:linear-gradient(135deg,var(--g),#004d35);color:#fff;padding:10px 14px;font-weight:700;font-size:.88rem}
.tc .cb{padding:10px}
.rt{width:100%;border-collapse:separate;border-spacing:0;font-size:.72rem}
.rt th{background:linear-gradient(135deg,var(--g),#004d35);color:#fff;padding:8px 6px;font-weight:700;font-size:.72rem;text-align:center;border:1px solid rgba(255,255,255,.15)}
.rt th:first-child{width:80px}
.rt td{border:1px solid #dee2e6;padding:4px;vertical-align:top;min-height:60px;background:#fff}
.rt td:hover{background:#f0fdf4}
.ri{background:#f8f9fa;border-radius:6px;padding:6px;margin:2px 0;border-left:3px solid var(--g);font-size:.72rem;transition:.2s}
.ri:hover{background:#e8f5e9;transform:translateY(-1px);box-shadow:0 2px 6px rgba(0,0,0,.08)}
.ri .sn{font-weight:700;color:#333;font-size:.74rem}
.ri .cr{color:#666;font-size:.68rem}
.ri .bn{color:#e65100;font-size:.64rem;font-weight:600}
.ri .tn{color:var(--b);font-size:.66rem}
.mc{border-left:3px solid var(--b);background:#e3f2fd !important}
.hd{font-size:.68rem;font-weight:700;color:#333}
.ft{display:none}
@media print{
@page{size:A4 landscape;margin:3mm}
body{font-size:7pt;margin:0;padding:0}
.no-print,.ft{display:none !important}
.container-fluid{max-width:100%;padding:0}
.tc{box-shadow:none;border:1px solid #ccc}
.rt th{background:#333 !important;font-size:6pt;padding:3px}
.rt td{padding:2px;font-size:6pt}
.ri{padding:2px;border-left-width:2px;font-size:6pt}
.ri .sn{font-size:6.5pt}.ri .cr,.ri .tn,.ri .bn{font-size:5.5pt}
}
.fb{background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.25);border-radius:6px;padding:6px 10px;font-size:.78rem;width:100%;color:#fff}
.fb option{color:#333;background:#fff}
.fb:focus{outline:none;border-color:#fff;box-shadow:0 0 0 2px rgba(255,255,255,.3)}
.al{background:linear-gradient(135deg,var(--g),#004d35);padding:6px 14px;display:flex;align-items:center;border-radius:10px;margin-bottom:10px;color:#fff;font-size:.85rem;font-weight:700}
</style>
</head>
<body>
<?php if(file_exists(__DIR__.'/../includes/sidebar_layout.php')){require_once '../includes/sidebar_layout.php';?>
<div class="sidebar-container"><?=renderSidebar('routine.php',$ur,$_SESSION['username'])?>
<div class="main-content"><div class="content-header"><h1 class="content-title"><i class="fas fa-calendar-alt me-2"></i>শিক্ষকের ক্লাস রুটিন</h1><p class="content-breadcrumb"><i class="fas fa-home me-1"></i>হোম / শিক্ষক / রুটিন</p></div>
<div class="content-body">
<?php }else{ ?><nav class="navbar navbar-expand navbar-dark" style="background:linear-gradient(135deg,var(--g),#004d35)"><div class="container-fluid"><a class="navbar-brand" href="<?=$ur=='teacher'?'dashboard.php':'../index.php'?>"><i class="fas fa-graduation-cap me-1"></i> রুটিন</a></div></nav><div class="container-fluid mt-3"><?php }?>
<?php if($sm):?><div class="alert alert-success alert-dismissible fade show py-2" style="font-size:.8rem"><i class="fas fa-check-circle me-1"></i><?=$sm?><button type="button" class="btn-close btn-close-sm" data-bs-dismiss="alert"></button></div><?php endif;?>
<?php if($em):?><div class="alert alert-danger alert-dismissible fade show py-2" style="font-size:.8rem"><i class="fas fa-exclamation-triangle me-1"></i><?=$em?><button type="button" class="btn-close btn-close-sm" data-bs-dismiss="alert"></button></div><?php endif;?>

<div class="row g-2">
<?php if($ur=='admin'):?>
<div class="col-lg-3 no-print">
<div class="tc"><div class="ch"><i class="fas fa-<?=$er?'edit':'plus'?> me-1"></i><?=$er?'রুটিন সম্পাদনা':'নতুন রুটিন'?></div>
<div class="cb">
<form method="POST">
<input type="hidden" name="<?=$er?'edit_routine':'create_routine'?>" value="1">
<?php if($er):?><input type="hidden" name="routine_id" value="<?=$er['id']?>"><?php endif;?>
<div class="mb-2"><label class="hd">শাখা</label><select class="form-select form-select-sm" name="branch_id"><option value="">ঐচ্ছিক</option><?php foreach($branches as$br):?><option value="<?=$br['id']?>" <?=$er&&$er['branch_id']==$br['id']?'selected':''?>><?=htmlspecialchars($br['branch_name'])?></option><?php endforeach;?></select></div>
<div class="mb-2"><label class="hd">ক্লাস *</label><select class="form-select form-select-sm" name="class_id" required><option value="">নির্বাচন</option><?php foreach($classes as$c):?><option value="<?=$c['id']?>" <?=$er&&$er['class_id']==$c['id']?'selected':''?>><?=htmlspecialchars($c['name'].' - '.$c['section'])?></option><?php endforeach;?></select></div>
<div class="mb-2"><label class="hd">বিষয় *</label><select class="form-select form-select-sm" name="subject_id" required><option value="">নির্বাচন</option><?php foreach($subjects as$s):?><option value="<?=$s['id']?>" <?=$er&&$er['subject_id']==$s['id']?'selected':''?>><?=htmlspecialchars($s['name'].' ('.$s['code'].')')?></option><?php endforeach;?></select></div>
<div class="mb-2"><label class="hd">শিক্ষক *</label><select class="form-select form-select-sm" name="teacher_id" required><option value="">নির্বাচন</option><?php foreach($teachers as$t):?><option value="<?=$t['id']?>" <?=$er&&$er['teacher_id']==$t['id']?'selected':''?>><?=htmlspecialchars($t['first_name'].' '.$t['last_name'])?></option><?php endforeach;?></select></div>
<div class="mb-2"><label class="hd">দিন *</label><select class="form-select form-select-sm" name="day_of_week" required><option value="">নির্বাচন</option><?php foreach($days as$dk=>$dn):?><option value="<?=$dk?>" <?=$er&&$er['day_of_week']==$dk?'selected':''?>><?=$dn?></option><?php endforeach;?></select></div>
<div class="row g-1"><div class="col-6"><label class="hd">শুরু *</label><input type="time" class="form-control form-control-sm" name="start_time" value="<?=$er?$er['start_time']:''?>" required></div><div class="col-6"><label class="hd">শেষ *</label><input type="time" class="form-control form-control-sm" name="end_time" value="<?=$er?$er['end_time']:''?>" required></div></div>
<div class="mb-2"><label class="hd">রুম</label><input type="text" class="form-control form-control-sm" name="room_number" value="<?=$er?htmlspecialchars($er['room_number']):''?>" placeholder="ঐচ্ছিক"></div>
<div class="mb-2"><label class="hd">সেশন</label><select class="form-select form-select-sm" name="academic_year"><option value="">নির্বাচন</option><?php foreach($sessions as$ss):?><option value="<?=htmlspecialchars($ss['session_name'])?>" <?=$er&&$er['academic_year']==$ss['session_name']?'selected':''?>><?=htmlspecialchars($ss['session_name'])?></option><?php endforeach;?></select></div>
<button type="submit" class="btn btn-sm w-100 mb-1" style="background:var(--g);color:#fff"><i class="fas fa-save me-1"></i><?=$er?'আপডেট':'সেভ'?></button>
<?php if($er):?><a href="routine.php" class="btn btn-outline-secondary btn-sm w-100"><i class="fas fa-times me-1"></i>বাতিল</a><?php endif;?>
</form></div></div>
</div>
<div class="col-lg-<?=($ur=='admin'?'9':'12')?>">
<?php else:?>
<div class="col-12">
<?php endif;?>
<div class="tc no-print"><div class="ch d-flex justify-content-between align-items-center">
<span><i class="fas fa-filter me-1"></i>ফিল্টার</span>
<div><button class="btn btn-sm btn-light me-1" onclick="window.print()"><i class="fas fa-print"></i> প্রিন্ট</button><?php if($ur=='admin'):?><a href="voip_check.php" class="btn btn-sm btn-warning"><i class="fas fa-phone-volume"></i> VoIP</a><?php endif;?></div>
</div><div class="cb">
<form method="GET" class="row g-1 align-items-end">
<?php if($ur=='admin'):?>
<div class="col-md-2"><label class="hd text-dark">সেশন</label><select class="form-select form-select-sm" name="session_id"><option value="">সব</option><?php foreach($sessions as$ss):?><option value="<?=$ss['id']?>" <?=($_GET['session_id']??'')==$ss['id']?'selected':''?>><?=htmlspecialchars($ss['session_name'])?></option><?php endforeach;?></select></div>
<div class="col-md-2"><label class="hd text-dark">শাখা</label><select class="form-select form-select-sm" name="branch_id"><option value="">সব</option><?php foreach($branches as$br):?><option value="<?=$br['id']?>" <?=($_GET['branch_id']??'')==$br['id']?'selected':''?>><?=htmlspecialchars($br['branch_name'])?> (<?=$branchCounts[$br['id']]??0?>)</option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="hd text-dark">ক্লাস</label><select class="form-select form-select-sm" name="class_id"><option value="">সব</option><?php foreach($classes as$c):?><option value="<?=$c['id']?>" <?=($_GET['class_id']??'')==$c['id']?'selected':''?>><?=htmlspecialchars($c['name'].' - '.$c['section'])?></option><?php endforeach;?></select></div>
<div class="col-md-3"><label class="hd text-dark">শিক্ষক</label><select class="form-select form-select-sm" name="teacher_id"><option value="">সব</option><?php foreach($teachers as$t):?><option value="<?=$t['id']?>" <?=($_GET['teacher_id']??'')==$t['id']?'selected':''?>><?=htmlspecialchars($t['first_name'].' '.$t['last_name'])?></option><?php endforeach;?></select></div>
<?php else:?>
<div class="col-md-4"><label class="hd text-dark">সেশন</label><select class="form-select form-select-sm" name="session_id"><option value="">সব</option><?php foreach($sessions as$ss):?><option value="<?=$ss['id']?>" <?=($_GET['session_id']??'')==$ss['id']?'selected':''?>><?=htmlspecialchars($ss['session_name'])?></option><?php endforeach;?></select></div>
<?php endif;?>
<div class="col-auto"><button type="submit" class="btn btn-sm" style="background:var(--g);color:#fff"><i class="fas fa-search"></i></button><a href="routine.php" class="btn btn-sm btn-outline-secondary"><i class="fas fa-redo"></i></a></div>
</form></div></div>

<div class="tc"><div class="cb p-0">
<?php if(empty($routines)):?>
<div class="text-center py-5"><i class="fas fa-calendar-times fa-3x mb-2" style="color:#ccc"></i><p class="text-muted small">কোনো রুটিন নেই</p></div>
<?php else:?>
<div class="table-responsive">
<table class="rt">
<thead><tr><th>দিন / সময়</th><?php $sk_list=$slots; foreach($sk_list as$sk){$t=explode('-',$sk);$s=date('g:i',strtotime($t[0]));$e=date('g:i',strtotime($t[1]));?><th><?=$s?><br><?=$e?></th><?php }?></tr></thead>
<tbody>
<?php foreach($days as$dk=>$dn):?>
<tr>
<td style="background:linear-gradient(135deg,var(--g),#004d35);color:#fff;text-align:center;font-weight:700;font-size:.74rem;vertical-align:middle"><?=$dn?></td>
<?php foreach($sk_list as$sk):?>
<td class="<?=count($grid[$dk][$sk])>1?'multiple':''?>" style="min-width:120px">
<?php foreach($grid[$dk][$sk] as$r):?>
<div class="ri <?=count($grid[$dk][$sk])>1?'mc':''?>">
<div class="sn"><i class="fas fa-book me-1" style="color:var(--g)"></i><?=htmlspecialchars($r['sname'])?></div>
<div class="cr"><i class="fas fa-school me-1"></i><?=htmlspecialchars($r['cname'].' - '.$r['csec'])?></div>
<?php if(!empty($r['bname'])):?><div class="bn"><i class="fas fa-code-branch me-1"></i><?=htmlspecialchars($r['bname'])?></div><?php endif;?>
<?php if(!empty($r['room_number'])):?><div class="cr"><i class="fas fa-door-open me-1"></i>রুম <?=htmlspecialchars($r['room_number'])?></div><?php endif;?>
<?php if($ur=='admin'):?><div class="tn"><i class="fas fa-user-tie me-1"></i><?=htmlspecialchars($r['tfn'].' '.$r['tln'])?></div>
<div class="d-flex gap-1 mt-1 no-print">
<a href="?edit_id=<?=$r['id']?>" class="btn btn-outline-warning btn-sm" style="padding:1px 5px;font-size:.62rem"><i class="fas fa-edit"></i></a>
<form method="POST" class="d-inline" onsubmit="return confirm('মুছে ফেলবেন?')"><input type="hidden" name="delete_routine" value="1"><input type="hidden" name="routine_id" value="<?=$r['id']?>"><button class="btn btn-outline-danger btn-sm" style="padding:1px 5px;font-size:.62rem"><i class="fas fa-trash"></i></button></form>
<form method="POST" class="d-inline"><input type="hidden" name="send_voip_notification" value="1"><input type="hidden" name="routine_id" value="<?=$r['id']?>"><button class="btn btn-outline-info btn-sm" style="padding:1px 5px;font-size:.62rem" onclick="return confirm('VoIP পাঠাবেন?')"><i class="fas fa-phone"></i></button></form>
</div><?php endif;?>
</div>
<?php endforeach;?>
</td>
<?php endforeach;?>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
<?php endif;?>
</div></div>
</div></div>
</div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>