<?php
declare(strict_types=1);require __DIR__.'/_bootstrap.php';
if(request_is_post()){
 verify_csrf();$action=(string)($_POST['action']??'hours');
 try{
  if($action==='hours'){
   $rows=[];for($d=1;$d<=7;$d++){$open=(string)($_POST['open'][$d]??'09:00');$close=(string)($_POST['close'][$d]??'22:00');if(!preg_match('/^\d{2}:\d{2}$/',$open)||!preg_match('/^\d{2}:\d{2}$/',$close)||$open>=$close)throw new RuntimeException($d.'. gün çalışma saatini kontrol edin.');$rows[]=[$open,$close,!empty($_POST['closed'][$d])?1:0,$d];}
   $pdo=db();$pdo->beginTransaction();try{foreach($rows as $row)$pdo->prepare('UPDATE business_hours SET open_time=?,close_time=?,is_closed=? WHERE weekday=?')->execute($row);$pdo->commit();}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();throw $e;}flash('success','Çalışma saatleri güncellendi.');
  }elseif($action==='block'){
   $blockDate=(string)($_POST['block_date']??'');$allDay=!empty($_POST['is_all_day']);$blockStart=(string)($_POST['start_time']??'');$blockEnd=(string)($_POST['end_time']??'');
   if(!valid_iso_date($blockDate)||$blockDate<date('Y-m-d')||(!$allDay&&(!preg_match('/^\d{2}:\d{2}$/',$blockStart)||!preg_match('/^\d{2}:\d{2}$/',$blockEnd)||$blockStart>=$blockEnd)))throw new RuntimeException('Kapalı tarih veya saat aralığını kontrol edin.');
   db()->prepare('INSERT INTO blocked_times(therapist_id,room_id,block_date,start_time,end_time,is_all_day,reason,created_at) VALUES(?,?,?,?,?,?,?,NOW())')->execute([($_POST['therapist_id']??'')!==''?(int)$_POST['therapist_id']:null,($_POST['room_id']??'')!==''?(int)$_POST['room_id']:null,$blockDate,$allDay?null:$blockStart,$allDay?null:$blockEnd,$allDay?1:0,admin_post_string('reason')]);flash('success','Kapalı zaman eklendi.');
  }elseif($action==='delete_block'){
   db()->prepare('DELETE FROM blocked_times WHERE id=?')->execute([(int)$_POST['id']]);flash('success','Kapalı zaman silindi.');
  }elseif($action==='therapist_schedule'){
   $therapistId=(int)($_POST['therapist_id']??0);if($therapistId<1)throw new RuntimeException('Terapist seçin.');$rows=[];
   for($d=1;$d<=7;$d++){$start=(string)($_POST['t_start'][$d]??'09:00');$end=(string)($_POST['t_end'][$d]??'22:00');if(!preg_match('/^\d{2}:\d{2}$/',$start)||!preg_match('/^\d{2}:\d{2}$/',$end)||$start>=$end)throw new RuntimeException($d.'. gün terapist vardiyasını kontrol edin.');$rows[]=[$therapistId,$d,$start,$end,!empty($_POST['t_off'][$d])?1:0];}
   $pdo=db();$pdo->beginTransaction();try{foreach($rows as $row)$pdo->prepare('INSERT INTO therapist_schedules(therapist_id,weekday,start_time,end_time,is_off) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE start_time=VALUES(start_time),end_time=VALUES(end_time),is_off=VALUES(is_off)')->execute($row);$pdo->commit();}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();throw $e;}flash('success','Terapist vardiyası güncellendi.');redirect('/admin/schedule.php?therapist_id='.$therapistId);
  }
 }catch(Throwable $e){flash('error',$e->getMessage());}
 redirect('/admin/schedule.php');
}
$hours=db()->query('SELECT * FROM business_hours ORDER BY weekday')->fetchAll();$therapists=db()->query('SELECT id,name FROM therapists WHERE is_active=1 ORDER BY name')->fetchAll();$rooms=db()->query('SELECT id,name FROM rooms WHERE is_active=1 ORDER BY name')->fetchAll();$blocks=db()->query('SELECT b.*,t.name therapist_name,r.name room_name FROM blocked_times b LEFT JOIN therapists t ON t.id=b.therapist_id LEFT JOIN rooms r ON r.id=b.room_id WHERE b.block_date>=CURDATE() ORDER BY b.block_date,b.start_time LIMIT 100')->fetchAll();$days=[1=>'Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi','Pazar'];$selectedTherapist=(int)($_GET['therapist_id']??($therapists[0]['id']??0));$therapistHours=[];if($selectedTherapist){$ts=db()->prepare('SELECT * FROM therapist_schedules WHERE therapist_id=? ORDER BY weekday');$ts->execute([$selectedTherapist]);foreach($ts->fetchAll() as $row)$therapistHours[(int)$row['weekday']]=$row;}admin_header('Çalışma Takvimi');?>
<div class="split-admin"><form class="panel" style="margin-top:0" method="post"><div class="panel-head"><h2>Genel çalışma saatleri</h2></div><div class="panel-body"><?=csrf_field()?><input type="hidden" name="action" value="hours"><table><thead><tr><th>Gün</th><th>Açılış</th><th>Kapanış</th><th>Kapalı</th></tr></thead><tbody><?php foreach($hours as $h):?><tr><td><?=$days[$h['weekday']]?></td><td><input type="time" name="open[<?=$h['weekday']?>]" value="<?=e(substr($h['open_time'],0,5))?>"></td><td><input type="time" name="close[<?=$h['weekday']?>]" value="<?=e(substr($h['close_time'],0,5))?>"></td><td><input type="checkbox" name="closed[<?=$h['weekday']?>]" value="1" <?=$h['is_closed']?'checked':''?>></td></tr><?php endforeach;?></tbody></table><button class="button" style="margin-top:15px">Saatleri Kaydet</button></div></form>
<form class="panel" style="margin-top:0" method="post"><div class="panel-head"><h2>Kapalı zaman ekle</h2></div><div class="panel-body"><?=csrf_field()?><input type="hidden" name="action" value="block"><label>Tarih<input type="date" name="block_date" min="<?=date('Y-m-d')?>" required></label><label>Terapist<select name="therapist_id"><option value="">Tümü</option><?php foreach($therapists as $t):?><option value="<?=$t['id']?>"><?=e($t['name'])?></option><?php endforeach;?></select></label><label>Oda<select name="room_id"><option value="">Tümü</option><?php foreach($rooms as $r):?><option value="<?=$r['id']?>"><?=e($r['name'])?></option><?php endforeach;?></select></label><div class="form-grid"><label>Başlangıç<input type="time" name="start_time" value="09:00"></label><label>Bitiş<input type="time" name="end_time" value="22:00"></label></div><label class="checkrow"><input type="checkbox" name="is_all_day" value="1"> Tüm gün</label><label>Neden<input name="reason"></label><button class="button" type="submit">Ekle</button></div></form></div>
<div class="panel"><div class="panel-head"><h2>Terapist vardiyaları</h2><form method="get" class="filterbar"><select name="therapist_id" onchange="this.form.submit()"><?php foreach($therapists as $t):?><option value="<?=$t['id']?>" <?=$selectedTherapist===$t['id']?'selected':''?>><?=e($t['name'])?></option><?php endforeach;?></select><noscript><button class="button secondary">Göster</button></noscript></form></div><div class="panel-body"><form method="post"><?=csrf_field()?><input type="hidden" name="action" value="therapist_schedule"><input type="hidden" name="therapist_id" value="<?=$selectedTherapist?>"><div class="table-wrap"><table><thead><tr><th>Gün</th><th>Başlangıç</th><th>Bitiş</th><th>İzinli</th></tr></thead><tbody><?php for($d=1;$d<=7;$d++):$th=$therapistHours[$d]??['start_time'=>'09:00:00','end_time'=>'22:00:00','is_off'=>0];?><tr><td><?=$days[$d]?></td><td><input type="time" name="t_start[<?=$d?>]" value="<?=e(substr($th['start_time'],0,5))?>"></td><td><input type="time" name="t_end[<?=$d?>]" value="<?=e(substr($th['end_time'],0,5))?>"></td><td><input type="checkbox" name="t_off[<?=$d?>]" value="1" <?=$th['is_off']?'checked':''?>></td></tr><?php endfor;?></tbody></table></div><button class="button" style="margin-top:15px">Vardiyayı Kaydet</button></form></div></div>
<div class="panel"><div class="panel-head"><h2>Yaklaşan kapalı zamanlar</h2></div><div class="table-wrap"><table><thead><tr><th>Tarih</th><th>Saat</th><th>Terapist</th><th>Oda</th><th>Neden</th><th></th></tr></thead><tbody><?php foreach($blocks as $b):?><tr><td><?=e(date('d.m.Y',strtotime($b['block_date'])))?></td><td><?=$b['is_all_day']?'Tüm gün':e(substr($b['start_time'],0,5).'–'.substr($b['end_time'],0,5))?></td><td><?=e($b['therapist_name']?:'Tümü')?></td><td><?=e($b['room_name']?:'Tümü')?></td><td><?=e($b['reason'])?></td><td><form method="post"><?=csrf_field()?><input type="hidden" name="action" value="delete_block"><button class="button small danger" name="id" value="<?=$b['id']?>" data-confirm="Silinsin mi?">Sil</button></form></td></tr><?php endforeach;?></tbody></table></div></div>
<?php admin_footer();?>
