<?php
declare(strict_types=1);require __DIR__.'/_bootstrap.php';
if(request_is_post()){
 verify_csrf();$id=(int)($_POST['id']??0);$status=(string)($_POST['status']??'pending');$allowed=['pending','confirmed','completed','cancelled','rejected','no_show'];
 if($id>0&&in_array($status,$allowed,true)){
  $stmt=db()->prepare('UPDATE reservations SET status=?,admin_notes=?,updated_at=NOW() WHERE id=?');$stmt->execute([$status,trim((string)($_POST['admin_notes']??'')),$id]);
  audit_log('update','reservations',$id,'Durum: '.$status);flash('success','Rezervasyon güncellendi.');redirect('/admin/reservations.php?view='.$id);
 }
}
$statusFilter=(string)($_GET['status']??'');$date=(string)($_GET['date']??'');$q=trim((string)($_GET['q']??''));
$where=['1=1'];$params=[];
if($statusFilter!==''){$where[]='r.status=?';$params[]=$statusFilter;}if($date!==''){$where[]='r.reservation_date=?';$params[]=$date;}if($q!==''){$where[]='(r.guest_name LIKE ? OR r.reservation_code LIKE ? OR r.guest_phone LIKE ?)';$like='%'.$q.'%';array_push($params,$like,$like,$like);}
$export=($_GET['export']??'')==='csv';$limit=$export?'':' LIMIT 300';
$stmt=db()->prepare('SELECT r.*,ADDTIME(r.start_time,SEC_TO_TIME(sd.duration_minutes*60)) actual_end_time,s.name service_name,sd.label duration_label,t.name therapist_name,t2.name second_therapist_name,rm.name room_name FROM reservations r JOIN services s ON s.id=r.service_id JOIN service_durations sd ON sd.id=r.duration_id LEFT JOIN therapists t ON t.id=r.therapist_id LEFT JOIN therapists t2 ON t2.id=r.second_therapist_id LEFT JOIN rooms rm ON rm.id=r.room_id WHERE '.implode(' AND ',$where).' ORDER BY r.reservation_date DESC,r.start_time DESC'.$limit);$stmt->execute($params);$reservations=$stmt->fetchAll();
if($export){header('Content-Type: text/csv; charset=UTF-8');header('Content-Disposition: attachment; filename=nekrut-rezervasyonlar-'.date('Y-m-d').'.csv');echo "\xEF\xBB\xBF";$out=fopen('php://output','w');fputcsv($out,['Kod','Tarih','Başlangıç','Bitiş','Misafir','E-posta','Telefon','Hizmet','Süre','Seans','Terapist','İkinci Terapist','Oda','Durum','Not'],';','"','');foreach($reservations as $r){$safe=static fn($v)=>preg_match('/^[=+@-]/',(string)$v)?"'".(string)$v:(string)$v;fputcsv($out,array_map($safe,[$r['reservation_code'],$r['reservation_date'],substr($r['start_time'],0,5),substr($r['actual_end_time'],0,5),$r['guest_name'],$r['guest_email'],$r['guest_phone'],$r['service_name'],$r['duration_label'],$r['session_type'],$r['therapist_name'],$r['second_therapist_name'],$r['room_name'],$r['status'],$r['notes']]),';','"','');}fclose($out);exit;}
$view=null;if(isset($_GET['view'])){$id=(int)$_GET['view'];foreach($reservations as $row)if((int)$row['id']===$id)$view=$row;if(!$view){$s=db()->prepare('SELECT r.*,ADDTIME(r.start_time,SEC_TO_TIME(sd.duration_minutes*60)) actual_end_time,s.name service_name,sd.label duration_label,t.name therapist_name,t2.name second_therapist_name,rm.name room_name FROM reservations r JOIN services s ON s.id=r.service_id JOIN service_durations sd ON sd.id=r.duration_id LEFT JOIN therapists t ON t.id=r.therapist_id LEFT JOIN therapists t2 ON t2.id=r.second_therapist_id LEFT JOIN rooms rm ON rm.id=r.room_id WHERE r.id=?');$s->execute([$id]);$view=$s->fetch();}}
admin_header('Rezervasyonlar');?>
<div class="panel"><div class="panel-head"><form class="filterbar" method="get"><input name="q" value="<?=e($q)?>" placeholder="Kod, ad veya telefon"><input type="date" name="date" value="<?=e($date)?>"><select name="status"><option value="">Tüm durumlar</option><?php foreach(['pending'=>'Bekleyen','confirmed'=>'Onaylandı','completed'=>'Tamamlandı','cancelled'=>'İptal','rejected'=>'Reddedildi','no_show'=>'Gelmedi'] as $k=>$v):?><option value="<?=$k?>" <?=$statusFilter===$k?'selected':''?>><?=$v?></option><?php endforeach;?></select><button class="button" type="submit">Filtrele</button><button class="button secondary" type="submit" name="export" value="csv">CSV İndir</button></form></div>
<div class="table-wrap"><table><thead><tr><th>Kod</th><th>Tarih</th><th>Misafir</th><th>Hizmet</th><th>Kaynak</th><th>Durum</th><th></th></tr></thead><tbody><?php foreach($reservations as $r):?><tr><td><b><?=e($r['reservation_code'])?></b></td><td><?=e(date('d.m.Y',strtotime($r['reservation_date'])))?><br><span class="muted"><?=e(substr($r['start_time'],0,5))?>–<?=e(substr($r['actual_end_time'],0,5))?></span></td><td><?=e($r['guest_name'])?><br><span class="muted"><?=e($r['guest_phone'])?></span></td><td><?=e($r['service_name'])?><br><span class="muted"><?=e($r['duration_label'])?></span></td><td><?=e($r['therapist_name']?:'—')?><?=!empty($r['second_therapist_name'])?' + '.e($r['second_therapist_name']):''?><br><span class="muted"><?=e($r['room_name']?:'—')?></span></td><td><?=admin_status($r['status'])?></td><td><a class="button small secondary" href="?view=<?=$r['id']?>">Aç</a></td></tr><?php endforeach;?></tbody></table></div></div>
<?php if($view):?><div class="panel"><div class="panel-head"><h2><?=e($view['reservation_code'])?></h2><a class="button secondary" href="<?=url('/rezervasyon/yonet/'.$view['manage_token'])?>" target="_blank">Misafir Bağlantısı ↗</a></div><div class="panel-body split-admin"><div><div class="form-grid"><div><b>Misafir</b><p><?=e($view['guest_name'])?><br><?=e($view['guest_email'])?><br><?=e($view['guest_phone'])?></p></div><div><b>Hizmet</b><p><?=e($view['service_name'])?> · <?=e($view['duration_label'])?><br><?=e(format_date_tr($view['reservation_date']))?> · <?=e(substr($view['start_time'],0,5))?></p></div><div><b>Terapist</b><p><?=e($view['therapist_name']?:'Atanmadı')?><?=!empty($view['second_therapist_name'])?' + '.e($view['second_therapist_name']):''?></p></div><div><b>Oda</b><p><?=e($view['room_name']?:'Atanmadı')?></p></div><div class="full"><b>Misafir notu</b><p><?=nl2br(e($view['notes']?:'Not yok'))?></p></div></div></div><form method="post"><?=csrf_field()?><input type="hidden" name="id" value="<?=$view['id']?>"><label>Durum<select name="status"><?php foreach(['pending'=>'Bekleyen','confirmed'=>'Onaylandı','completed'=>'Tamamlandı','cancelled'=>'İptal','rejected'=>'Reddedildi','no_show'=>'Gelmedi'] as $k=>$v):?><option value="<?=$k?>" <?=$view['status']===$k?'selected':''?>><?=$v?></option><?php endforeach;?></select></label><label style="display:block;margin-top:14px">Yönetici notu<textarea name="admin_notes" rows="7"><?=e($view['admin_notes'])?></textarea></label><button class="button" type="submit" style="margin-top:14px">Güncelle</button></form></div></div><?php endif;?>
<?php admin_footer();?>
