117 lines
3.2 KiB
PHP
117 lines
3.2 KiB
PHP
<?php
|
|
// Limpar qualquer saída anterior
|
|
ob_clean();
|
|
ob_start();
|
|
|
|
// Definir cabeçalhos
|
|
header('Content-Type: application/json');
|
|
header('X-Content-Type-Options: nosniff');
|
|
|
|
require_once 'config.php';
|
|
|
|
try {
|
|
// Reset de quaisquer resultados pendentes
|
|
while ($conn->next_result()) {
|
|
if ($res = $conn->store_result()) {
|
|
$res->free();
|
|
}
|
|
}
|
|
|
|
// Verificar dados do POST e FILES
|
|
if (!isset($_POST['client_id']) || !isset($_FILES['image'])) {
|
|
throw new Exception("Dados incompletos");
|
|
}
|
|
|
|
// Debug
|
|
error_log("POST data: " . print_r($_POST, true));
|
|
error_log("FILES data: " . print_r($_FILES, true));
|
|
|
|
$client_id = intval($_POST['client_id']);
|
|
$doc_type = $_POST['doc_type'];
|
|
|
|
// Verificar cliente com nova conexão
|
|
$check_client = $conn->prepare("SELECT id FROM clients WHERE id = ? LIMIT 1");
|
|
if (!$check_client) {
|
|
throw new Exception("Erro ao preparar consulta: " . $conn->error);
|
|
}
|
|
|
|
$check_client->bind_param("i", $client_id);
|
|
$check_client->execute();
|
|
$result = $check_client->get_result();
|
|
|
|
if ($result->num_rows === 0) {
|
|
throw new Exception("Cliente não encontrado");
|
|
}
|
|
$check_client->close();
|
|
|
|
// Criar diretório do cliente
|
|
$client_dir = "processed/{$client_id}/";
|
|
if (!file_exists($client_dir)) {
|
|
if (!mkdir($client_dir, 0777, true)) {
|
|
throw new Exception("Erro ao criar diretório");
|
|
}
|
|
}
|
|
|
|
// Verificar tipo do arquivo
|
|
$mime_type = $_FILES['image']['type'];
|
|
if ($mime_type !== 'application/pdf' && !strpos($mime_type, 'image/') === 0) {
|
|
throw new Exception("Tipo de arquivo não permitido");
|
|
}
|
|
|
|
// Gerar nome do arquivo sempre como PDF
|
|
$timestamp = time();
|
|
$filename = sprintf(
|
|
'%s_%s_%s.pdf',
|
|
$doc_type,
|
|
$timestamp,
|
|
uniqid()
|
|
);
|
|
$filepath = $client_dir . $filename;
|
|
|
|
// Se for imagem, converter para PDF
|
|
if (strpos($mime_type, 'image/') === 0) {
|
|
require_once 'vendor/autoload.php'; // Requer tecnickcom/tcpdf
|
|
$pdf = new TCPDF();
|
|
$pdf->AddPage();
|
|
$pdf->Image($_FILES['image']['tmp_name'], 0, 0, $pdf->getPageWidth(), $pdf->getPageHeight());
|
|
$pdf->Output($filepath, 'F');
|
|
} else {
|
|
// Se já for PDF, apenas mover
|
|
move_uploaded_file($_FILES['image']['tmp_name'], $filepath);
|
|
}
|
|
|
|
// Registrar no banco com nova preparação
|
|
$insert = $conn->prepare("INSERT INTO documentos (client_id, tipo, arquivo, data_upload) VALUES (?, ?, ?, NOW())");
|
|
if (!$insert) {
|
|
throw new Exception("Erro ao preparar inserção: " . $conn->error);
|
|
}
|
|
|
|
$insert->bind_param("iss", $client_id, $doc_type, $filepath);
|
|
|
|
if (!$insert->execute()) {
|
|
unlink($filepath);
|
|
throw new Exception("Erro ao registrar documento: " . $insert->error);
|
|
}
|
|
|
|
$doc_id = $insert->insert_id;
|
|
$insert->close();
|
|
|
|
// Retornar sucesso
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Documento salvo com sucesso',
|
|
'file' => $filepath,
|
|
'id' => $doc_id
|
|
]);
|
|
exit();
|
|
|
|
} catch (Exception $e) {
|
|
http_response_code(400);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => $e->getMessage()
|
|
]);
|
|
exit();
|
|
}
|
|
?>
|