<!-- Author  Raivis Rampāns
Created 09.06.2025
Editor Raivis
Modified 09.06.2025 -->

<?php
session_start();
include "conn.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $userId = $_SESSION['user_id'];
    $fileId = intval($_POST["file_id"] ?? 0);
    $title = trim($_POST["title"] ?? '');
    $description = trim($_POST["description"] ?? '');
    $date = date("Y-m-d");
    $time = date("H:i:s");

    $thumbnail = null;
    if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === UPLOAD_ERR_OK) {
        $thumbnail = file_get_contents($_FILES['thumbnail']['tmp_name']);
    }

    // Pamatvalidācija
    if ($fileId <= 0 || $title === '' || $description === '') {
        header("Location: browse.php?error=missing");
        exit;
    }

    // Iegūst faila tekstu
    $stmt = $conn->prepare("SELECT text FROM files WHERE id = ?");
    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }
    $stmt->bind_param("i", $fileId);
    $stmt->execute();
    $stmt->bind_result($fileText);
    $stmt->fetch();
    $stmt->close();

    if (!$fileText) {
        header("Location: browse.php?error=file_not_found");
        exit;
    }

    // Saglabā publicēto failu
    $stmt = $conn->prepare("INSERT INTO published_files (user_id, file_id, title, description, text, thumbnail, date, time)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }
    $stmt->bind_param("iissssss", $userId, $fileId, $title, $description, $fileText, $thumbnail, $date, $time);

    if (!$stmt->execute()) {
        $error = $stmt->error;
        $stmt->close();
        die("Failed to insert published_file: $error");
    }

    $publishedId = $stmt->insert_id;
    $stmt->close();

    // === Apstrādā kategorijas ===
    if (!empty($_POST["categories"]) && is_array($_POST["categories"])) {
        foreach ($_POST["categories"] as $categoryName) {
            $categoryName = strtolower(trim($categoryName));
            if ($categoryName === "") continue;

            // 1. Pārbauda, vai kategorija jau eksistē
            $stmt = $conn->prepare("SELECT id FROM categories WHERE name = ?");
            if (!$stmt) {
                die("Prepare failed: " . $conn->error);
            }
            $stmt->bind_param("s", $categoryName);
            $stmt->execute();
            $stmt->bind_result($catId);
            $found = $stmt->fetch();
            $stmt->close();

            // 2. Ja nav – pievieno jaunu kategoriju
            if (!$found) {
                $stmt = $conn->prepare("INSERT INTO categories (name) VALUES (?)");
                if (!$stmt) {
                    die("Prepare failed: " . $conn->error);
                }
                $stmt->bind_param("s", $categoryName);
                if (!$stmt->execute()) {
                    die("Failed to insert category '$categoryName': " . $stmt->error);
                }
                $catId = $stmt->insert_id;
                $stmt->close();
            }

            // 3. Sasaista kategoriju ar publicēto failu
            if (!empty($catId)) {
                // Pārbauda, vai šī saistība jau eksistē
                $stmt = $conn->prepare("SELECT id FROM published_file_categories WHERE published_file_id = ? AND category_id = ?");
                if (!$stmt) {
                    die("Prepare failed: " . $conn->error);
                }
                $stmt->bind_param("ii", $publishedId, $catId);
                $stmt->execute();
                $stmt->bind_result($existingId);
                $exists = $stmt->fetch();
                $stmt->close();

                if (!$exists) {
                    $stmt = $conn->prepare("INSERT INTO published_file_categories (published_file_id, category_id) VALUES (?, ?)");
                    if (!$stmt) {
                        die("Prepare failed: " . $conn->error);
                    }
                    $stmt->bind_param("ii", $publishedId, $catId);
                    if (!$stmt->execute()) {
                        die("Failed to insert published_file_category: " . $stmt->error);
                    }
                    $stmt->close();
                }
            }
        }
    }

    header("Location: browse.php?success=1");
    exit;
}
?>