Files
theloftstore/public/userarea/client_files_upload.php
T
2025-11-12 18:43:50 +01:00

99 lines
3.2 KiB
PHP

<?php
require_once(__DIR__ . '/class/db-functions.php');
use Dotenv\Dotenv;
header('Content-Type: application/json');
try {
$db = DBHandlerSelect::getInstance();
$pdo = $db->getConnection();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception("Invalid request method.");
}
$idclient = intval($_POST['idclient'] ?? 0);
$file_type = $_POST['file_type'] ?? '';
$uploaded_by = $_POST['uploaded_by'] ?? null; // opzionale
$notes = $_POST['notes'] ?? null;
if ($idclient <= 0 || empty($file_type) || !isset($_FILES['file'])) {
throw new Exception("Missing required parameters.");
}
// Cartella di upload
$uploadDir = __DIR__ . '/../uploads/client_files/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$file = $_FILES['file'];
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception("File upload error.");
}
$filename = time() . '_' . preg_replace('/[^A-Za-z0-9_.-]/', '_', basename($file['name']));
$targetPath = $uploadDir . $filename;
if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
throw new Exception("Failed to move uploaded file.");
}
// === 1️⃣ Inserisci nel DB senza source_id inizialmente ===
$stmt = $pdo->prepare("
INSERT INTO client_files (idclient, file_type, filename, uploaded_by, notes)
VALUES (:idclient, :file_type, :filename, :uploaded_by, :notes)
");
$stmt->execute([
':idclient' => $idclient,
':file_type' => $file_type,
':filename' => $filename,
':uploaded_by' => $uploaded_by,
':notes' => $notes
]);
$insertId = $pdo->lastInsertId();
// === 2️⃣ Upload verso ChatPDF ===
$dotenv = Dotenv::createImmutable(dirname(__DIR__, 2));
$dotenv->load();
$apiKey = $_ENV['CHATPDF_API_KEY'] ?? null;
if (!$apiKey) {
throw new Exception("ChatPDF API key not found in .env");
}
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.chatpdf.com/v1/sources/add-file",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["x-api-key: $apiKey"],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => [
"file" => new CURLFile($targetPath)
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) throw new Exception("ChatPDF API error: $err");
$json = json_decode($response, true);
$sourceId = $json['sourceId'] ?? null;
// === 3️⃣ Se ChatPDF restituisce un source_id, aggiorniamo il DB ===
if ($sourceId) {
$upd = $pdo->prepare("UPDATE client_files SET source_id = :source_id WHERE id = :id");
$upd->execute([':source_id' => $sourceId, ':id' => $insertId]);
$msg = "File uploaded and ChatPDF registered (sourceId: $sourceId)";
} else {
$msg = "File uploaded, but ChatPDF did not return a source ID. Response: " . json_encode($json);
}
echo json_encode(['status' => 'ok', 'message' => $msg, 'source_id' => $sourceId]);
} catch (Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}