<?php
// admin/roulette_segment_image_delete.php
declare(strict_types=1);

// Sempre JSON
header('Content-Type: application/json; charset=utf-8');

try {
  // Sessão mínima (sem redirect)
  $cookieParams = session_get_cookie_params();
  session_set_cookie_params([
    'lifetime' => 0,
    'path'     => $cookieParams['path'] ?? '/',
    'domain'   => $cookieParams['domain'] ?? '',
    'secure'   => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    'httponly' => true,
    'samesite' => 'Lax',
  ]);
  ini_set('session.use_strict_mode', '1');
  session_start();

  if (empty($_SESSION['auth']['user_id'])) {
    http_response_code(401);
    echo json_encode(['ok'=>false,'error'=>'not_authenticated']);
    exit;
  }

  require __DIR__ . '/../db/config.php'; // $pdo

  // Aceita POST (preferido) ou GET
  $src = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
  $segmentId  = isset($src['segment_id'])  ? (int)$src['segment_id']  : 0;
  $rouletteId = isset($src['roulette_id']) ? (int)$src['roulette_id'] : 0; // opcional

  if ($segmentId <= 0) {
    http_response_code(400);
    echo json_encode(['ok'=>false, 'error'=>'segment_id_missing']);
    exit;
  }

  // Busca segmento
  if ($rouletteId > 0) {
    $st = $pdo->prepare("SELECT id, roulette_id, image_path FROM roulette_segments WHERE id=? AND roulette_id=?");
    $st->execute([$segmentId, $rouletteId]);
  } else {
    $st = $pdo->prepare("SELECT id, roulette_id, image_path FROM roulette_segments WHERE id=?");
    $st->execute([$segmentId]);
  }
  $seg = $st->fetch(PDO::FETCH_ASSOC);
  if (!$seg) {
    echo json_encode(['ok'=>true, 'deleted'=>false, 'note'=>'segment_not_found']);
    exit;
  }

  $rid  = (int)$seg['roulette_id'];
  $path = (string)($seg['image_path'] ?? '');

  // Resolve caminho físico em /public
  $rel = ltrim($path, '/');
  $rel = preg_replace('#^public/#i', '', $rel);
  if (stripos($rel, 'uploads/') !== 0 && $rid > 0) {
    $rel = 'uploads/roulette_' . $rid . '/' . basename($rel);
  }
  $absPublic = realpath(__DIR__ . '/../public');
  $abs = $absPublic
    ? $absPublic . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $rel)
    : __DIR__ . '/../public/' . $rel;

  $fileDeleted = false;
  if ($path !== '' && is_file($abs)) {
    $fileDeleted = @unlink($abs);
  }

  // Zera no banco
  $st = $pdo->prepare("UPDATE roulette_segments SET image_path=NULL WHERE id=?");
  $st->execute([$segmentId]);

  echo json_encode([
    'ok'=>true,
    'deleted'=>true,
    'file_deleted'=>$fileDeleted,
    'segment_id'=>$segmentId,
    'roulette_id'=>$rid
  ]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['ok'=>false, 'error'=>$e->getMessage()]);
}