<?php
require __DIR__.'/../db/config.php';
function rrmdir($dir){ if (!is_dir($dir)) return; foreach(scandir($dir) as $i){ if($i=='.'||$i=='..') continue; $p=$dir.DIRECTORY_SEPARATOR.$i; if(is_dir($p)) rrmdir($p); else @unlink($p);} @rmdir($dir); }
$id = (int)($_GET['id'] ?? 0); if ($id<=0){ header('Location: index.php'); exit; }
$st=$pdo->prepare("SELECT slug FROM roulettes WHERE id=?"); $st->execute([$id]); $slug=$st->fetchColumn();

$roletasDir = realpath(__DIR__.'/../public/roletas') ?: (__DIR__.'/../public/roletas');
if ($slug){ $f=$roletasDir.DIRECTORY_SEPARATOR.$slug.'.php'; if (is_file($f)) @unlink($f); }
foreach (glob($roletasDir.'/*.php') as $f){
  $chunk=@file_get_contents($f,false,null,0,8192);
  $has = ($chunk!==false && strpos($chunk,"ROULETTE_ID:$id")!==false);
  if(!$has){ $all=@file_get_contents($f); if($all!==false && strpos($all,"ROULETTE_ID:$id")!==false) $has=true; }
  if($has) @unlink($f);
}
$up=realpath(__DIR__.'/../uploads') ?: (__DIR__.'/../uploads'); $dir=$up.DIRECTORY_SEPARATOR.$id; if(is_dir($dir)) rrmdir($dir);
$pdo->prepare("DELETE FROM roulettes WHERE id=?")->execute([$id]);
header('Location: index.php'); exit;
