75 lines
2.0 KiB
PHP
75 lines
2.0 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
require_once 'config.php';
|
|
|
|
try {
|
|
// Verificar se recebeu os dados necessários
|
|
if (!isset($_POST['client_id']) || !isset($_FILES['image'])) {
|
|
throw new Exception("Dados incompletos");
|
|
}
|
|
|
|
$client_id = intval($_POST['client_id']);
|
|
$doc_type = $_POST['doc_type'];
|
|
|
|
// Verificar cliente
|
|
$stmt = $conn->prepare("SELECT id FROM clients WHERE id = ?");
|
|
$stmt->bind_param("i", $client_id);
|
|
$stmt->execute();
|
|
if (!$stmt->fetch()) {
|
|
throw new Exception("Cliente não encontrado");
|
|
}
|
|
|
|
// Criar diretório do cliente se não existir
|
|
$client_dir = "processed/{$client_id}/";
|
|
if (!file_exists($client_dir)) {
|
|
mkdir($client_dir, 0777, true);
|
|
}
|
|
|
|
// Gerar nome único para o arquivo
|
|
$timestamp = time();
|
|
$filename = sprintf(
|
|
'%s_%s_%s.jpg',
|
|
$doc_type,
|
|
$timestamp,
|
|
uniqid()
|
|
);
|
|
$filepath = $client_dir . $filename;
|
|
|
|
// Salvar arquivo
|
|
if (!move_uploaded_file($_FILES['image']['tmp_name'], $filepath)) {
|
|
throw new Exception("Erro ao salvar arquivo");
|
|
}
|
|
|
|
// Registrar no banco de dados
|
|
$stmt = $conn->prepare(
|
|
"INSERT INTO documentos (client_id, tipo, arquivo, data_upload)
|
|
VALUES (?, ?, ?, NOW())"
|
|
);
|
|
$stmt->bind_param("iss", $client_id, $doc_type, $filepath);
|
|
|
|
if (!$stmt->execute()) {
|
|
unlink($filepath); // Remove arquivo se falhar registro no banco
|
|
throw new Exception("Erro ao registrar documento: " . $stmt->error);
|
|
}
|
|
|
|
// Log de sucesso
|
|
error_log("Documento salvo: " . $filepath);
|
|
|
|
// Retornar sucesso
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Documento salvo com sucesso',
|
|
'file' => $filepath,
|
|
'id' => $conn->insert_id
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
error_log("Erro ao salvar documento: " . $e->getMessage());
|
|
http_response_code(400);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => $e->getMessage()
|
|
]);
|
|
}
|
|
?>
|