<?php
require_once __DIR__ . "/../auth/check-permission.php";
require_once __DIR__ . "/../services/db.php";

requireProjectRole($conn, $_POST["project_id"], ["owner", "member"]);

$uploadDir = __DIR__ . "/../../uploads/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$taskId   = $_POST["task_id"];
$file     = $_FILES["file"];

$fileName = $file["name"];
$tmpPath  = $file["tmp_name"];
$fileSize = $file["size"];
$mimeType = $file["type"];

$targetPath = $uploadDir . $fileName;

move_uploaded_file($tmpPath, $targetPath);

$sql = "INSERT INTO attachments
        (task_id, file_name, file_path, file_size, mime_type, uploaded_by)
        VALUES (?, ?, ?, ?, ?, ?)";
sqlsrv_query($conn, $sql, [
    $taskId,
    $fileName,
    $targetPath,
    $fileSize,
    $mimeType,
    $authUser["id"]
]);

echo json_encode([
    "success" => true,
    "file_name" => $fileName,
    "file_size" => $fileSize,
    "mime_type" => $mimeType
]);
