<?php
declare(strict_types=1);require __DIR__.'/_bootstrap.php';
$id=(int)($_GET['id']??0);$service=null;$durations=[];$selectedTherapists=[];$selectedRooms=[];
if($id){$stmt=db()->prepare('SELECT * FROM services WHERE id=?');$stmt->execute([$id]);$service=$stmt->fetch();if(!$service){flash('error','Hizmet bulunamadı.');redirect('/admin/services.php');}$stmt=db()->prepare('SELECT * FROM service_durations WHERE service_id=? ORDER BY sort_order,duration_minutes');$stmt->execute([$id]);$durations=$stmt->fetchAll();$stmt=db()->prepare('SELECT therapist_id FROM therapist_services WHERE service_id=?');$stmt->execute([$id]);$selectedTherapists=array_map('intval',$stmt->fetchAll(PDO::FETCH_COLUMN));$stmt=db()->prepare('SELECT room_id FROM room_services WHERE service_id=?');$stmt->execute([$id]);$selectedRooms=array_map('intval',$stmt->fetchAll(PDO::FETCH_COLUMN));}
$allTherapists=db()->query('SELECT id,name FROM therapists WHERE is_active=1 ORDER BY sort_order,name')->fetchAll();$allRooms=db()->query('SELECT id,name,capacity FROM rooms WHERE is_active=1 ORDER BY sort_order,name')->fetchAll();
if(request_is_post()){
 verify_csrf();try{
  $name=admin_post_string('name');
  $shortDescription=admin_post_string('short_description');
  $description=sanitize_rich_html((string)($_POST['description']??''));
  if($name===''||$shortDescription===''||$description==='')throw new RuntimeException('Hizmet adı, kısa açıklama ve detay içeriği zorunludur.');
  $durationRows=[];
  foreach(preg_split('/\r?\n/',admin_post_string('durations'))?:[] as $line){
   $line=trim($line);if($line==='')continue;$parts=array_map('trim',explode('|',$line));$minutes=(int)($parts[0]??0);
   if($minutes<10||$minutes>1440)throw new RuntimeException('Süre seçenekleri 10 ile 1440 dakika arasında olmalıdır.');
   $label=mb_substr($parts[1]??($minutes.' Dakika'),0,80);$price=isset($parts[2])&&$parts[2]!==''?(float)str_replace(',','.',$parts[2]):null;
   if($price!==null&&$price<0)throw new RuntimeException('Süre fiyatı negatif olamaz.');
   $durationRows[]=[$minutes,$label,$price];
  }
  if(!$durationRows)throw new RuntimeException('En az bir geçerli süre seçeneği girin.');
  $therapistIds=array_values(array_unique(array_filter(array_map('intval',(array)($_POST['therapist_ids']??[])))));
  $roomIds=array_values(array_unique(array_filter(array_map('intval',(array)($_POST['room_ids']??[])))));
  if(!$therapistIds)throw new RuntimeException('Hizmet için en az bir terapist seçin.');
  if(!$roomIds)throw new RuntimeException('Hizmet için en az bir uygun oda seçin.');
  $slug=unique_slug('services',slugify(admin_post_string('slug',$name)),$id?:null);$image=upload_image('cover_image','services')?:admin_post_string('existing_image');
  $startingRaw=trim((string)($_POST['starting_price']??''));$startingPrice=$startingRaw!==''?(float)str_replace(',','.',$startingRaw):null;if($startingPrice!==null&&$startingPrice<0)throw new RuntimeException('Başlangıç fiyatı negatif olamaz.');
  $buffer=min(240,max(0,(int)($_POST['buffer_minutes']??15)));
  $values=[$name,$slug,admin_post_string('category','Wellness Ritüelleri'),admin_post_string('eyebrow'),$shortDescription,$description,admin_post_string('preparation_text'),admin_post_string('suitability_text'),$image,admin_post_string('meta_title'),admin_post_string('meta_description'),!empty($_POST['price_visible'])?1:0,$startingPrice,$buffer,min(2,max(1,(int)($_POST['required_therapists']??1))),!empty($_POST['is_featured'])?1:0,!empty($_POST['is_active'])?1:0,(int)($_POST['sort_order']??0)];
  $pdo=db();$pdo->beginTransaction();
  try{
   if($id){$sql='UPDATE services SET name=?,slug=?,category=?,eyebrow=?,short_description=?,description=?,preparation_text=?,suitability_text=?,cover_image=?,meta_title=?,meta_description=?,price_visible=?,starting_price=?,buffer_minutes=?,required_therapists=?,is_featured=?,is_active=?,sort_order=?,updated_at=NOW() WHERE id=?';$values[]=$id;$pdo->prepare($sql)->execute($values);}else{$sql='INSERT INTO services(name,slug,category,eyebrow,short_description,description,preparation_text,suitability_text,cover_image,meta_title,meta_description,price_visible,starting_price,buffer_minutes,required_therapists,is_featured,is_active,sort_order,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())';$pdo->prepare($sql)->execute($values);$id=(int)$pdo->lastInsertId();}
   $pdo->prepare('DELETE FROM service_durations WHERE service_id=?')->execute([$id]);$sort=0;foreach($durationRows as [$minutes,$label,$price]){$pdo->prepare('INSERT INTO service_durations(service_id,label,duration_minutes,price,is_active,sort_order) VALUES(?,?,?,?,1,?)')->execute([$id,$label,$minutes,$price,++$sort]);}
   $pdo->prepare('DELETE FROM therapist_services WHERE service_id=?')->execute([$id]);foreach($therapistIds as $therapistId){$pdo->prepare('INSERT INTO therapist_services(therapist_id,service_id) VALUES(?,?)')->execute([$therapistId,$id]);}
   $pdo->prepare('DELETE FROM room_services WHERE service_id=?')->execute([$id]);foreach($roomIds as $roomId){$pdo->prepare('INSERT INTO room_services(room_id,service_id) VALUES(?,?)')->execute([$roomId,$id]);}
   $pdo->commit();
  }catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();throw $e;}
  audit_log($service?'update':'create','services',$id);flash('success','Hizmet kaydedildi.');redirect('/admin/service-edit.php?id='.$id);
 }catch(Throwable $e){flash('error',$e->getMessage());}
}
$durationText=$service?'':"60|60 Dakika|\n90|90 Dakika|\n";foreach($durations as $d)$durationText.=$d['duration_minutes'].'|'.$d['label'].'|'.($d['price']??'')."\n";
admin_header($service?'Hizmeti Düzenle':'Yeni Hizmet');?>
<form method="post" enctype="multipart/form-data"><div class="panel"><div class="panel-head"><h2>Hizmet bilgileri</h2><div class="actions"><a class="button secondary" href="<?=url('/admin/services.php')?>">Listeye Dön</a><button class="button" type="submit">Kaydet</button></div></div><div class="panel-body form-grid"><?=csrf_field()?><div><label>Hizmet adı</label><input name="name" value="<?=e($service['name']??'')?>" required></div><div><label>URL</label><input name="slug" value="<?=e($service['slug']??'')?>" placeholder="Otomatik oluşturulur"></div><div><label>Kategori</label><input name="category" value="<?=e($service['category']??'Wellness Ritüelleri')?>"></div><div><label>Üst kısa başlık</label><input name="eyebrow" value="<?=e($service['eyebrow']??'')?>"></div><div class="full"><label>Kısa açıklama</label><textarea name="short_description" required><?=e($service['short_description']??'')?></textarea></div><div class="full"><label>Detay içeriği HTML kullanılabilir</label><textarea name="description" rows="12" required><?=e($service['description']??'')?></textarea></div><div><label>Seans öncesi bilgi</label><textarea name="preparation_text"><?=e($service['preparation_text']??'')?></textarea></div><div><label>Uygunluk ve bilgilendirme</label><textarea name="suitability_text"><?=e($service['suitability_text']??'')?></textarea></div><div><label>Kapak görseli</label><input type="file" name="cover_image" accept="image/jpeg,image/png,image/webp,image/avif"><input type="hidden" name="existing_image" value="<?=e($service['cover_image']??'')?>"><p class="help">Mevcut: <?=e($service['cover_image']??'Yok')?></p></div><div><label>Süre seçenekleri</label><textarea name="durations" rows="7" placeholder="60|60 Dakika|\n90|90 Dakika|"><?=e(trim($durationText))?></textarea><p class="help">Her satır: dakika|etiket|fiyat. Fiyat boş bırakılabilir.</p></div><div><label>Meta başlığı</label><input name="meta_title" value="<?=e($service['meta_title']??'')?>"></div><div><label>Meta açıklaması</label><textarea name="meta_description"><?=e($service['meta_description']??'')?></textarea></div><div><label>Başlangıç fiyatı</label><input type="number" step="0.01" name="starting_price" value="<?=e($service['starting_price']??'')?>"></div><div><label>Seans arası tampon dakika</label><input type="number" name="buffer_minutes" value="<?=e($service['buffer_minutes']??15)?>"></div><div><label>Gerekli terapist sayısı</label><select name="required_therapists"><option value="1" <?=($service['required_therapists']??1)==1?'selected':''?>>1 terapist</option><option value="2" <?=($service['required_therapists']??1)==2?'selected':''?>>2 terapist</option></select></div><div><label>Sıralama</label><input type="number" name="sort_order" value="<?=e($service['sort_order']??0)?>"></div><div class="full"><label>Bu hizmeti sunan terapistler</label><div class="form-grid"><?php foreach($allTherapists as $t):?><label class="checkrow"><input type="checkbox" name="therapist_ids[]" value="<?=$t['id']?>" <?=(!$service||in_array((int)$t['id'],$selectedTherapists,true))?'checked':''?>> <?=e($t['name'])?></label><?php endforeach;?></div></div><div class="full"><label>Bu hizmete uygun odalar</label><div class="form-grid"><?php foreach($allRooms as $r):?><label class="checkrow"><input type="checkbox" name="room_ids[]" value="<?=$r['id']?>" <?=(!$service||in_array((int)$r['id'],$selectedRooms,true))?'checked':''?>> <?=e($r['name'])?> · <?=$r['capacity']?> kişi</label><?php endforeach;?></div></div><div><label class="checkrow"><input type="checkbox" name="price_visible" value="1" <?=!empty($service['price_visible'])?'checked':''?>> Fiyatı göster</label><label class="checkrow"><input type="checkbox" name="is_featured" value="1" <?=!empty($service['is_featured'])?'checked':''?>> Öne çıkar</label><label class="checkrow"><input type="checkbox" name="is_active" value="1" <?=!$service||!empty($service['is_active'])?'checked':''?>> Aktif</label></div></div></div></form>
<?php admin_footer();?>
