<?php
// uploader.php - Universal Uploader
$categories = [
    'images'    => ['name' => 'Images',     'folder' => 'assets/images/fulls',   'thumb_folder' => 'assets/images/thumbs'],
    'pdfs'      => ['name' => 'PDFs',       'folder' => 'assets/pdfs',           'thumb_folder' => 'assets/pdfs/thumbs'],
    'archives'  => ['name' => 'Archives',   'folder' => 'assets/archives',       'thumb_folder' => 'assets/archives/thumbs'],
    'media'     => ['name' => 'Media',      'folder' => 'assets/media/videos',   'thumb_folder' => 'assets/media/thumbs'],
    'projects'  => ['name' => 'Projects',   'folder' => 'assets/projects',       'isFolderBased' => true],
];

$message = '';

function loadJson($file) {
    if (file_exists($file)) return json_decode(file_get_contents($file), true) ?: [];
    return ['category' => '', 'totalItems' => 0, 'items' => []];
}

function saveJson($file, $data) {
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $catKey = $_POST['category'] ?? '';
    $type = $_POST['upload_type'] ?? 'file'; // file, stream, project

    if (!isset($categories[$catKey])) {
        $message = "Invalid category selected.";
    } else {
        $config = $categories[$catKey];
        $jsonFile = "data/{$catKey}.json";
        $data = loadJson($jsonFile);
        $data['category'] = $catKey;

        // ====================== FILE UPLOAD (Images, Videos, PDFs, Archives) ======================
        if ($type === 'file' && isset($_FILES['file'])) {
            $file = $_FILES['file'];
            if ($file['error'] === 0) {
                $filename = basename($file['name']);
                $title = trim($_POST['title'] ?? pathinfo($filename, PATHINFO_FILENAME));
                $uploadDir = $config['folder'] . '/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

                $targetPath = $uploadDir . $filename;

                if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                    $size = round(filesize($targetPath) / (1024*1024), 1) . ' MB';
                    $ext = strtoupper(pathinfo($filename, PATHINFO_EXTENSION));

                    $thumb = $config['thumb_folder'] . '/' . $filename;
                    if ($catKey === 'images' || $catKey === 'media') {
                        if (!is_dir($config['thumb_folder'])) mkdir($config['thumb_folder'], 0755, true);
                        // Simple thumbnail
                        if (function_exists('imagecreatefromstring')) {
                            $src = imagecreatefromstring(file_get_contents($targetPath));
                            $thumbImg = imagescale($src, 400);
                            imagejpeg($thumbImg, $thumb, 85);
                            imagedestroy($src); imagedestroy($thumbImg);
                        }
                    } else {
                        $thumb = "assets/archives/thumbs/default.png";
                    }

                    $newItem = [
                        "id" => substr($catKey, 0, 3) . '-' . str_pad(count($data['items']) + 1, 3, '0', STR_PAD_LEFT),
                        "title" => $title,
                        "slug" => strtolower(str_replace(' ', '-', $title)),
                        "location" => $targetPath,
                        "full" => $targetPath,
                        "thumb" => $thumb,
                        "size" => $size,
                        "format" => $ext,
                        "description" => $_POST['description'] ?? '',
                        "dateAdded" => date('Y-m-d')
                    ];

                    // Media specific fields
                    if ($catKey === 'media') {
                        $newItem['type'] = 'video';
                        $newItem['duration'] = $_POST['duration'] ?? '';
                        $newItem['isLive'] = false;
                    }

                    $data['items'][] = $newItem;
                    $data['totalItems'] = count($data['items']);
                    saveJson($jsonFile, $data);
                    $message = "✅ File uploaded and added to <strong>$catKey</strong> successfully!";
                }
            }
        }

        // ====================== ADD LIVE STREAM ======================
        elseif ($type === 'stream' && $catKey === 'media') {
            $title = trim($_POST['title']);
            $streamUrl = trim($_POST['stream_url']);

            if (!empty($title) && !empty($streamUrl)) {
                $newItem = [
                    "id" => "med-" . str_pad(count($data['items']) + 1, 3, '0', STR_PAD_LEFT),
                    "title" => $title,
                    "slug" => strtolower(str_replace(' ', '-', $title)),
                    "type" => "stream",
                    "location" => $streamUrl,
                    "full" => $streamUrl,
                    "thumb" => $_POST['thumb'] ?? 'assets/media/thumbs/default-live.jpg',
                    "size" => "Live",
                    "format" => "M3U8",
                    "duration" => "Live",
                    "description" => $_POST['description'] ?? '',
                    "homepage" => $_POST['homepage'] ?? '',
                    "isLive" => true,
                    "dateAdded" => date('Y-m-d')
                ];

                $data['items'][] = $newItem;
                $data['totalItems'] = count($data['items']);
                saveJson($jsonFile, $data);
                $message = "✅ Live stream added successfully!";
            }
        }

        // ====================== ADD PROJECT FROM FOLDER ======================
        elseif ($type === 'project' && $catKey === 'projects') {
            $projectFolder = trim($_POST['project_folder']);
            $title = trim($_POST['title']);

            if (is_dir($projectFolder)) {
                $folderName = basename($projectFolder);
                $newItem = [
                    "id" => "proj-" . str_pad(count($data['items']) + 1, 3, '0', STR_PAD_LEFT),
                    "title" => $title ?: ucwords(str_replace(['-', '_'], ' ', $folderName)),
                    "slug" => strtolower($folderName),
                    "folder" => rtrim($projectFolder, '/') . "/",
                    "mainImage" => $projectFolder . "/screenshot.jpg",
                    "thumb" => $projectFolder . "/thumb.jpg",
                    "description" => $_POST['description'] ?? '',
                    "homepage" => $_POST['homepage'] ?? '',
                    "technologies" => explode(',', $_POST['technologies'] ?? ''),
                    "status" => $_POST['status'] ?? 'Completed',
                    "dateAdded" => date('Y-m-d'),
                    "tags" => []
                ];

                $data['items'][] = $newItem;
                $data['totalItems'] = count($data['items']);
                saveJson($jsonFile, $data);
                $message = "✅ Project added from folder successfully!";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Universal Uploader</title>
  <style>
    body { font-family: Arial, sans-serif; background:#f4f4f4; margin:0; padding:20px; }
    .container { max-width: 900px; margin:auto; background:white; padding:30px; border-radius:12px; box-shadow:0 4px 15px rgba(0,0,0,0.1); }
    h1 { text-align:center; }
    .tabs { display:flex; gap:10px; margin-bottom:20px; }
    .tab { padding:10px 20px; background:#ddd; cursor:pointer; border-radius:6px; }
    .tab.active { background:#0066cc; color:white; }
    input, select, textarea { width:100%; padding:10px; margin:8px 0; }
    button { padding:12px 30px; background:#0066cc; color:white; border:none; border-radius:6px; cursor:pointer; }
    .message { padding:15px; background:#d4edda; color:#155724; border-radius:6px; margin:15px 0; }
  </style>
</head>
<body>
  <div class="container">
    <h1>Universal Content Uploader</h1>
    <?php if ($message) echo "<div class='message'>$message</div>"; ?>

    <div class="tabs">
      <div class="tab active" onclick="showTab(0)">📤 File Upload</div>
      <div class="tab" onclick="showTab(1)">📡 Live Stream</div>
      <div class="tab" onclick="showTab(2)">📁 Add Project</div>
    </div>

    <!-- Tab 1: File Upload -->
    <div id="tab0">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="upload_type" value="file">
        <label>Category</label>
        <select name="category" required>
          <?php foreach ($categories as $key => $c): ?>
            <option value="<?= $key ?>"><?= $c['name'] ?></option>
          <?php endforeach; ?>
        </select>

        <label>Select File</label>
        <input type="file" name="file" required>

        <label>Title</label>
        <input type="text" name="title" placeholder="Leave empty to use filename">

        <label>Description</label>
        <textarea name="description" rows="3"></textarea>

        <label>Duration (for videos)</label>
        <input type="text" name="duration" placeholder="e.g. 12:45">

        <button type="submit">Upload File</button>
      </form>
    </div>

    <!-- Tab 2: Live Stream -->
    <div id="tab1" style="display:none;">
      <form method="post">
        <input type="hidden" name="upload_type" value="stream">
        <input type="hidden" name="category" value="media">

        <label>Stream Title</label>
        <input type="text" name="title" required>

        <label>M3U8 Stream URL</label>
        <input type="url" name="stream_url" required placeholder="https://example.com/stream.m3u8">

        <label>Thumbnail URL</label>
        <input type="text" name="thumb" placeholder="assets/media/thumbs/stream.jpg">

        <label>Description</label>
        <textarea name="description" rows="3"></textarea>

        <label>Homepage / Source</label>
        <input type="text" name="homepage">

        <button type="submit">Add Live Stream</button>
      </form>
    </div>

    <!-- Tab 3: Add Project -->
    <div id="tab2" style="display:none;">
      <form method="post">
        <input type="hidden" name="upload_type" value="project">
        <input type="hidden" name="category" value="projects">

        <label>Project Folder (full path)</label>
        <input type="text" name="project_folder" value="assets/projects/your-project-name" required>

        <label>Project Title</label>
        <input type="text" name="title" placeholder="Will use folder name if empty">

        <label>Description</label>
        <textarea name="description" rows="4"></textarea>

        <label>Homepage / Demo URL</label>
        <input type="text" name="homepage">

        <label>Technologies (comma separated)</label>
        <input type="text" name="technologies" placeholder="React, Node.js, Tailwind">

        <label>Status</label>
        <select name="status">
          <option value="Completed">Completed</option>
          <option value="In Progress">In Progress</option>
        </select>

        <button type="submit">Add Project</button>
      </form>
    </div>
  </div>

  <script>
    function showTab(n) {
      document.querySelectorAll('.tab').forEach((t,i) => t.classList.toggle('active', i===n));
      document.getElementById('tab0').style.display = n===0 ? 'block' : 'none';
      document.getElementById('tab1').style.display = n===1 ? 'block' : 'none';
      document.getElementById('tab2').style.display = n===2 ? 'block' : 'none';
    }
  </script>
</body>
</html>