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

// セキュリティ設定
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/';

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

// フォームデータ取得
$title = trim($_POST['title'] ?? '');
if (empty($title)) {
    header('Location: admin.php?error=1');
    exit;
}

// 新しいIDを生成
$maxId = 0;
foreach ($works as $w) {
    $id = intval($w['id'] ?? 0);
    if ($id > $maxId) $maxId = $id;
}
$newId = (string)($maxId + 1);

// 写真アップロード処理
$savedPhotos = [];
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;

        // ディレクトリトラバーサル対策：新しいファイル名を生成
        $newName = $newId . '_' . ($i + 1) . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $destPath = $uploadsDir . $newName;

        // uploadsDir外への書き込み防止
        $realUploads = realpath($uploadsDir);
        $realDest = realpath(dirname($destPath)) . DIRECTORY_SEPARATOR . basename($destPath);
        if (strpos($realDest, $realUploads) !== 0) continue;

        if (move_uploaded_file($tmpName, $destPath)) {
            $savedPhotos[] = $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)));

// 新しい実績データ
$newWork = [
    'id' => $newId,
    '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' => $savedPhotos,
    'createdAt' => date('c'),
];

$works[] = $newWork;

// works.jsonに書き戻す
$jsonStr = json_encode($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;
