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

<?php
session_start();
include "conn.php"; // Pievieno savienojumu ar datubāzi

if (!isset($_SESSION['user_id'])) {
    echo json_encode(["success" => false, "error" => "User not logged in."]);
    exit;
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $fileName = trim($_POST["fileName"]);
    $fileText = trim($_POST["fileText"]);
    $userId = $_SESSION['user_id']; // Lietotāja ID no sesijas
    $date = date("Y-m-d");
    $time = date("H:i:s");

    if (empty($fileName) || empty($fileText)) {
        echo json_encode(["success" => false, "error" => "File name or text is empty."]);
        exit;
    }

    // Ievieto failu tabulā
    $stmt = $conn->prepare("INSERT INTO files (name, text, date, time) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $fileName, $fileText, $date, $time);

    if ($stmt->execute()) {
        $fileId = $stmt->insert_id; // Iegūst jaunā faila ID
        $stmt->close();

        // Sasaista failu ar lietotāju
        $stmt2 = $conn->prepare("INSERT INTO file_users (files_id, users_id) VALUES (?, ?)");
        $stmt2->bind_param("ii", $fileId, $userId);
        $stmt2->execute();
        $stmt2->close();

        // Pāradresē lietotāju uz filelist.php pēc saglabāšanas
        header("Location: filelist.php");
        exit;
    } else {
        echo json_encode(["success" => false, "error" => "Database error."]);
    }
}
?>