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

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

// セキュリティ設定
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const ALLOWED_EXTS = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

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

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

// タイトルチェック
$title = trim($_POST['title'] ?? '');
if (empty($title)) {
    header('Location: admin.php?error=1');
    exit;
}

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

// 対象のworkを探す
$targetIndex = null;
foreach ($works as $i => $w) {
    if ((string)($w['id'] ?? '') === $targetId) {
        $targetIndex = $i;
        break;
    }
}

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

$existingWork = $works[$targetIndex];

// 削除する写真の処理
$deletePhotos = $_POST['delete_photos'] ?? [];
$remainingPhotos = [];
foreach ($existingWork['photos'] ?? [] as $photo) {
    $safeName = basename($photo);
    if (in_array($safeName, $deletePhotos, true)) {
        // ファイル削除（ディレクトリトラバーサル対策）
        $filePath = $uploadsDir . $safeName;
        $realUploads = realpath($uploadsDir);
        if ($realUploads) {
            $realFile = $realUploads . DIRECTORY_SEPARATOR . $safeName;
            if (file_exists($realFile)) {
                unlink($realFile);
            }
        }
    } else {
        $remainingPhotos[] = $safeName;
    }
}

// 新しい写真のアップロード処理
$newPhotos = [];
if (!empty($_FILES['photos']['name'][0])) {
    foreach ($_FILES['photos']['tmp_name'] as $i => $tmpName) {
        if ($_FILES['photos']['error'][$i] !== UPLOAD_ERR_OK) continue;
        if ($_FILES['photos']['size'][$i] > MAX_FILE_SIZE) continue;

        // MIMEタイプ検証
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($tmpName);
        if (!in_array($mimeType, ALLOWED_TYPES)) continue;

        // 拡張子検証
        $origName = $_FILES['photos']['name'][$i];
        $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
        if (!in_array($ext, ALLOWED_EXTS)) continue;

        // 新しいファイル名を生成（idを含む）
        $newName = $targetId . '_edit_' . ($i + 1) . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $destPath = $uploadsDir . $newName;

        // uploadsDir外への書き込み防止
        $realUploads = realpath($uploadsDir);
        if ($realUploads && strpos(realpath(dirname($destPath)) . DIRECTORY_SEPARATOR . basename($destPath), $realUploads) === 0) {
            if (move_uploaded_file($tmpName, $destPath)) {
                $newPhotos[] = $newName;
            }
        }
    }
}

// tagsを配列として取得・バリデーション
$tags = $_POST['tags'] ?? [];
$allowedTags = ['PLANNING', 'WEB', 'PR', 'DESIGN', 'EVENT', 'MOVIE'];
$tags = array_values(array_filter($tags, fn($t) => in_array($t, $allowedTags)));

// categoriesを配列として取得
$categories = $_POST['categories'] ?? [];
$allowedCats = ['動画制作', 'Web・SNS', 'デザイン', 'イベント企画', 'PR・広報', '広告運用'];
$categories = array_values(array_filter($categories, fn($c) => in_array($c, $allowedCats)));
$category = implode('・', $categories);

// scopesを配列として取得
$scopes = $_POST['scopes'] ?? [];
$allowedScopes = ['戦略・企画','Webサイト制作・運用','SNS運用','動画制作','グラフィックデザイン','広報・PR','広告','イベント運営','ブース制作','コンテンツ制作'];
$scopes = array_values(array_filter($scopes, fn($s) => in_array($s, $allowedScopes)));

// 既存データを上書き更新（idとcreatedAtは保持）
$works[$targetIndex] = [
    'id'                 => $existingWork['id'],
    'title'              => $title,
    'category'           => $category,
    'categories'         => $categories,
    'tags'               => $tags,
    'industry'           => trim($_POST['industry'] ?? ''),
    'client'             => trim($_POST['client'] ?? ''),
    'sponsor'            => trim($_POST['sponsor'] ?? ''),
    'publishToCorporate' => isset($_POST['publishToCorporate']) ? true : false,
    'staff'              => trim($_POST['staff'] ?? ''),
    'date'               => trim($_POST['date'] ?? ''),
    'description'        => trim($_POST['description'] ?? ''),
    'result'             => trim($_POST['result'] ?? ''),
    'resultDetail'       => trim($_POST['resultDetail'] ?? ''),
    'scope'              => implode(' / ', $scopes),
    'scopes'             => $scopes,
    'websiteUrl'         => trim($_POST['websiteUrl'] ?? ''),
    'youtubeUrl'         => trim($_POST['youtubeUrl'] ?? ''),
    'photos'             => array_merge($remainingPhotos, $newPhotos),
    'createdAt'          => $existingWork['createdAt'] ?? date('c'),
    'updatedAt'          => date('c'),
];

// works.jsonに書き戻す
$jsonStr = json_encode(array_values($works), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if (file_put_contents($dataFile, $jsonStr) === false) {
    header('Location: admin.php?error=1');
    exit;
}

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