<!-- Author Raivis Rampāns
Created 07.06.2025
Editor Raivis
Modified 07.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']);
    $name = trim($_POST['name']);
    $description = trim($_POST['description']);

    if ($name === '') {
        // Varētu uzlikt kļūdas ziņu, bet šeit vienkārši atpakaļ
        header("Location: filelist.php");
        exit;
    }

    // Pārbauda, vai fails pieder lietotājam
    $checkSql = "SELECT f.id FROM files f
                 INNER JOIN file_users fu ON f.id = fu.files_id
                 WHERE f.id = ? AND fu.users_id = ?";
    $checkStmt = $conn->prepare($checkSql);
    $checkStmt->bind_param("ii", $fileId, $userId);
    $checkStmt->execute();
    $checkResult = $checkStmt->get_result();

    if ($checkResult->num_rows === 0) {
        // Failam nepieder šis lietotājs
        $checkStmt->close();
        $conn->close();
        header("Location: filelist.php");
        exit;
    }
    $checkStmt->close();

    // Atjauno faila info tabulā
    $updateSql = "UPDATE files SET name = ?, description = ? WHERE id = ?";
    $updateStmt = $conn->prepare($updateSql);
    $updateStmt->bind_param("ssi", $name, $description, $fileId);
    $updateStmt->execute();
    $updateStmt->close();
}

$conn->close();

// Pēc atjaunošanas atgriež lietotāju atpakaļ uz filelist.php
header("Location: filelist.php");
exit;