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"); } } // Gerar nome do 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 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 ]); } catch (Exception $e) { error_log("Erro ao salvar documento: " . $e->getMessage()); http_response_code(400); echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); } ?>