<?php
require_once 'auth.php';
requireAdminAuth();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: admin.php');
    exit;
}

$targetId = trim($_POST['id'] ?? '');
if (empty($targetId)) {
    header('Location: admin.php?error=1');
    exit;
}

$dataFile = __DIR__ . '/data/works.json';
$uploadsDir = __DIR__ . '/uploads/';

// works.json読み込み
$works = [];
if (file_exists($dataFile)) {
    $json = file_get_contents($dataFile);
    $works = json_decode($json, true) ?: [];
}

// 対象を見つけて削除
$targetWork = null;
$newWorks = [];
foreach ($works as $w) {
    if ((string)($w['id'] ?? '') === $targetId) {
        $targetWork = $w;
    } else {
        $newWorks[] = $w;
    }
}

if ($targetWork === null) {
    header('Location: admin.php?error=1');
    exit;
}

// 写真ファイルを削除
if (!empty($targetWork['photos'])) {
    foreach ($targetWork['photos'] as $photo) {
        // ディレクトリトラバーサル対策
        $safeName = basename($photo);
        $filePath = $uploadsDir . $safeName;
        $realUploads = realpath($uploadsDir);
        $realFile = realpath(dirname($filePath)) . DIRECTORY_SEPARATOR . basename($filePath);
        if ($realFile && strpos($realFile, $realUploads) === 0 && file_exists($filePath)) {
            unlink($filePath);
        }
    }
}

// works.jsonを更新
$jsonStr = json_encode(array_values($newWorks), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if (file_put_contents($dataFile, $jsonStr) === false) {
    header('Location: admin.php?error=1');
    exit;
}

header('Location: admin.php?deleted=1');
exit;
